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.

69557 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 98
  53. /** Current Juce version number.
  54. Bits 16 to 32 = major version.
  55. Bits 8 to 16 = minor version.
  56. Bits 0 to 8 = point release (not currently used).
  57. See also SystemStats::getJUCEVersion() for a string version.
  58. */
  59. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  60. /*** Start of inlined file: juce_TargetPlatform.h ***/
  61. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  62. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  63. /* This file figures out which platform is being built, and defines some macros
  64. that the rest of the code can use for OS-specific compilation.
  65. Macros that will be set here are:
  66. - One of JUCE_WINDOWS, JUCE_MAC JUCE_LINUX, JUCE_IOS, JUCE_ANDROID, etc.
  67. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  68. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  69. - Either JUCE_INTEL or JUCE_PPC
  70. - Either JUCE_GCC or JUCE_MSVC
  71. */
  72. #if (defined (_WIN32) || defined (_WIN64))
  73. #define JUCE_WIN32 1
  74. #define JUCE_WINDOWS 1
  75. #elif defined (JUCE_ANDROID)
  76. #undef JUCE_ANDROID
  77. #define JUCE_ANDROID 1
  78. #elif defined (LINUX) || defined (__linux__)
  79. #define JUCE_LINUX 1
  80. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  81. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  82. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  83. #define JUCE_IPHONE 1
  84. #define JUCE_IOS 1
  85. #else
  86. #define JUCE_MAC 1
  87. #endif
  88. #else
  89. #error "Unknown platform!"
  90. #endif
  91. #if JUCE_WINDOWS
  92. #ifdef _MSC_VER
  93. #ifdef _WIN64
  94. #define JUCE_64BIT 1
  95. #else
  96. #define JUCE_32BIT 1
  97. #endif
  98. #endif
  99. #ifdef _DEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __MINGW32__
  103. #define JUCE_MINGW 1
  104. #endif
  105. /** If defined, this indicates that the processor is little-endian. */
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #define JUCE_INTEL 1
  108. #endif
  109. #if JUCE_MAC || JUCE_IOS
  110. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  111. #define JUCE_DEBUG 1
  112. #endif
  113. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  114. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  115. #endif
  116. #ifdef __LITTLE_ENDIAN__
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #else
  119. #define JUCE_BIG_ENDIAN 1
  120. #endif
  121. #endif
  122. #if JUCE_MAC
  123. #if defined (__ppc__) || defined (__ppc64__)
  124. #define JUCE_PPC 1
  125. #else
  126. #define JUCE_INTEL 1
  127. #endif
  128. #ifdef __LP64__
  129. #define JUCE_64BIT 1
  130. #else
  131. #define JUCE_32BIT 1
  132. #endif
  133. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  134. #error "Building for OSX 10.3 is no longer supported!"
  135. #endif
  136. #ifndef MAC_OS_X_VERSION_10_5
  137. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  138. #endif
  139. #endif
  140. #if JUCE_LINUX || JUCE_ANDROID
  141. #ifdef _DEBUG
  142. #define JUCE_DEBUG 1
  143. #endif
  144. // Allow override for big-endian Linux platforms
  145. #if defined (__LITTLE_ENDIAN__) || ! defined (JUCE_BIG_ENDIAN)
  146. #define JUCE_LITTLE_ENDIAN 1
  147. #undef JUCE_BIG_ENDIAN
  148. #else
  149. #undef JUCE_LITTLE_ENDIAN
  150. #define JUCE_BIG_ENDIAN 1
  151. #endif
  152. #if defined (__LP64__) || defined (_LP64)
  153. #define JUCE_64BIT 1
  154. #else
  155. #define JUCE_32BIT 1
  156. #endif
  157. #if __MMX__ || __SSE__ || __amd64__
  158. #define JUCE_INTEL 1
  159. #endif
  160. #endif
  161. // Compiler type macros.
  162. #ifdef __GNUC__
  163. #define JUCE_GCC 1
  164. #elif defined (_MSC_VER)
  165. #define JUCE_MSVC 1
  166. #if _MSC_VER < 1500
  167. #define JUCE_VC8_OR_EARLIER 1
  168. #if _MSC_VER < 1400
  169. #define JUCE_VC7_OR_EARLIER 1
  170. #if _MSC_VER < 1300
  171. #define JUCE_VC6 1
  172. #endif
  173. #endif
  174. #endif
  175. #if ! JUCE_VC7_OR_EARLIER
  176. #define JUCE_USE_INTRINSICS 1
  177. #endif
  178. #else
  179. #error unknown compiler
  180. #endif
  181. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  182. /*** End of inlined file: juce_TargetPlatform.h ***/
  183. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  184. /*** Start of inlined file: juce_Config.h ***/
  185. #ifndef __JUCE_CONFIG_JUCEHEADER__
  186. #define __JUCE_CONFIG_JUCEHEADER__
  187. /*
  188. This file contains macros that enable/disable various JUCE features.
  189. */
  190. /** The name of the namespace that all Juce classes and functions will be
  191. put inside. If this is not defined, no namespace will be used.
  192. */
  193. #ifndef JUCE_NAMESPACE
  194. #define JUCE_NAMESPACE juce
  195. #endif
  196. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  197. project settings, but if you define this value, you can override this to force
  198. it to be true or false.
  199. */
  200. #ifndef JUCE_FORCE_DEBUG
  201. //#define JUCE_FORCE_DEBUG 0
  202. #endif
  203. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  204. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  205. Enabling it will also leave this turned on in release builds. When it's disabled,
  206. however, the jassert and jassertfalse macros will not be compiled in a
  207. release build.
  208. @see jassert, jassertfalse, Logger
  209. */
  210. #ifndef JUCE_LOG_ASSERTIONS
  211. #define JUCE_LOG_ASSERTIONS 0
  212. #endif
  213. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  214. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  215. on your Windows build machine.
  216. See the comments in the ASIOAudioIODevice class's header file for more
  217. info about this.
  218. */
  219. #ifndef JUCE_ASIO
  220. #define JUCE_ASIO 0
  221. #endif
  222. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  223. */
  224. #ifndef JUCE_WASAPI
  225. #define JUCE_WASAPI 0
  226. #endif
  227. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  228. */
  229. #ifndef JUCE_DIRECTSOUND
  230. #define JUCE_DIRECTSOUND 1
  231. #endif
  232. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  233. #ifndef JUCE_ALSA
  234. #define JUCE_ALSA 1
  235. #endif
  236. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  237. #ifndef JUCE_JACK
  238. #define JUCE_JACK 0
  239. #endif
  240. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  241. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  242. installed, and its header files will need to be on your include path.
  243. */
  244. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  245. #define JUCE_QUICKTIME 0
  246. #endif
  247. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  248. #undef JUCE_QUICKTIME
  249. #endif
  250. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  251. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  252. */
  253. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  254. #define JUCE_OPENGL 1
  255. #endif
  256. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  257. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  258. */
  259. #ifndef JUCE_DIRECT2D
  260. #define JUCE_DIRECT2D 0
  261. #endif
  262. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  263. If your app doesn't need to read FLAC files, you might want to disable this to
  264. reduce the size of your codebase and build time.
  265. */
  266. #ifndef JUCE_USE_FLAC
  267. #define JUCE_USE_FLAC 1
  268. #endif
  269. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  270. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  271. reduce the size of your codebase and build time.
  272. */
  273. #ifndef JUCE_USE_OGGVORBIS
  274. #define JUCE_USE_OGGVORBIS 1
  275. #endif
  276. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  277. Unless you're using CD-burning, you should probably turn this flag off to
  278. reduce code size.
  279. */
  280. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  281. #define JUCE_USE_CDBURNER 1
  282. #endif
  283. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  284. Unless you're using CD-reading, you should probably turn this flag off to
  285. reduce code size.
  286. */
  287. #ifndef JUCE_USE_CDREADER
  288. #define JUCE_USE_CDREADER 1
  289. #endif
  290. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  291. */
  292. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  293. #define JUCE_USE_CAMERA 0
  294. #endif
  295. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  296. gets repainted will flash in a random colour, so that you can check exactly how much and how
  297. often your components are being drawn.
  298. */
  299. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  300. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  301. #endif
  302. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  303. Unless you specifically want to disable this, it's best to leave this option turned on.
  304. */
  305. #ifndef JUCE_USE_XINERAMA
  306. #define JUCE_USE_XINERAMA 1
  307. #endif
  308. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  309. turned on unless you have a good reason to disable it.
  310. */
  311. #ifndef JUCE_USE_XSHM
  312. #define JUCE_USE_XSHM 1
  313. #endif
  314. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  315. */
  316. #ifndef JUCE_USE_XRENDER
  317. #define JUCE_USE_XRENDER 0
  318. #endif
  319. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  320. unless you have a good reason to disable it.
  321. */
  322. #ifndef JUCE_USE_XCURSOR
  323. #define JUCE_USE_XCURSOR 1
  324. #endif
  325. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  326. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  327. you're building a plugin hosting app.
  328. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  329. */
  330. #ifndef JUCE_PLUGINHOST_VST
  331. #define JUCE_PLUGINHOST_VST 0
  332. #endif
  333. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  334. of course, and should only be enabled if you're building a plugin hosting app.
  335. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  336. */
  337. #ifndef JUCE_PLUGINHOST_AU
  338. #define JUCE_PLUGINHOST_AU 0
  339. #endif
  340. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  341. This should be enabled if you're writing a console application.
  342. */
  343. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  344. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  345. #endif
  346. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  347. If you're not using any embedded web-pages, turning this off may reduce your code size.
  348. */
  349. #ifndef JUCE_WEB_BROWSER
  350. #define JUCE_WEB_BROWSER 1
  351. #endif
  352. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  353. Carbon isn't required for a normal app, but may be needed by specialised classes like
  354. plugin-hosts, which support older APIs.
  355. */
  356. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  357. #define JUCE_SUPPORT_CARBON 1
  358. #endif
  359. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  360. You might need to tweak this if you're linking to an external zlib library in your app,
  361. but for normal apps, this option should be left alone.
  362. */
  363. #ifndef JUCE_INCLUDE_ZLIB_CODE
  364. #define JUCE_INCLUDE_ZLIB_CODE 1
  365. #endif
  366. #ifndef JUCE_INCLUDE_FLAC_CODE
  367. #define JUCE_INCLUDE_FLAC_CODE 1
  368. #endif
  369. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  370. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  371. #endif
  372. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  373. #define JUCE_INCLUDE_PNGLIB_CODE 1
  374. #endif
  375. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  376. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  377. #endif
  378. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  379. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  380. macro for more details about enabling leak checking for specific classes.
  381. */
  382. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  383. #define JUCE_CHECK_MEMORY_LEAKS 1
  384. #endif
  385. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  386. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  387. are passed to the JUCEApplication::unhandledException() callback for logging.
  388. */
  389. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  390. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  391. #endif
  392. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  393. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  394. #undef JUCE_QUICKTIME
  395. #define JUCE_QUICKTIME 0
  396. #undef JUCE_OPENGL
  397. #define JUCE_OPENGL 0
  398. #undef JUCE_USE_CDBURNER
  399. #define JUCE_USE_CDBURNER 0
  400. #undef JUCE_USE_CDREADER
  401. #define JUCE_USE_CDREADER 0
  402. #undef JUCE_WEB_BROWSER
  403. #define JUCE_WEB_BROWSER 0
  404. #undef JUCE_PLUGINHOST_AU
  405. #define JUCE_PLUGINHOST_AU 0
  406. #undef JUCE_PLUGINHOST_VST
  407. #define JUCE_PLUGINHOST_VST 0
  408. #endif
  409. #endif
  410. /*** End of inlined file: juce_Config.h ***/
  411. #ifdef JUCE_NAMESPACE
  412. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  413. #define END_JUCE_NAMESPACE }
  414. #else
  415. #define BEGIN_JUCE_NAMESPACE
  416. #define END_JUCE_NAMESPACE
  417. #endif
  418. /*** Start of inlined file: juce_PlatformDefs.h ***/
  419. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  420. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  421. /* This file defines miscellaneous macros for debugging, assertions, etc.
  422. */
  423. #ifdef JUCE_FORCE_DEBUG
  424. #undef JUCE_DEBUG
  425. #if JUCE_FORCE_DEBUG
  426. #define JUCE_DEBUG 1
  427. #endif
  428. #endif
  429. /** This macro defines the C calling convention used as the standard for Juce calls. */
  430. #if JUCE_MSVC
  431. #define JUCE_CALLTYPE __stdcall
  432. #define JUCE_CDECL __cdecl
  433. #else
  434. #define JUCE_CALLTYPE
  435. #define JUCE_CDECL
  436. #endif
  437. // Debugging and assertion macros
  438. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  439. #if JUCE_LOG_ASSERTIONS
  440. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  441. #elif JUCE_DEBUG
  442. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  443. #else
  444. #define juce_LogCurrentAssertion
  445. #endif
  446. #if JUCE_MAC || DOXYGEN
  447. /** This will try to break into the debugger if the app is currently being debugged.
  448. If called by an app that's not being debugged, the behaiour isn't defined - it may crash or not, depending
  449. on the platform.
  450. @see jassert()
  451. */
  452. #define juce_breakDebugger { Debugger(); }
  453. #elif JUCE_IOS || JUCE_LINUX || JUCE_ANDROID
  454. #define juce_breakDebugger { kill (0, SIGTRAP); }
  455. #elif JUCE_USE_INTRINSICS
  456. #pragma intrinsic (__debugbreak)
  457. #define juce_breakDebugger { __debugbreak(); }
  458. #elif JUCE_GCC
  459. #define juce_breakDebugger { asm("int $3"); }
  460. #else
  461. #define juce_breakDebugger { __asm int 3 }
  462. #endif
  463. #if JUCE_DEBUG || DOXYGEN
  464. /** Writes a string to the standard error stream.
  465. This is only compiled in a debug build.
  466. @see Logger::outputDebugString
  467. */
  468. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  469. /** This will always cause an assertion failure.
  470. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled for your build).
  471. @see jassert
  472. */
  473. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  474. /** Platform-independent assertion macro.
  475. This macro gets turned into a no-op when you're building with debugging turned off, so be
  476. careful that the expression you pass to it doesn't perform any actions that are vital for the
  477. correct behaviour of your program!
  478. @see jassertfalse
  479. */
  480. #define jassert(expression) { if (! (expression)) jassertfalse; }
  481. #else
  482. // If debugging is disabled, these dummy debug and assertion macros are used..
  483. #define DBG(dbgtext)
  484. #define jassertfalse { juce_LogCurrentAssertion }
  485. #if JUCE_LOG_ASSERTIONS
  486. #define jassert(expression) { if (! (expression)) jassertfalse; }
  487. #else
  488. #define jassert(a) {}
  489. #endif
  490. #endif
  491. #ifndef DOXYGEN
  492. BEGIN_JUCE_NAMESPACE
  493. template <bool b> struct JuceStaticAssert;
  494. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  495. END_JUCE_NAMESPACE
  496. #endif
  497. /** A compile-time assertion macro.
  498. If the expression parameter is false, the macro will cause a compile error. (The actual error
  499. message that the compiler generates may be completely bizarre and seem to have no relation to
  500. the place where you put the static_assert though!)
  501. */
  502. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  503. /** This is a shorthand macro for declaring stubs for a class's copy constructor and operator=.
  504. For example, instead of
  505. @code
  506. class MyClass
  507. {
  508. etc..
  509. private:
  510. MyClass (const MyClass&);
  511. MyClass& operator= (const MyClass&);
  512. };@endcode
  513. ..you can just write:
  514. @code
  515. class MyClass
  516. {
  517. etc..
  518. private:
  519. JUCE_DECLARE_NON_COPYABLE (MyClass);
  520. };@endcode
  521. */
  522. #define JUCE_DECLARE_NON_COPYABLE(className) \
  523. className (const className&);\
  524. className& operator= (const className&)
  525. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  526. JUCE_LEAK_DETECTOR macro for a class.
  527. */
  528. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  529. JUCE_DECLARE_NON_COPYABLE(className);\
  530. JUCE_LEAK_DETECTOR(className)
  531. #if ! DOXYGEN
  532. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  533. #endif
  534. /** A good old-fashioned C macro concatenation helper.
  535. This combines two items (which may themselves be macros) into a single string,
  536. avoiding the pitfalls of the ## macro operator.
  537. */
  538. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  539. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  540. #define JUCE_TRY try
  541. #define JUCE_CATCH_ALL catch (...) {}
  542. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  543. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  544. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  545. #else
  546. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  547. object so they can be logged by the application if it wants to.
  548. */
  549. #define JUCE_CATCH_EXCEPTION \
  550. catch (const std::exception& e) \
  551. { \
  552. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  553. } \
  554. catch (...) \
  555. { \
  556. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  557. }
  558. #endif
  559. #else
  560. #define JUCE_TRY
  561. #define JUCE_CATCH_EXCEPTION
  562. #define JUCE_CATCH_ALL
  563. #define JUCE_CATCH_ALL_ASSERT
  564. #endif
  565. #if JUCE_DEBUG || DOXYGEN
  566. /** A platform-independent way of forcing an inline function.
  567. Use the syntax: @code
  568. forcedinline void myfunction (int x)
  569. @endcode
  570. */
  571. #define forcedinline inline
  572. #else
  573. #if JUCE_MSVC
  574. #define forcedinline __forceinline
  575. #else
  576. #define forcedinline inline __attribute__((always_inline))
  577. #endif
  578. #endif
  579. #if JUCE_MSVC || DOXYGEN
  580. /** This can be placed before a stack or member variable declaration to tell the compiler
  581. to align it to the specified number of bytes. */
  582. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  583. #else
  584. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  585. #endif
  586. // Cross-compiler deprecation macros..
  587. #if DOXYGEN || (JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS)
  588. /** This can be used to wrap a function which has been deprecated. */
  589. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  590. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  591. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  592. #else
  593. #define JUCE_DEPRECATED(functionDef) functionDef
  594. #endif
  595. #if JUCE_ANDROID && ! DOXYGEN
  596. #define JUCE_MODAL_LOOPS_PERMITTED 0
  597. #else
  598. /** Some operating environments don't provide a modal loop mechanism, so this flag can be
  599. used to disable any functions that try to run a modal loop. */
  600. #define JUCE_MODAL_LOOPS_PERMITTED 1
  601. #endif
  602. // Here, we'll check for C++2011 compiler support, and if it's not available, define
  603. // a few workarounds, so that we can still use a few of the newer language features.
  604. #if defined (__GXX_EXPERIMENTAL_CXX0X__) && defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  605. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  606. #endif
  607. #if defined (__clang__) && defined (__has_feature)
  608. #if __has_feature (cxx_noexcept) // (NB: do not add this test to the previous line)
  609. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  610. #endif
  611. #endif
  612. #if defined (_MSC_VER) && _MSC_VER >= 1600
  613. //#define JUCE_COMPILER_SUPPORTS_CXX2011 1
  614. #endif
  615. #if ! (DOXYGEN || JUCE_COMPILER_SUPPORTS_CXX2011)
  616. #define noexcept throw() // for c++98 compilers, we can fake these newer language features.
  617. #define nullptr (0)
  618. #endif
  619. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  620. /*** End of inlined file: juce_PlatformDefs.h ***/
  621. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  622. #if JUCE_MSVC
  623. #if JUCE_VC6
  624. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  625. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  626. {
  627. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  628. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  629. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  630. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  631. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  632. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  633. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  634. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  635. }
  636. #endif
  637. #pragma warning (push)
  638. #pragma warning (disable: 4514 4245 4100)
  639. #endif
  640. #include <cstdlib>
  641. #include <cstdarg>
  642. #include <climits>
  643. #include <limits>
  644. #include <cmath>
  645. #include <cwchar>
  646. #include <stdexcept>
  647. #include <typeinfo>
  648. #include <cstring>
  649. #include <cstdio>
  650. #include <iostream>
  651. #include <vector>
  652. #if JUCE_USE_INTRINSICS
  653. #include <intrin.h>
  654. #endif
  655. #if JUCE_MAC || JUCE_IOS
  656. #include <libkern/OSAtomic.h>
  657. #endif
  658. #if JUCE_LINUX
  659. #include <signal.h>
  660. #if __INTEL_COMPILER
  661. #if __ia64__
  662. #include <ia64intrin.h>
  663. #else
  664. #include <ia32intrin.h>
  665. #endif
  666. #endif
  667. #endif
  668. #if JUCE_MSVC && JUCE_DEBUG
  669. #include <crtdbg.h>
  670. #endif
  671. #if JUCE_MSVC
  672. #include <malloc.h>
  673. #pragma warning (pop)
  674. #if ! JUCE_PUBLIC_INCLUDES
  675. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  676. #endif
  677. #endif
  678. #if JUCE_ANDROID
  679. #include <sys/atomics.h>
  680. #include <byteswap.h>
  681. #endif
  682. // DLL building settings on Win32
  683. #if JUCE_MSVC
  684. #ifdef JUCE_DLL_BUILD
  685. #define JUCE_API __declspec (dllexport)
  686. #pragma warning (disable: 4251)
  687. #elif defined (JUCE_DLL)
  688. #define JUCE_API __declspec (dllimport)
  689. #pragma warning (disable: 4251)
  690. #endif
  691. #ifdef __INTEL_COMPILER
  692. #pragma warning (disable: 1125) // (virtual override warning)
  693. #endif
  694. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  695. #ifdef JUCE_DLL_BUILD
  696. #define JUCE_API __attribute__ ((visibility("default")))
  697. #endif
  698. #endif
  699. #ifndef JUCE_API
  700. /** This macro is added to all juce public class declarations. */
  701. #define JUCE_API
  702. #endif
  703. /** This macro is added to all juce public function declarations. */
  704. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  705. /** This turns on some non-essential bits of code that should prevent old code from compiling
  706. in cases where method signatures have changed, etc.
  707. */
  708. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  709. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  710. #endif
  711. // Now include some basics that are needed by most of the Juce classes...
  712. BEGIN_JUCE_NAMESPACE
  713. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  714. #if JUCE_LOG_ASSERTIONS
  715. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) noexcept;
  716. #endif
  717. /*** Start of inlined file: juce_Memory.h ***/
  718. #ifndef __JUCE_MEMORY_JUCEHEADER__
  719. #define __JUCE_MEMORY_JUCEHEADER__
  720. #if JUCE_MSVC || DOXYGEN
  721. /** This is a compiler-independent way of declaring a variable as being thread-local.
  722. E.g.
  723. @code
  724. juce_ThreadLocal int myVariable;
  725. @endcode
  726. */
  727. #define juce_ThreadLocal __declspec(thread)
  728. #else
  729. #define juce_ThreadLocal __thread
  730. #endif
  731. #if JUCE_MINGW
  732. /** This allocator is not defined in mingw gcc. */
  733. #define alloca __builtin_alloca
  734. #endif
  735. /** Fills a block of memory with zeros. */
  736. inline void zeromem (void* memory, size_t numBytes) noexcept { memset (memory, 0, numBytes); }
  737. /** Overwrites a structure or object with zeros. */
  738. template <typename Type>
  739. inline void zerostruct (Type& structure) noexcept { memset (&structure, 0, sizeof (structure)); }
  740. /** Delete an object pointer, and sets the pointer to null.
  741. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  742. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  743. */
  744. template <typename Type>
  745. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = nullptr; }
  746. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  747. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  748. a specific number of bytes,
  749. */
  750. template <typename Type>
  751. inline Type* addBytesToPointer (Type* pointer, int bytes) noexcept { return (Type*) (((char*) pointer) + bytes); }
  752. /** A handy function which returns the difference between any two pointers, in bytes.
  753. The address of the second pointer is subtracted from the first, and the difference in bytes is returned.
  754. */
  755. template <typename Type1, typename Type2>
  756. inline int getAddressDifference (Type1* pointer1, Type2* pointer2) noexcept { return (int) (((const char*) pointer1) - (const char*) pointer2); }
  757. /* In a win32 DLL build, we'll expose some malloc/free functions that live inside the DLL, and use these for
  758. allocating all the objects - that way all juce objects in the DLL and in the host will live in the same heap,
  759. avoiding problems when an object is created in one module and passed across to another where it is deleted.
  760. By piggy-backing on the JUCE_LEAK_DETECTOR macro, these allocators can be injected into most juce classes.
  761. */
  762. #if JUCE_MSVC && defined (JUCE_DLL) && ! DOXYGEN
  763. extern JUCE_API void* juceDLL_malloc (size_t);
  764. extern JUCE_API void juceDLL_free (void*);
  765. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  766. static void* operator new (size_t sz) { return JUCE_NAMESPACE::juceDLL_malloc ((int) sz); } \
  767. static void* operator new (size_t, void* p) { return p; } \
  768. static void operator delete (void* p) { JUCE_NAMESPACE::juceDLL_free (p); } \
  769. static void operator delete (void*, void*) {}
  770. #endif
  771. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  772. use the JUCE_LEAK_DETECTOR instead.
  773. */
  774. #ifndef juce_UseDebuggingNewOperator
  775. #define juce_UseDebuggingNewOperator
  776. #endif
  777. #endif // __JUCE_MEMORY_JUCEHEADER__
  778. /*** End of inlined file: juce_Memory.h ***/
  779. /*** Start of inlined file: juce_MathsFunctions.h ***/
  780. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  781. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  782. /*
  783. This file sets up some handy mathematical typdefs and functions.
  784. */
  785. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  786. /** A platform-independent 8-bit signed integer type. */
  787. typedef signed char int8;
  788. /** A platform-independent 8-bit unsigned integer type. */
  789. typedef unsigned char uint8;
  790. /** A platform-independent 16-bit signed integer type. */
  791. typedef signed short int16;
  792. /** A platform-independent 16-bit unsigned integer type. */
  793. typedef unsigned short uint16;
  794. /** A platform-independent 32-bit signed integer type. */
  795. typedef signed int int32;
  796. /** A platform-independent 32-bit unsigned integer type. */
  797. typedef unsigned int uint32;
  798. #if JUCE_MSVC
  799. /** A platform-independent 64-bit integer type. */
  800. typedef __int64 int64;
  801. /** A platform-independent 64-bit unsigned integer type. */
  802. typedef unsigned __int64 uint64;
  803. /** A platform-independent macro for writing 64-bit literals, needed because
  804. different compilers have different syntaxes for this.
  805. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  806. GCC, or 0x1000000000 for MSVC.
  807. */
  808. #define literal64bit(longLiteral) ((__int64) longLiteral)
  809. #else
  810. /** A platform-independent 64-bit integer type. */
  811. typedef long long int64;
  812. /** A platform-independent 64-bit unsigned integer type. */
  813. typedef unsigned long long uint64;
  814. /** A platform-independent macro for writing 64-bit literals, needed because
  815. different compilers have different syntaxes for this.
  816. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  817. GCC, or 0x1000000000 for MSVC.
  818. */
  819. #define literal64bit(longLiteral) (longLiteral##LL)
  820. #endif
  821. #if JUCE_64BIT
  822. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  823. typedef int64 pointer_sized_int;
  824. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  825. typedef uint64 pointer_sized_uint;
  826. #elif JUCE_MSVC && ! JUCE_VC6
  827. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  828. typedef _W64 int pointer_sized_int;
  829. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  830. typedef _W64 unsigned int pointer_sized_uint;
  831. #else
  832. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  833. typedef int pointer_sized_int;
  834. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  835. typedef unsigned int pointer_sized_uint;
  836. #endif
  837. // Some indispensible min/max functions
  838. /** Returns the larger of two values. */
  839. template <typename Type>
  840. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  841. /** Returns the larger of three values. */
  842. template <typename Type>
  843. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  844. /** Returns the larger of four values. */
  845. template <typename Type>
  846. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  847. /** Returns the smaller of two values. */
  848. template <typename Type>
  849. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  850. /** Returns the smaller of three values. */
  851. template <typename Type>
  852. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  853. /** Returns the smaller of four values. */
  854. template <typename Type>
  855. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  856. /** Scans an array of values, returning the minimum value that it contains. */
  857. template <typename Type>
  858. const Type findMinimum (const Type* data, int numValues)
  859. {
  860. if (numValues <= 0)
  861. return Type();
  862. Type result (*data++);
  863. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  864. {
  865. const Type& v = *data++;
  866. if (v < result) result = v;
  867. }
  868. return result;
  869. }
  870. /** Scans an array of values, returning the minimum value that it contains. */
  871. template <typename Type>
  872. const Type findMaximum (const Type* values, int numValues)
  873. {
  874. if (numValues <= 0)
  875. return Type();
  876. Type result (*values++);
  877. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  878. {
  879. const Type& v = *values++;
  880. if (result > v) result = v;
  881. }
  882. return result;
  883. }
  884. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  885. template <typename Type>
  886. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  887. {
  888. if (numValues <= 0)
  889. {
  890. lowest = Type();
  891. highest = Type();
  892. }
  893. else
  894. {
  895. Type mn (*values++);
  896. Type mx (mn);
  897. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  898. {
  899. const Type& v = *values++;
  900. if (mx < v) mx = v;
  901. if (v < mn) mn = v;
  902. }
  903. lowest = mn;
  904. highest = mx;
  905. }
  906. }
  907. /** Constrains a value to keep it within a given range.
  908. This will check that the specified value lies between the lower and upper bounds
  909. specified, and if not, will return the nearest value that would be in-range. Effectively,
  910. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  911. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  912. the results will be unpredictable.
  913. @param lowerLimit the minimum value to return
  914. @param upperLimit the maximum value to return
  915. @param valueToConstrain the value to try to return
  916. @returns the closest value to valueToConstrain which lies between lowerLimit
  917. and upperLimit (inclusive)
  918. @see jlimit0To, jmin, jmax
  919. */
  920. template <typename Type>
  921. inline Type jlimit (const Type lowerLimit,
  922. const Type upperLimit,
  923. const Type valueToConstrain) noexcept
  924. {
  925. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  926. return (valueToConstrain < lowerLimit) ? lowerLimit
  927. : ((upperLimit < valueToConstrain) ? upperLimit
  928. : valueToConstrain);
  929. }
  930. /** Returns true if a value is at least zero, and also below a specified upper limit.
  931. This is basically a quicker way to write:
  932. @code valueToTest >= 0 && valueToTest < upperLimit
  933. @endcode
  934. */
  935. template <typename Type>
  936. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  937. {
  938. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  939. return Type() <= valueToTest && valueToTest < upperLimit;
  940. }
  941. #if ! JUCE_VC6
  942. template <>
  943. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  944. {
  945. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  946. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  947. }
  948. #endif
  949. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  950. This is basically a quicker way to write:
  951. @code valueToTest >= 0 && valueToTest <= upperLimit
  952. @endcode
  953. */
  954. template <typename Type>
  955. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  956. {
  957. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  958. return Type() <= valueToTest && valueToTest <= upperLimit;
  959. }
  960. #if ! JUCE_VC6
  961. template <>
  962. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  963. {
  964. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  965. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  966. }
  967. #endif
  968. /** Handy function to swap two values. */
  969. template <typename Type>
  970. inline void swapVariables (Type& variable1, Type& variable2)
  971. {
  972. std::swap (variable1, variable2);
  973. }
  974. #if JUCE_VC6
  975. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  976. #else
  977. /** Handy function for getting the number of elements in a simple const C array.
  978. E.g.
  979. @code
  980. static int myArray[] = { 1, 2, 3 };
  981. int numElements = numElementsInArray (myArray) // returns 3
  982. @endcode
  983. */
  984. template <typename Type, int N>
  985. inline int numElementsInArray (Type (&array)[N])
  986. {
  987. (void) array; // (required to avoid a spurious warning in MS compilers)
  988. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  989. return N;
  990. }
  991. #endif
  992. // Some useful maths functions that aren't always present with all compilers and build settings.
  993. /** Using juce_hypot is easier than dealing with the different types of hypot function
  994. that are provided by the various platforms and compilers. */
  995. template <typename Type>
  996. inline Type juce_hypot (Type a, Type b) noexcept
  997. {
  998. #if JUCE_WINDOWS
  999. return static_cast <Type> (_hypot (a, b));
  1000. #else
  1001. return static_cast <Type> (hypot (a, b));
  1002. #endif
  1003. }
  1004. /** 64-bit abs function. */
  1005. inline int64 abs64 (const int64 n) noexcept
  1006. {
  1007. return (n >= 0) ? n : -n;
  1008. }
  1009. /** This templated negate function will negate pointers as well as integers */
  1010. template <typename Type>
  1011. inline Type juce_negate (Type n) noexcept
  1012. {
  1013. return sizeof (Type) == 1 ? (Type) -(signed char) n
  1014. : (sizeof (Type) == 2 ? (Type) -(short) n
  1015. : (sizeof (Type) == 4 ? (Type) -(int) n
  1016. : ((Type) -(int64) n)));
  1017. }
  1018. /** This templated negate function will negate pointers as well as integers */
  1019. template <typename Type>
  1020. inline Type* juce_negate (Type* n) noexcept
  1021. {
  1022. return (Type*) -(pointer_sized_int) n;
  1023. }
  1024. /** A predefined value for Pi, at double-precision.
  1025. @see float_Pi
  1026. */
  1027. const double double_Pi = 3.1415926535897932384626433832795;
  1028. /** A predefined value for Pi, at sngle-precision.
  1029. @see double_Pi
  1030. */
  1031. const float float_Pi = 3.14159265358979323846f;
  1032. /** The isfinite() method seems to vary between platforms, so this is a
  1033. platform-independent function for it.
  1034. */
  1035. template <typename FloatingPointType>
  1036. inline bool juce_isfinite (FloatingPointType value)
  1037. {
  1038. #if JUCE_WINDOWS
  1039. return _finite (value);
  1040. #elif JUCE_ANDROID
  1041. return isfinite (value);
  1042. #else
  1043. return std::isfinite (value);
  1044. #endif
  1045. }
  1046. /** Fast floating-point-to-integer conversion.
  1047. This is faster than using the normal c++ cast to convert a float to an int, and
  1048. it will round the value to the nearest integer, rather than rounding it down
  1049. like the normal cast does.
  1050. Note that this routine gets its speed at the expense of some accuracy, and when
  1051. rounding values whose floating point component is exactly 0.5, odd numbers and
  1052. even numbers will be rounded up or down differently.
  1053. */
  1054. template <typename FloatType>
  1055. inline int roundToInt (const FloatType value) noexcept
  1056. {
  1057. union { int asInt[2]; double asDouble; } n;
  1058. n.asDouble = ((double) value) + 6755399441055744.0;
  1059. #if JUCE_BIG_ENDIAN
  1060. return n.asInt [1];
  1061. #else
  1062. return n.asInt [0];
  1063. #endif
  1064. }
  1065. /** Fast floating-point-to-integer conversion.
  1066. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1067. fine for values above zero, but negative numbers are rounded the wrong way.
  1068. */
  1069. inline int roundToIntAccurate (const double value) noexcept
  1070. {
  1071. return roundToInt (value + 1.5e-8);
  1072. }
  1073. /** Fast floating-point-to-integer conversion.
  1074. This is faster than using the normal c++ cast to convert a double to an int, and
  1075. it will round the value to the nearest integer, rather than rounding it down
  1076. like the normal cast does.
  1077. Note that this routine gets its speed at the expense of some accuracy, and when
  1078. rounding values whose floating point component is exactly 0.5, odd numbers and
  1079. even numbers will be rounded up or down differently. For a more accurate conversion,
  1080. see roundDoubleToIntAccurate().
  1081. */
  1082. inline int roundDoubleToInt (const double value) noexcept
  1083. {
  1084. return roundToInt (value);
  1085. }
  1086. /** Fast floating-point-to-integer conversion.
  1087. This is faster than using the normal c++ cast to convert a float to an int, and
  1088. it will round the value to the nearest integer, rather than rounding it down
  1089. like the normal cast does.
  1090. Note that this routine gets its speed at the expense of some accuracy, and when
  1091. rounding values whose floating point component is exactly 0.5, odd numbers and
  1092. even numbers will be rounded up or down differently.
  1093. */
  1094. inline int roundFloatToInt (const float value) noexcept
  1095. {
  1096. return roundToInt (value);
  1097. }
  1098. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  1099. /** This macro can be applied to a float variable to check whether it contains a denormalised
  1100. value, and to normalise it if necessary.
  1101. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  1102. */
  1103. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  1104. #else
  1105. #define JUCE_UNDENORMALISE(x)
  1106. #endif
  1107. /** This namespace contains a few template classes for helping work out class type variations.
  1108. */
  1109. namespace TypeHelpers
  1110. {
  1111. #if JUCE_VC8_OR_EARLIER
  1112. #define PARAMETER_TYPE(type) const type&
  1113. #else
  1114. /** The ParameterType struct is used to find the best type to use when passing some kind
  1115. of object as a parameter.
  1116. Of course, this is only likely to be useful in certain esoteric template situations.
  1117. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1118. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1119. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1120. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1121. pass-by-value, but passing objects as a const reference, to avoid copying.
  1122. */
  1123. template <typename Type> struct ParameterType { typedef const Type& type; };
  1124. #if ! DOXYGEN
  1125. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1126. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1127. template <> struct ParameterType <char> { typedef char type; };
  1128. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1129. template <> struct ParameterType <short> { typedef short type; };
  1130. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1131. template <> struct ParameterType <int> { typedef int type; };
  1132. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1133. template <> struct ParameterType <long> { typedef long type; };
  1134. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1135. template <> struct ParameterType <int64> { typedef int64 type; };
  1136. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1137. template <> struct ParameterType <bool> { typedef bool type; };
  1138. template <> struct ParameterType <float> { typedef float type; };
  1139. template <> struct ParameterType <double> { typedef double type; };
  1140. #endif
  1141. /** A helpful macro to simplify the use of the ParameterType template.
  1142. @see ParameterType
  1143. */
  1144. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1145. #endif
  1146. }
  1147. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1148. /*** End of inlined file: juce_MathsFunctions.h ***/
  1149. /*** Start of inlined file: juce_ByteOrder.h ***/
  1150. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1151. #define __JUCE_BYTEORDER_JUCEHEADER__
  1152. /** Contains static methods for converting the byte order between different
  1153. endiannesses.
  1154. */
  1155. class JUCE_API ByteOrder
  1156. {
  1157. public:
  1158. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1159. static uint16 swap (uint16 value);
  1160. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1161. static uint32 swap (uint32 value);
  1162. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1163. static uint64 swap (uint64 value);
  1164. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1165. static uint16 swapIfBigEndian (uint16 value);
  1166. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1167. static uint32 swapIfBigEndian (uint32 value);
  1168. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1169. static uint64 swapIfBigEndian (uint64 value);
  1170. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1171. static uint16 swapIfLittleEndian (uint16 value);
  1172. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1173. static uint32 swapIfLittleEndian (uint32 value);
  1174. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1175. static uint64 swapIfLittleEndian (uint64 value);
  1176. /** Turns 4 bytes into a little-endian integer. */
  1177. static uint32 littleEndianInt (const void* bytes);
  1178. /** Turns 2 bytes into a little-endian integer. */
  1179. static uint16 littleEndianShort (const void* bytes);
  1180. /** Turns 4 bytes into a big-endian integer. */
  1181. static uint32 bigEndianInt (const void* bytes);
  1182. /** Turns 2 bytes into a big-endian integer. */
  1183. static uint16 bigEndianShort (const void* bytes);
  1184. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1185. static int littleEndian24Bit (const char* bytes);
  1186. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1187. static int bigEndian24Bit (const char* bytes);
  1188. /** Copies a 24-bit number to 3 little-endian bytes. */
  1189. static void littleEndian24BitToChars (int value, char* destBytes);
  1190. /** Copies a 24-bit number to 3 big-endian bytes. */
  1191. static void bigEndian24BitToChars (int value, char* destBytes);
  1192. /** Returns true if the current CPU is big-endian. */
  1193. static bool isBigEndian();
  1194. private:
  1195. ByteOrder();
  1196. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1197. };
  1198. #if JUCE_USE_INTRINSICS
  1199. #pragma intrinsic (_byteswap_ulong)
  1200. #endif
  1201. inline uint16 ByteOrder::swap (uint16 n)
  1202. {
  1203. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1204. return static_cast <uint16> (_byteswap_ushort (n));
  1205. #else
  1206. return static_cast <uint16> ((n << 8) | (n >> 8));
  1207. #endif
  1208. }
  1209. inline uint32 ByteOrder::swap (uint32 n)
  1210. {
  1211. #if JUCE_MAC || JUCE_IOS
  1212. return OSSwapInt32 (n);
  1213. #elif JUCE_GCC && JUCE_INTEL
  1214. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1215. return n;
  1216. #elif JUCE_USE_INTRINSICS
  1217. return _byteswap_ulong (n);
  1218. #elif JUCE_MSVC
  1219. __asm {
  1220. mov eax, n
  1221. bswap eax
  1222. mov n, eax
  1223. }
  1224. return n;
  1225. #elif JUCE_ANDROID
  1226. return bswap_32 (n);
  1227. #else
  1228. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1229. #endif
  1230. }
  1231. inline uint64 ByteOrder::swap (uint64 value)
  1232. {
  1233. #if JUCE_MAC || JUCE_IOS
  1234. return OSSwapInt64 (value);
  1235. #elif JUCE_USE_INTRINSICS
  1236. return _byteswap_uint64 (value);
  1237. #else
  1238. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1239. #endif
  1240. }
  1241. #if JUCE_LITTLE_ENDIAN
  1242. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1243. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1244. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1245. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1246. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1247. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1248. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1249. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1250. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1251. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1252. inline bool ByteOrder::isBigEndian() { return false; }
  1253. #else
  1254. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1255. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1256. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1257. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1258. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1259. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1260. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1261. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1262. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1263. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1264. inline bool ByteOrder::isBigEndian() { return true; }
  1265. #endif
  1266. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1267. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1268. 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); }
  1269. 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); }
  1270. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1271. /*** End of inlined file: juce_ByteOrder.h ***/
  1272. /*** Start of inlined file: juce_Logger.h ***/
  1273. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1274. #define __JUCE_LOGGER_JUCEHEADER__
  1275. /*** Start of inlined file: juce_String.h ***/
  1276. #ifndef __JUCE_STRING_JUCEHEADER__
  1277. #define __JUCE_STRING_JUCEHEADER__
  1278. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1279. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1280. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1281. #if JUCE_WINDOWS && ! DOXYGEN
  1282. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1283. #define JUCE_NATIVE_WCHAR_IS_UTF16 1
  1284. #define JUCE_NATIVE_WCHAR_IS_UTF32 0
  1285. #else
  1286. /** This macro will be set to 1 if the compiler's native wchar_t is an 8-bit type. */
  1287. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1288. /** This macro will be set to 1 if the compiler's native wchar_t is a 16-bit type. */
  1289. #define JUCE_NATIVE_WCHAR_IS_UTF16 0
  1290. /** This macro will be set to 1 if the compiler's native wchar_t is a 32-bit type. */
  1291. #define JUCE_NATIVE_WCHAR_IS_UTF32 1
  1292. #endif
  1293. #if JUCE_NATIVE_WCHAR_IS_UTF32 || DOXYGEN
  1294. /** A platform-independent 32-bit unicode character type. */
  1295. typedef wchar_t juce_wchar;
  1296. #else
  1297. typedef uint32 juce_wchar;
  1298. #endif
  1299. /** This macro is deprecated, but preserved for compatibility with old code.*/
  1300. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1301. #if ! JUCE_DONT_DEFINE_MACROS
  1302. /** The 'T' macro is an alternative for using the "L" prefix in front of a string literal.
  1303. This macro is deprectated, but kept here for compatibility with old code. The best (i.e.
  1304. most portable) way to encode your string literals is just as standard 8-bit strings, but
  1305. using escaped utf-8 character codes for extended characters.
  1306. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1307. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1308. the juce/src directory) to avoid defining this macro. See the comments in
  1309. juce_withoutMacros.h for more info.
  1310. */
  1311. #define T(stringLiteral) JUCE_T(stringLiteral)
  1312. #endif
  1313. #undef max
  1314. #undef min
  1315. /**
  1316. A set of methods for manipulating characters and character strings.
  1317. These are defined as wrappers around the basic C string handlers, to provide
  1318. a clean, cross-platform layer, (because various platforms differ in the
  1319. range of C library calls that they provide).
  1320. @see String
  1321. */
  1322. class JUCE_API CharacterFunctions
  1323. {
  1324. public:
  1325. static juce_wchar toUpperCase (juce_wchar character) noexcept;
  1326. static juce_wchar toLowerCase (juce_wchar character) noexcept;
  1327. static bool isUpperCase (juce_wchar character) noexcept;
  1328. static bool isLowerCase (juce_wchar character) noexcept;
  1329. static bool isWhitespace (char character) noexcept;
  1330. static bool isWhitespace (juce_wchar character) noexcept;
  1331. static bool isDigit (char character) noexcept;
  1332. static bool isDigit (juce_wchar character) noexcept;
  1333. static bool isLetter (char character) noexcept;
  1334. static bool isLetter (juce_wchar character) noexcept;
  1335. static bool isLetterOrDigit (char character) noexcept;
  1336. static bool isLetterOrDigit (juce_wchar character) noexcept;
  1337. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1338. static int getHexDigitValue (juce_wchar digit) noexcept;
  1339. template <typename CharPointerType>
  1340. static double readDoubleValue (CharPointerType& text) noexcept
  1341. {
  1342. double result[3] = { 0 }, accumulator[2] = { 0 };
  1343. int exponentAdjustment[2] = { 0 }, exponentAccumulator[2] = { -1, -1 };
  1344. int exponent = 0, decPointIndex = 0, digit = 0;
  1345. int lastDigit = 0, numSignificantDigits = 0;
  1346. bool isNegative = false, digitsFound = false;
  1347. const int maxSignificantDigits = 15 + 2;
  1348. text = text.findEndOfWhitespace();
  1349. juce_wchar c = *text;
  1350. switch (c)
  1351. {
  1352. case '-': isNegative = true; // fall-through..
  1353. case '+': c = *++text;
  1354. }
  1355. switch (c)
  1356. {
  1357. case 'n':
  1358. case 'N':
  1359. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1360. return std::numeric_limits<double>::quiet_NaN();
  1361. break;
  1362. case 'i':
  1363. case 'I':
  1364. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1365. return std::numeric_limits<double>::infinity();
  1366. break;
  1367. }
  1368. for (;;)
  1369. {
  1370. if (text.isDigit())
  1371. {
  1372. lastDigit = digit;
  1373. digit = text.getAndAdvance() - '0';
  1374. digitsFound = true;
  1375. if (decPointIndex != 0)
  1376. exponentAdjustment[1]++;
  1377. if (numSignificantDigits == 0 && digit == 0)
  1378. continue;
  1379. if (++numSignificantDigits > maxSignificantDigits)
  1380. {
  1381. if (digit > 5)
  1382. ++accumulator [decPointIndex];
  1383. else if (digit == 5 && (lastDigit & 1) != 0)
  1384. ++accumulator [decPointIndex];
  1385. if (decPointIndex > 0)
  1386. exponentAdjustment[1]--;
  1387. else
  1388. exponentAdjustment[0]++;
  1389. while (text.isDigit())
  1390. {
  1391. ++text;
  1392. if (decPointIndex == 0)
  1393. exponentAdjustment[0]++;
  1394. }
  1395. }
  1396. else
  1397. {
  1398. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1399. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1400. {
  1401. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1402. + accumulator [decPointIndex];
  1403. accumulator [decPointIndex] = 0;
  1404. exponentAccumulator [decPointIndex] = 0;
  1405. }
  1406. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1407. exponentAccumulator [decPointIndex]++;
  1408. }
  1409. }
  1410. else if (decPointIndex == 0 && *text == '.')
  1411. {
  1412. ++text;
  1413. decPointIndex = 1;
  1414. if (numSignificantDigits > maxSignificantDigits)
  1415. {
  1416. while (text.isDigit())
  1417. ++text;
  1418. break;
  1419. }
  1420. }
  1421. else
  1422. {
  1423. break;
  1424. }
  1425. }
  1426. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1427. if (decPointIndex != 0)
  1428. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1429. c = *text;
  1430. if ((c == 'e' || c == 'E') && digitsFound)
  1431. {
  1432. bool negativeExponent = false;
  1433. switch (*++text)
  1434. {
  1435. case '-': negativeExponent = true; // fall-through..
  1436. case '+': ++text;
  1437. }
  1438. while (text.isDigit())
  1439. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1440. if (negativeExponent)
  1441. exponent = -exponent;
  1442. }
  1443. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1444. if (decPointIndex != 0)
  1445. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1446. return isNegative ? -r : r;
  1447. }
  1448. template <typename CharPointerType>
  1449. static double getDoubleValue (const CharPointerType& text) noexcept
  1450. {
  1451. CharPointerType t (text);
  1452. return readDoubleValue (t);
  1453. }
  1454. template <typename IntType, typename CharPointerType>
  1455. static IntType getIntValue (const CharPointerType& text) noexcept
  1456. {
  1457. IntType v = 0;
  1458. CharPointerType s (text.findEndOfWhitespace());
  1459. const bool isNeg = *s == '-';
  1460. if (isNeg)
  1461. ++s;
  1462. for (;;)
  1463. {
  1464. const juce_wchar c = s.getAndAdvance();
  1465. if (c >= '0' && c <= '9')
  1466. v = v * 10 + (IntType) (c - '0');
  1467. else
  1468. break;
  1469. }
  1470. return isNeg ? -v : v;
  1471. }
  1472. template <typename CharPointerType>
  1473. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) noexcept
  1474. {
  1475. size_t len = 0;
  1476. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  1477. ++len;
  1478. return len;
  1479. }
  1480. template <typename CharPointerType>
  1481. static size_t lengthUpTo (CharPointerType start, const CharPointerType& end) noexcept
  1482. {
  1483. size_t len = 0;
  1484. while (start < end && start.getAndAdvance() != 0)
  1485. ++len;
  1486. return len;
  1487. }
  1488. template <typename DestCharPointerType, typename SrcCharPointerType>
  1489. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) noexcept
  1490. {
  1491. for (;;)
  1492. {
  1493. const juce_wchar c = src.getAndAdvance();
  1494. if (c == 0)
  1495. break;
  1496. dest.write (c);
  1497. }
  1498. dest.writeNull();
  1499. }
  1500. template <typename DestCharPointerType, typename SrcCharPointerType>
  1501. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) noexcept
  1502. {
  1503. typename DestCharPointerType::CharType const* const startAddress = dest.getAddress();
  1504. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1505. for (;;)
  1506. {
  1507. const juce_wchar c = src.getAndAdvance();
  1508. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1509. maxBytes -= bytesNeeded;
  1510. if (c == 0 || maxBytes < 0)
  1511. break;
  1512. dest.write (c);
  1513. }
  1514. dest.writeNull();
  1515. return getAddressDifference (dest.getAddress(), startAddress);
  1516. }
  1517. template <typename DestCharPointerType, typename SrcCharPointerType>
  1518. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) noexcept
  1519. {
  1520. while (--maxChars > 0)
  1521. {
  1522. const juce_wchar c = src.getAndAdvance();
  1523. if (c == 0)
  1524. break;
  1525. dest.write (c);
  1526. }
  1527. dest.writeNull();
  1528. }
  1529. template <typename CharPointerType1, typename CharPointerType2>
  1530. static int compare (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1531. {
  1532. for (;;)
  1533. {
  1534. const int c1 = (int) s1.getAndAdvance();
  1535. const int c2 = (int) s2.getAndAdvance();
  1536. const int diff = c1 - c2;
  1537. if (diff != 0)
  1538. return diff < 0 ? -1 : 1;
  1539. else if (c1 == 0)
  1540. break;
  1541. }
  1542. return 0;
  1543. }
  1544. template <typename CharPointerType1, typename CharPointerType2>
  1545. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1546. {
  1547. while (--maxChars >= 0)
  1548. {
  1549. const int c1 = (int) s1.getAndAdvance();
  1550. const int c2 = (int) s2.getAndAdvance();
  1551. const int diff = c1 - c2;
  1552. if (diff != 0)
  1553. return diff < 0 ? -1 : 1;
  1554. else if (c1 == 0)
  1555. break;
  1556. }
  1557. return 0;
  1558. }
  1559. template <typename CharPointerType1, typename CharPointerType2>
  1560. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1561. {
  1562. for (;;)
  1563. {
  1564. int c1 = s1.toUpperCase();
  1565. int c2 = s2.toUpperCase();
  1566. ++s1;
  1567. ++s2;
  1568. const int diff = c1 - c2;
  1569. if (diff != 0)
  1570. return diff < 0 ? -1 : 1;
  1571. else if (c1 == 0)
  1572. break;
  1573. }
  1574. return 0;
  1575. }
  1576. template <typename CharPointerType1, typename CharPointerType2>
  1577. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1578. {
  1579. while (--maxChars >= 0)
  1580. {
  1581. int c1 = s1.toUpperCase();
  1582. int c2 = s2.toUpperCase();
  1583. ++s1;
  1584. ++s2;
  1585. const int diff = c1 - c2;
  1586. if (diff != 0)
  1587. return diff < 0 ? -1 : 1;
  1588. else if (c1 == 0)
  1589. break;
  1590. }
  1591. return 0;
  1592. }
  1593. template <typename CharPointerType1, typename CharPointerType2>
  1594. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1595. {
  1596. int index = 0;
  1597. const int needleLength = (int) needle.length();
  1598. for (;;)
  1599. {
  1600. if (haystack.compareUpTo (needle, needleLength) == 0)
  1601. return index;
  1602. if (haystack.getAndAdvance() == 0)
  1603. return -1;
  1604. ++index;
  1605. }
  1606. }
  1607. template <typename CharPointerType1, typename CharPointerType2>
  1608. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1609. {
  1610. int index = 0;
  1611. const int needleLength = (int) needle.length();
  1612. for (;;)
  1613. {
  1614. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  1615. return index;
  1616. if (haystack.getAndAdvance() == 0)
  1617. return -1;
  1618. ++index;
  1619. }
  1620. }
  1621. template <typename Type>
  1622. static int indexOfChar (Type text, const juce_wchar charToFind) noexcept
  1623. {
  1624. int i = 0;
  1625. while (! text.isEmpty())
  1626. {
  1627. if (text.getAndAdvance() == charToFind)
  1628. return i;
  1629. ++i;
  1630. }
  1631. return -1;
  1632. }
  1633. template <typename Type>
  1634. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) noexcept
  1635. {
  1636. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1637. int i = 0;
  1638. while (! text.isEmpty())
  1639. {
  1640. if (text.toLowerCase() == charToFind)
  1641. return i;
  1642. ++text;
  1643. ++i;
  1644. }
  1645. return -1;
  1646. }
  1647. template <typename Type>
  1648. static Type findEndOfWhitespace (const Type& text) noexcept
  1649. {
  1650. Type p (text);
  1651. while (p.isWhitespace())
  1652. ++p;
  1653. return p;
  1654. }
  1655. template <typename Type>
  1656. static Type findEndOfToken (const Type& text, const Type& breakCharacters, const Type& quoteCharacters)
  1657. {
  1658. Type t (text);
  1659. juce_wchar currentQuoteChar = 0;
  1660. while (! t.isEmpty())
  1661. {
  1662. const juce_wchar c = t.getAndAdvance();
  1663. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  1664. {
  1665. --t;
  1666. break;
  1667. }
  1668. if (quoteCharacters.indexOf (c) >= 0)
  1669. {
  1670. if (currentQuoteChar == 0)
  1671. currentQuoteChar = c;
  1672. else if (currentQuoteChar == c)
  1673. currentQuoteChar = 0;
  1674. }
  1675. }
  1676. return t;
  1677. }
  1678. private:
  1679. static double mulexp10 (const double value, int exponent) noexcept;
  1680. };
  1681. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1682. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1683. #ifndef JUCE_STRING_UTF_TYPE
  1684. #define JUCE_STRING_UTF_TYPE 8
  1685. #endif
  1686. #if JUCE_MSVC
  1687. #pragma warning (push)
  1688. #pragma warning (disable: 4514 4996)
  1689. #endif
  1690. /*** Start of inlined file: juce_Atomic.h ***/
  1691. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1692. #define __JUCE_ATOMIC_JUCEHEADER__
  1693. /**
  1694. Simple class to hold a primitive value and perform atomic operations on it.
  1695. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1696. There are methods to perform most of the basic atomic operations.
  1697. */
  1698. template <typename Type>
  1699. class Atomic
  1700. {
  1701. public:
  1702. /** Creates a new value, initialised to zero. */
  1703. inline Atomic() noexcept
  1704. : value (0)
  1705. {
  1706. }
  1707. /** Creates a new value, with a given initial value. */
  1708. inline Atomic (const Type initialValue) noexcept
  1709. : value (initialValue)
  1710. {
  1711. }
  1712. /** Copies another value (atomically). */
  1713. inline Atomic (const Atomic& other) noexcept
  1714. : value (other.get())
  1715. {
  1716. }
  1717. /** Destructor. */
  1718. inline ~Atomic() noexcept
  1719. {
  1720. // This class can only be used for types which are 32 or 64 bits in size.
  1721. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1722. }
  1723. /** Atomically reads and returns the current value. */
  1724. Type get() const noexcept;
  1725. /** Copies another value onto this one (atomically). */
  1726. inline Atomic& operator= (const Atomic& other) noexcept { exchange (other.get()); return *this; }
  1727. /** Copies another value onto this one (atomically). */
  1728. inline Atomic& operator= (const Type newValue) noexcept { exchange (newValue); return *this; }
  1729. /** Atomically sets the current value. */
  1730. void set (Type newValue) noexcept { exchange (newValue); }
  1731. /** Atomically sets the current value, returning the value that was replaced. */
  1732. Type exchange (Type value) noexcept;
  1733. /** Atomically adds a number to this value, returning the new value. */
  1734. Type operator+= (Type amountToAdd) noexcept;
  1735. /** Atomically subtracts a number from this value, returning the new value. */
  1736. Type operator-= (Type amountToSubtract) noexcept;
  1737. /** Atomically increments this value, returning the new value. */
  1738. Type operator++() noexcept;
  1739. /** Atomically decrements this value, returning the new value. */
  1740. Type operator--() noexcept;
  1741. /** Atomically compares this value with a target value, and if it is equal, sets
  1742. this to be equal to a new value.
  1743. This operation is the atomic equivalent of doing this:
  1744. @code
  1745. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1746. {
  1747. if (get() == valueToCompare)
  1748. {
  1749. set (newValue);
  1750. return true;
  1751. }
  1752. return false;
  1753. }
  1754. @endcode
  1755. @returns true if the comparison was true and the value was replaced; false if
  1756. the comparison failed and the value was left unchanged.
  1757. @see compareAndSetValue
  1758. */
  1759. bool compareAndSetBool (Type newValue, Type valueToCompare) noexcept;
  1760. /** Atomically compares this value with a target value, and if it is equal, sets
  1761. this to be equal to a new value.
  1762. This operation is the atomic equivalent of doing this:
  1763. @code
  1764. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1765. {
  1766. Type oldValue = get();
  1767. if (oldValue == valueToCompare)
  1768. set (newValue);
  1769. return oldValue;
  1770. }
  1771. @endcode
  1772. @returns the old value before it was changed.
  1773. @see compareAndSetBool
  1774. */
  1775. Type compareAndSetValue (Type newValue, Type valueToCompare) noexcept;
  1776. /** Implements a memory read/write barrier. */
  1777. static void memoryBarrier() noexcept;
  1778. #if JUCE_64BIT
  1779. JUCE_ALIGN (8)
  1780. #else
  1781. JUCE_ALIGN (4)
  1782. #endif
  1783. /** The raw value that this class operates on.
  1784. This is exposed publically in case you need to manipulate it directly
  1785. for performance reasons.
  1786. */
  1787. volatile Type value;
  1788. private:
  1789. static inline Type castFrom32Bit (int32 value) noexcept { return *(Type*) &value; }
  1790. static inline Type castFrom64Bit (int64 value) noexcept { return *(Type*) &value; }
  1791. static inline int32 castTo32Bit (Type value) noexcept { return *(int32*) &value; }
  1792. static inline int64 castTo64Bit (Type value) noexcept { return *(int64*) &value; }
  1793. Type operator++ (int); // better to just use pre-increment with atomics..
  1794. Type operator-- (int);
  1795. };
  1796. /*
  1797. The following code is in the header so that the atomics can be inlined where possible...
  1798. */
  1799. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1800. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1801. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1802. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1803. #define JUCE_MAC_ATOMICS_VOLATILE
  1804. #else
  1805. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1806. #endif
  1807. #if JUCE_PPC || JUCE_IOS
  1808. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1809. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return *a += b; }
  1810. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return ++*a; }
  1811. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return --*a; }
  1812. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) noexcept
  1813. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1814. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1815. #endif
  1816. #elif JUCE_ANDROID
  1817. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1818. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1819. #elif JUCE_GCC
  1820. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1821. #if JUCE_IOS
  1822. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1823. #endif
  1824. #else
  1825. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1826. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1827. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1828. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1829. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1830. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1831. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1832. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1833. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1834. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1835. #define juce_MemoryBarrier _ReadWriteBarrier
  1836. #else
  1837. // (these are defined in juce_win32_Threads.cpp)
  1838. long juce_InterlockedExchange (volatile long* a, long b) noexcept;
  1839. long juce_InterlockedIncrement (volatile long* a) noexcept;
  1840. long juce_InterlockedDecrement (volatile long* a) noexcept;
  1841. long juce_InterlockedExchangeAdd (volatile long* a, long b) noexcept;
  1842. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) noexcept;
  1843. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) noexcept;
  1844. inline void juce_MemoryBarrier() noexcept { long x = 0; juce_InterlockedIncrement (&x); }
  1845. #endif
  1846. #if JUCE_64BIT
  1847. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1848. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1849. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1850. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1851. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1852. #else
  1853. // None of these atomics are available in a 32-bit Windows build!!
  1854. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a += b; return old; }
  1855. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a = b; return old; }
  1856. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) noexcept { jassertfalse; return ++*a; }
  1857. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) noexcept { jassertfalse; return --*a; }
  1858. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1859. #endif
  1860. #endif
  1861. #if JUCE_MSVC
  1862. #pragma warning (push)
  1863. #pragma warning (disable: 4311) // (truncation warning)
  1864. #endif
  1865. template <typename Type>
  1866. inline Type Atomic<Type>::get() const noexcept
  1867. {
  1868. #if JUCE_ATOMICS_MAC
  1869. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1870. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1871. #elif JUCE_ATOMICS_WINDOWS
  1872. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1873. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1874. #elif JUCE_ATOMICS_ANDROID
  1875. return value;
  1876. #elif JUCE_ATOMICS_GCC
  1877. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1878. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1879. #endif
  1880. }
  1881. template <typename Type>
  1882. inline Type Atomic<Type>::exchange (const Type newValue) noexcept
  1883. {
  1884. #if JUCE_ATOMICS_ANDROID
  1885. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1886. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1887. Type currentVal = value;
  1888. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1889. return currentVal;
  1890. #elif JUCE_ATOMICS_WINDOWS
  1891. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1892. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1893. #endif
  1894. }
  1895. template <typename Type>
  1896. inline Type Atomic<Type>::operator+= (const Type amountToAdd) noexcept
  1897. {
  1898. #if JUCE_ATOMICS_MAC
  1899. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1900. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1901. #elif JUCE_ATOMICS_WINDOWS
  1902. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1903. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1904. #elif JUCE_ATOMICS_ANDROID
  1905. for (;;)
  1906. {
  1907. const Type oldValue (value);
  1908. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1909. if (compareAndSetBool (newValue, oldValue))
  1910. return newValue;
  1911. }
  1912. #elif JUCE_ATOMICS_GCC
  1913. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1914. #endif
  1915. }
  1916. template <typename Type>
  1917. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) noexcept
  1918. {
  1919. return operator+= (juce_negate (amountToSubtract));
  1920. }
  1921. template <typename Type>
  1922. inline Type Atomic<Type>::operator++() noexcept
  1923. {
  1924. #if JUCE_ATOMICS_MAC
  1925. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1926. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1927. #elif JUCE_ATOMICS_WINDOWS
  1928. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1929. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1930. #elif JUCE_ATOMICS_ANDROID
  1931. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1932. #elif JUCE_ATOMICS_GCC
  1933. return (Type) __sync_add_and_fetch (&value, 1);
  1934. #endif
  1935. }
  1936. template <typename Type>
  1937. inline Type Atomic<Type>::operator--() noexcept
  1938. {
  1939. #if JUCE_ATOMICS_MAC
  1940. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1941. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1942. #elif JUCE_ATOMICS_WINDOWS
  1943. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1944. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1945. #elif JUCE_ATOMICS_ANDROID
  1946. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1947. #elif JUCE_ATOMICS_GCC
  1948. return (Type) __sync_add_and_fetch (&value, -1);
  1949. #endif
  1950. }
  1951. template <typename Type>
  1952. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) noexcept
  1953. {
  1954. #if JUCE_ATOMICS_MAC
  1955. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1956. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1957. #elif JUCE_ATOMICS_WINDOWS
  1958. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1959. #elif JUCE_ATOMICS_ANDROID
  1960. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1961. #elif JUCE_ATOMICS_GCC
  1962. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1963. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1964. #endif
  1965. }
  1966. template <typename Type>
  1967. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) noexcept
  1968. {
  1969. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  1970. for (;;) // Annoying workaround for only having a bool CAS operation..
  1971. {
  1972. if (compareAndSetBool (newValue, valueToCompare))
  1973. return valueToCompare;
  1974. const Type result = value;
  1975. if (result != valueToCompare)
  1976. return result;
  1977. }
  1978. #elif JUCE_ATOMICS_WINDOWS
  1979. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  1980. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  1981. #elif JUCE_ATOMICS_GCC
  1982. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  1983. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  1984. #endif
  1985. }
  1986. template <typename Type>
  1987. inline void Atomic<Type>::memoryBarrier() noexcept
  1988. {
  1989. #if JUCE_ATOMICS_MAC
  1990. OSMemoryBarrier();
  1991. #elif JUCE_ATOMICS_GCC
  1992. __sync_synchronize();
  1993. #elif JUCE_ATOMICS_WINDOWS
  1994. juce_MemoryBarrier();
  1995. #endif
  1996. }
  1997. #if JUCE_MSVC
  1998. #pragma warning (pop)
  1999. #endif
  2000. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2001. /*** End of inlined file: juce_Atomic.h ***/
  2002. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2003. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2004. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2005. /**
  2006. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2007. various methods to operate on the data.
  2008. @see CharPointer_UTF16, CharPointer_UTF32
  2009. */
  2010. class CharPointer_UTF8
  2011. {
  2012. public:
  2013. typedef char CharType;
  2014. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) noexcept
  2015. : data (const_cast <CharType*> (rawPointer))
  2016. {
  2017. }
  2018. inline CharPointer_UTF8 (const CharPointer_UTF8& other) noexcept
  2019. : data (other.data)
  2020. {
  2021. }
  2022. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) noexcept
  2023. {
  2024. data = other.data;
  2025. return *this;
  2026. }
  2027. inline CharPointer_UTF8& operator= (const CharType* text) noexcept
  2028. {
  2029. data = const_cast <CharType*> (text);
  2030. return *this;
  2031. }
  2032. /** This is a pointer comparison, it doesn't compare the actual text. */
  2033. inline bool operator== (const CharPointer_UTF8& other) const noexcept { return data == other.data; }
  2034. inline bool operator!= (const CharPointer_UTF8& other) const noexcept { return data != other.data; }
  2035. inline bool operator<= (const CharPointer_UTF8& other) const noexcept { return data <= other.data; }
  2036. inline bool operator< (const CharPointer_UTF8& other) const noexcept { return data < other.data; }
  2037. inline bool operator>= (const CharPointer_UTF8& other) const noexcept { return data >= other.data; }
  2038. inline bool operator> (const CharPointer_UTF8& other) const noexcept { return data > other.data; }
  2039. /** Returns the address that this pointer is pointing to. */
  2040. inline CharType* getAddress() const noexcept { return data; }
  2041. /** Returns the address that this pointer is pointing to. */
  2042. inline operator const CharType*() const noexcept { return data; }
  2043. /** Returns true if this pointer is pointing to a null character. */
  2044. inline bool isEmpty() const noexcept { return *data == 0; }
  2045. /** Returns the unicode character that this pointer is pointing to. */
  2046. juce_wchar operator*() const noexcept
  2047. {
  2048. const signed char byte = (signed char) *data;
  2049. if (byte >= 0)
  2050. return byte;
  2051. uint32 n = (uint32) (uint8) byte;
  2052. uint32 mask = 0x7f;
  2053. uint32 bit = 0x40;
  2054. size_t numExtraValues = 0;
  2055. while ((n & bit) != 0 && bit > 0x10)
  2056. {
  2057. mask >>= 1;
  2058. ++numExtraValues;
  2059. bit >>= 1;
  2060. }
  2061. n &= mask;
  2062. for (size_t i = 1; i <= numExtraValues; ++i)
  2063. {
  2064. const juce_wchar nextByte = data [i];
  2065. if ((nextByte & 0xc0) != 0x80)
  2066. break;
  2067. n <<= 6;
  2068. n |= (nextByte & 0x3f);
  2069. }
  2070. return (juce_wchar) n;
  2071. }
  2072. /** Moves this pointer along to the next character in the string. */
  2073. CharPointer_UTF8& operator++() noexcept
  2074. {
  2075. const signed char n = (signed char) *data++;
  2076. if (n < 0)
  2077. {
  2078. juce_wchar bit = 0x40;
  2079. while ((n & bit) != 0 && bit > 0x8)
  2080. {
  2081. ++data;
  2082. bit >>= 1;
  2083. }
  2084. }
  2085. return *this;
  2086. }
  2087. /** Moves this pointer back to the previous character in the string. */
  2088. CharPointer_UTF8& operator--() noexcept
  2089. {
  2090. const char n = *--data;
  2091. if ((n & 0xc0) == 0xc0)
  2092. {
  2093. int count = 3;
  2094. do
  2095. {
  2096. --data;
  2097. }
  2098. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2099. }
  2100. return *this;
  2101. }
  2102. /** Returns the character that this pointer is currently pointing to, and then
  2103. advances the pointer to point to the next character. */
  2104. juce_wchar getAndAdvance() noexcept
  2105. {
  2106. const signed char byte = (signed char) *data++;
  2107. if (byte >= 0)
  2108. return byte;
  2109. uint32 n = (uint32) (uint8) byte;
  2110. uint32 mask = 0x7f;
  2111. uint32 bit = 0x40;
  2112. int numExtraValues = 0;
  2113. while ((n & bit) != 0 && bit > 0x8)
  2114. {
  2115. mask >>= 1;
  2116. ++numExtraValues;
  2117. bit >>= 1;
  2118. }
  2119. n &= mask;
  2120. while (--numExtraValues >= 0)
  2121. {
  2122. const uint32 nextByte = (uint32) (uint8) *data++;
  2123. if ((nextByte & 0xc0) != 0x80)
  2124. break;
  2125. n <<= 6;
  2126. n |= (nextByte & 0x3f);
  2127. }
  2128. return (juce_wchar) n;
  2129. }
  2130. /** Moves this pointer along to the next character in the string. */
  2131. CharPointer_UTF8 operator++ (int) noexcept
  2132. {
  2133. CharPointer_UTF8 temp (*this);
  2134. ++*this;
  2135. return temp;
  2136. }
  2137. /** Moves this pointer forwards by the specified number of characters. */
  2138. void operator+= (int numToSkip) noexcept
  2139. {
  2140. if (numToSkip < 0)
  2141. {
  2142. while (++numToSkip <= 0)
  2143. --*this;
  2144. }
  2145. else
  2146. {
  2147. while (--numToSkip >= 0)
  2148. ++*this;
  2149. }
  2150. }
  2151. /** Moves this pointer backwards by the specified number of characters. */
  2152. void operator-= (int numToSkip) noexcept
  2153. {
  2154. operator+= (-numToSkip);
  2155. }
  2156. /** Returns the character at a given character index from the start of the string. */
  2157. juce_wchar operator[] (int characterIndex) const noexcept
  2158. {
  2159. CharPointer_UTF8 p (*this);
  2160. p += characterIndex;
  2161. return *p;
  2162. }
  2163. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2164. CharPointer_UTF8 operator+ (int numToSkip) const noexcept
  2165. {
  2166. CharPointer_UTF8 p (*this);
  2167. p += numToSkip;
  2168. return p;
  2169. }
  2170. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2171. CharPointer_UTF8 operator- (int numToSkip) const noexcept
  2172. {
  2173. CharPointer_UTF8 p (*this);
  2174. p += -numToSkip;
  2175. return p;
  2176. }
  2177. /** Returns the number of characters in this string. */
  2178. size_t length() const noexcept
  2179. {
  2180. const CharType* d = data;
  2181. size_t count = 0;
  2182. for (;;)
  2183. {
  2184. const uint32 n = (uint32) (uint8) *d++;
  2185. if ((n & 0x80) != 0)
  2186. {
  2187. uint32 bit = 0x40;
  2188. while ((n & bit) != 0)
  2189. {
  2190. ++d;
  2191. bit >>= 1;
  2192. if (bit == 0)
  2193. break; // illegal utf-8 sequence
  2194. }
  2195. }
  2196. else if (n == 0)
  2197. break;
  2198. ++count;
  2199. }
  2200. return count;
  2201. }
  2202. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2203. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2204. {
  2205. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2206. }
  2207. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2208. size_t lengthUpTo (const CharPointer_UTF8& end) const noexcept
  2209. {
  2210. return CharacterFunctions::lengthUpTo (*this, end);
  2211. }
  2212. /** Returns the number of bytes that are used to represent this string.
  2213. This includes the terminating null character.
  2214. */
  2215. size_t sizeInBytes() const noexcept
  2216. {
  2217. return strlen (data) + 1;
  2218. }
  2219. /** Returns the number of bytes that would be needed to represent the given
  2220. unicode character in this encoding format.
  2221. */
  2222. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2223. {
  2224. size_t num = 1;
  2225. const uint32 c = (uint32) charToWrite;
  2226. if (c >= 0x80)
  2227. {
  2228. ++num;
  2229. if (c >= 0x800)
  2230. {
  2231. ++num;
  2232. if (c >= 0x10000)
  2233. ++num;
  2234. }
  2235. }
  2236. return num;
  2237. }
  2238. /** Returns the number of bytes that would be needed to represent the given
  2239. string in this encoding format.
  2240. The value returned does NOT include the terminating null character.
  2241. */
  2242. template <class CharPointer>
  2243. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2244. {
  2245. size_t count = 0;
  2246. juce_wchar n;
  2247. while ((n = text.getAndAdvance()) != 0)
  2248. count += getBytesRequiredFor (n);
  2249. return count;
  2250. }
  2251. /** Returns a pointer to the null character that terminates this string. */
  2252. CharPointer_UTF8 findTerminatingNull() const noexcept
  2253. {
  2254. return CharPointer_UTF8 (data + strlen (data));
  2255. }
  2256. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2257. void write (const juce_wchar charToWrite) noexcept
  2258. {
  2259. const uint32 c = (uint32) charToWrite;
  2260. if (c >= 0x80)
  2261. {
  2262. int numExtraBytes = 1;
  2263. if (c >= 0x800)
  2264. {
  2265. ++numExtraBytes;
  2266. if (c >= 0x10000)
  2267. ++numExtraBytes;
  2268. }
  2269. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2270. while (--numExtraBytes >= 0)
  2271. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2272. }
  2273. else
  2274. {
  2275. *data++ = (CharType) c;
  2276. }
  2277. }
  2278. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2279. inline void writeNull() const noexcept
  2280. {
  2281. *data = 0;
  2282. }
  2283. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2284. template <typename CharPointer>
  2285. void writeAll (const CharPointer& src) noexcept
  2286. {
  2287. CharacterFunctions::copyAll (*this, src);
  2288. }
  2289. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2290. void writeAll (const CharPointer_UTF8& src) noexcept
  2291. {
  2292. const CharType* s = src.data;
  2293. while ((*data = *s) != 0)
  2294. {
  2295. ++data;
  2296. ++s;
  2297. }
  2298. }
  2299. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2300. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2301. to the destination buffer before stopping.
  2302. */
  2303. template <typename CharPointer>
  2304. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2305. {
  2306. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2307. }
  2308. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2309. The maxChars parameter specifies the maximum number of characters that can be
  2310. written to the destination buffer before stopping (including the terminating null).
  2311. */
  2312. template <typename CharPointer>
  2313. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2314. {
  2315. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2316. }
  2317. /** Compares this string with another one. */
  2318. template <typename CharPointer>
  2319. int compare (const CharPointer& other) const noexcept
  2320. {
  2321. return CharacterFunctions::compare (*this, other);
  2322. }
  2323. /** Compares this string with another one, up to a specified number of characters. */
  2324. template <typename CharPointer>
  2325. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2326. {
  2327. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2328. }
  2329. /** Compares this string with another one. */
  2330. template <typename CharPointer>
  2331. int compareIgnoreCase (const CharPointer& other) const noexcept
  2332. {
  2333. return CharacterFunctions::compareIgnoreCase (*this, other);
  2334. }
  2335. /** Compares this string with another one. */
  2336. int compareIgnoreCase (const CharPointer_UTF8& other) const noexcept
  2337. {
  2338. #if JUCE_WINDOWS
  2339. return stricmp (data, other.data);
  2340. #else
  2341. return strcasecmp (data, other.data);
  2342. #endif
  2343. }
  2344. /** Compares this string with another one, up to a specified number of characters. */
  2345. template <typename CharPointer>
  2346. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2347. {
  2348. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2349. }
  2350. /** Compares this string with another one, up to a specified number of characters. */
  2351. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const noexcept
  2352. {
  2353. #if JUCE_WINDOWS
  2354. return strnicmp (data, other.data, maxChars);
  2355. #else
  2356. return strncasecmp (data, other.data, maxChars);
  2357. #endif
  2358. }
  2359. /** Returns the character index of a substring, or -1 if it isn't found. */
  2360. template <typename CharPointer>
  2361. int indexOf (const CharPointer& stringToFind) const noexcept
  2362. {
  2363. return CharacterFunctions::indexOf (*this, stringToFind);
  2364. }
  2365. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2366. int indexOf (const juce_wchar charToFind) const noexcept
  2367. {
  2368. return CharacterFunctions::indexOfChar (*this, charToFind);
  2369. }
  2370. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2371. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2372. {
  2373. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2374. : CharacterFunctions::indexOfChar (*this, charToFind);
  2375. }
  2376. /** Returns true if the first character of this string is whitespace. */
  2377. bool isWhitespace() const noexcept { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2378. /** Returns true if the first character of this string is a digit. */
  2379. bool isDigit() const noexcept { return *data >= '0' && *data <= '9'; }
  2380. /** Returns true if the first character of this string is a letter. */
  2381. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2382. /** Returns true if the first character of this string is a letter or digit. */
  2383. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2384. /** Returns true if the first character of this string is upper-case. */
  2385. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2386. /** Returns true if the first character of this string is lower-case. */
  2387. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2388. /** Returns an upper-case version of the first character of this string. */
  2389. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2390. /** Returns a lower-case version of the first character of this string. */
  2391. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2392. /** Parses this string as a 32-bit integer. */
  2393. int getIntValue32() const noexcept { return atoi (data); }
  2394. /** Parses this string as a 64-bit integer. */
  2395. int64 getIntValue64() const noexcept
  2396. {
  2397. #if JUCE_LINUX || JUCE_ANDROID
  2398. return atoll (data);
  2399. #elif JUCE_WINDOWS
  2400. return _atoi64 (data);
  2401. #else
  2402. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2403. #endif
  2404. }
  2405. /** Parses this string as a floating point double. */
  2406. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2407. /** Returns the first non-whitespace character in the string. */
  2408. CharPointer_UTF8 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2409. /** Returns true if the given unicode character can be represented in this encoding. */
  2410. static bool canRepresent (juce_wchar character) noexcept
  2411. {
  2412. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2413. }
  2414. /** Returns true if this data contains a valid string in this encoding. */
  2415. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2416. {
  2417. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2418. {
  2419. const signed char byte = (signed char) *dataToTest;
  2420. if (byte < 0)
  2421. {
  2422. uint32 n = (uint32) (uint8) byte;
  2423. uint32 mask = 0x7f;
  2424. uint32 bit = 0x40;
  2425. int numExtraValues = 0;
  2426. while ((n & bit) != 0)
  2427. {
  2428. if (bit <= 0x10)
  2429. return false;
  2430. mask >>= 1;
  2431. ++numExtraValues;
  2432. bit >>= 1;
  2433. }
  2434. n &= mask;
  2435. while (--numExtraValues >= 0)
  2436. {
  2437. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2438. if ((nextByte & 0xc0) != 0x80)
  2439. return false;
  2440. }
  2441. }
  2442. }
  2443. return true;
  2444. }
  2445. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2446. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2447. {
  2448. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2449. }
  2450. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2451. enum
  2452. {
  2453. byteOrderMark1 = 0xef,
  2454. byteOrderMark2 = 0xbb,
  2455. byteOrderMark3 = 0xbf
  2456. };
  2457. private:
  2458. CharType* data;
  2459. };
  2460. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2461. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2462. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2463. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2464. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2465. /**
  2466. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2467. various methods to operate on the data.
  2468. @see CharPointer_UTF8, CharPointer_UTF32
  2469. */
  2470. class CharPointer_UTF16
  2471. {
  2472. public:
  2473. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2474. typedef wchar_t CharType;
  2475. #else
  2476. typedef int16 CharType;
  2477. #endif
  2478. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) noexcept
  2479. : data (const_cast <CharType*> (rawPointer))
  2480. {
  2481. }
  2482. inline CharPointer_UTF16 (const CharPointer_UTF16& other) noexcept
  2483. : data (other.data)
  2484. {
  2485. }
  2486. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) noexcept
  2487. {
  2488. data = other.data;
  2489. return *this;
  2490. }
  2491. inline CharPointer_UTF16& operator= (const CharType* text) noexcept
  2492. {
  2493. data = const_cast <CharType*> (text);
  2494. return *this;
  2495. }
  2496. /** This is a pointer comparison, it doesn't compare the actual text. */
  2497. inline bool operator== (const CharPointer_UTF16& other) const noexcept { return data == other.data; }
  2498. inline bool operator!= (const CharPointer_UTF16& other) const noexcept { return data != other.data; }
  2499. inline bool operator<= (const CharPointer_UTF16& other) const noexcept { return data <= other.data; }
  2500. inline bool operator< (const CharPointer_UTF16& other) const noexcept { return data < other.data; }
  2501. inline bool operator>= (const CharPointer_UTF16& other) const noexcept { return data >= other.data; }
  2502. inline bool operator> (const CharPointer_UTF16& other) const noexcept { return data > other.data; }
  2503. /** Returns the address that this pointer is pointing to. */
  2504. inline CharType* getAddress() const noexcept { return data; }
  2505. /** Returns the address that this pointer is pointing to. */
  2506. inline operator const CharType*() const noexcept { return data; }
  2507. /** Returns true if this pointer is pointing to a null character. */
  2508. inline bool isEmpty() const noexcept { return *data == 0; }
  2509. /** Returns the unicode character that this pointer is pointing to. */
  2510. juce_wchar operator*() const noexcept
  2511. {
  2512. uint32 n = (uint32) (uint16) *data;
  2513. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2514. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2515. return (juce_wchar) n;
  2516. }
  2517. /** Moves this pointer along to the next character in the string. */
  2518. CharPointer_UTF16& operator++() noexcept
  2519. {
  2520. const juce_wchar n = *data++;
  2521. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2522. ++data;
  2523. return *this;
  2524. }
  2525. /** Moves this pointer back to the previous character in the string. */
  2526. CharPointer_UTF16& operator--() noexcept
  2527. {
  2528. const juce_wchar n = *--data;
  2529. if (n >= 0xdc00 && n <= 0xdfff)
  2530. --data;
  2531. return *this;
  2532. }
  2533. /** Returns the character that this pointer is currently pointing to, and then
  2534. advances the pointer to point to the next character. */
  2535. juce_wchar getAndAdvance() noexcept
  2536. {
  2537. uint32 n = (uint32) (uint16) *data++;
  2538. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2539. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2540. return (juce_wchar) n;
  2541. }
  2542. /** Moves this pointer along to the next character in the string. */
  2543. CharPointer_UTF16 operator++ (int) noexcept
  2544. {
  2545. CharPointer_UTF16 temp (*this);
  2546. ++*this;
  2547. return temp;
  2548. }
  2549. /** Moves this pointer forwards by the specified number of characters. */
  2550. void operator+= (int numToSkip) noexcept
  2551. {
  2552. if (numToSkip < 0)
  2553. {
  2554. while (++numToSkip <= 0)
  2555. --*this;
  2556. }
  2557. else
  2558. {
  2559. while (--numToSkip >= 0)
  2560. ++*this;
  2561. }
  2562. }
  2563. /** Moves this pointer backwards by the specified number of characters. */
  2564. void operator-= (int numToSkip) noexcept
  2565. {
  2566. operator+= (-numToSkip);
  2567. }
  2568. /** Returns the character at a given character index from the start of the string. */
  2569. juce_wchar operator[] (const int characterIndex) const noexcept
  2570. {
  2571. CharPointer_UTF16 p (*this);
  2572. p += characterIndex;
  2573. return *p;
  2574. }
  2575. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2576. CharPointer_UTF16 operator+ (const int numToSkip) const noexcept
  2577. {
  2578. CharPointer_UTF16 p (*this);
  2579. p += numToSkip;
  2580. return p;
  2581. }
  2582. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2583. CharPointer_UTF16 operator- (const int numToSkip) const noexcept
  2584. {
  2585. CharPointer_UTF16 p (*this);
  2586. p += -numToSkip;
  2587. return p;
  2588. }
  2589. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2590. void write (juce_wchar charToWrite) noexcept
  2591. {
  2592. if (charToWrite >= 0x10000)
  2593. {
  2594. charToWrite -= 0x10000;
  2595. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2596. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2597. }
  2598. else
  2599. {
  2600. *data++ = (CharType) charToWrite;
  2601. }
  2602. }
  2603. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2604. inline void writeNull() const noexcept
  2605. {
  2606. *data = 0;
  2607. }
  2608. /** Returns the number of characters in this string. */
  2609. size_t length() const noexcept
  2610. {
  2611. const CharType* d = data;
  2612. size_t count = 0;
  2613. for (;;)
  2614. {
  2615. const int n = *d++;
  2616. if (n >= 0xd800 && n <= 0xdfff)
  2617. {
  2618. if (*d++ == 0)
  2619. break;
  2620. }
  2621. else if (n == 0)
  2622. break;
  2623. ++count;
  2624. }
  2625. return count;
  2626. }
  2627. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2628. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2629. {
  2630. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2631. }
  2632. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2633. size_t lengthUpTo (const CharPointer_UTF16& end) const noexcept
  2634. {
  2635. return CharacterFunctions::lengthUpTo (*this, end);
  2636. }
  2637. /** Returns the number of bytes that are used to represent this string.
  2638. This includes the terminating null character.
  2639. */
  2640. size_t sizeInBytes() const noexcept
  2641. {
  2642. return sizeof (CharType) * (findNullIndex (data) + 1);
  2643. }
  2644. /** Returns the number of bytes that would be needed to represent the given
  2645. unicode character in this encoding format.
  2646. */
  2647. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2648. {
  2649. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2650. }
  2651. /** Returns the number of bytes that would be needed to represent the given
  2652. string in this encoding format.
  2653. The value returned does NOT include the terminating null character.
  2654. */
  2655. template <class CharPointer>
  2656. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2657. {
  2658. size_t count = 0;
  2659. juce_wchar n;
  2660. while ((n = text.getAndAdvance()) != 0)
  2661. count += getBytesRequiredFor (n);
  2662. return count;
  2663. }
  2664. /** Returns a pointer to the null character that terminates this string. */
  2665. CharPointer_UTF16 findTerminatingNull() const noexcept
  2666. {
  2667. const CharType* t = data;
  2668. while (*t != 0)
  2669. ++t;
  2670. return CharPointer_UTF16 (t);
  2671. }
  2672. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2673. template <typename CharPointer>
  2674. void writeAll (const CharPointer& src) noexcept
  2675. {
  2676. CharacterFunctions::copyAll (*this, src);
  2677. }
  2678. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2679. void writeAll (const CharPointer_UTF16& src) noexcept
  2680. {
  2681. const CharType* s = src.data;
  2682. while ((*data = *s) != 0)
  2683. {
  2684. ++data;
  2685. ++s;
  2686. }
  2687. }
  2688. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2689. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2690. to the destination buffer before stopping.
  2691. */
  2692. template <typename CharPointer>
  2693. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2694. {
  2695. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2696. }
  2697. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2698. The maxChars parameter specifies the maximum number of characters that can be
  2699. written to the destination buffer before stopping (including the terminating null).
  2700. */
  2701. template <typename CharPointer>
  2702. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2703. {
  2704. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2705. }
  2706. /** Compares this string with another one. */
  2707. template <typename CharPointer>
  2708. int compare (const CharPointer& other) const noexcept
  2709. {
  2710. return CharacterFunctions::compare (*this, other);
  2711. }
  2712. /** Compares this string with another one, up to a specified number of characters. */
  2713. template <typename CharPointer>
  2714. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2715. {
  2716. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2717. }
  2718. /** Compares this string with another one. */
  2719. template <typename CharPointer>
  2720. int compareIgnoreCase (const CharPointer& other) const noexcept
  2721. {
  2722. return CharacterFunctions::compareIgnoreCase (*this, other);
  2723. }
  2724. /** Compares this string with another one, up to a specified number of characters. */
  2725. template <typename CharPointer>
  2726. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2727. {
  2728. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2729. }
  2730. #if JUCE_WINDOWS && ! DOXYGEN
  2731. int compareIgnoreCase (const CharPointer_UTF16& other) const noexcept
  2732. {
  2733. return _wcsicmp (data, other.data);
  2734. }
  2735. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const noexcept
  2736. {
  2737. return _wcsnicmp (data, other.data, maxChars);
  2738. }
  2739. int indexOf (const CharPointer_UTF16& stringToFind) const noexcept
  2740. {
  2741. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2742. return t == nullptr ? -1 : (int) (t - data);
  2743. }
  2744. #endif
  2745. /** Returns the character index of a substring, or -1 if it isn't found. */
  2746. template <typename CharPointer>
  2747. int indexOf (const CharPointer& stringToFind) const noexcept
  2748. {
  2749. return CharacterFunctions::indexOf (*this, stringToFind);
  2750. }
  2751. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2752. int indexOf (const juce_wchar charToFind) const noexcept
  2753. {
  2754. return CharacterFunctions::indexOfChar (*this, charToFind);
  2755. }
  2756. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2757. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2758. {
  2759. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2760. : CharacterFunctions::indexOfChar (*this, charToFind);
  2761. }
  2762. /** Returns true if the first character of this string is whitespace. */
  2763. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2764. /** Returns true if the first character of this string is a digit. */
  2765. bool isDigit() const noexcept { return CharacterFunctions::isDigit (operator*()) != 0; }
  2766. /** Returns true if the first character of this string is a letter. */
  2767. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2768. /** Returns true if the first character of this string is a letter or digit. */
  2769. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2770. /** Returns true if the first character of this string is upper-case. */
  2771. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2772. /** Returns true if the first character of this string is lower-case. */
  2773. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2774. /** Returns an upper-case version of the first character of this string. */
  2775. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2776. /** Returns a lower-case version of the first character of this string. */
  2777. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2778. /** Parses this string as a 32-bit integer. */
  2779. int getIntValue32() const noexcept
  2780. {
  2781. #if JUCE_WINDOWS
  2782. return _wtoi (data);
  2783. #else
  2784. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2785. #endif
  2786. }
  2787. /** Parses this string as a 64-bit integer. */
  2788. int64 getIntValue64() const noexcept
  2789. {
  2790. #if JUCE_WINDOWS
  2791. return _wtoi64 (data);
  2792. #else
  2793. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2794. #endif
  2795. }
  2796. /** Parses this string as a floating point double. */
  2797. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2798. /** Returns the first non-whitespace character in the string. */
  2799. CharPointer_UTF16 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2800. /** Returns true if the given unicode character can be represented in this encoding. */
  2801. static bool canRepresent (juce_wchar character) noexcept
  2802. {
  2803. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2804. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2805. }
  2806. /** Returns true if this data contains a valid string in this encoding. */
  2807. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2808. {
  2809. maxBytesToRead /= sizeof (CharType);
  2810. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2811. {
  2812. const uint32 n = (uint32) (uint16) *dataToTest++;
  2813. if (n >= 0xd800)
  2814. {
  2815. if (n > 0x10ffff)
  2816. return false;
  2817. if (n <= 0xdfff)
  2818. {
  2819. if (n > 0xdc00)
  2820. return false;
  2821. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2822. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2823. return false;
  2824. }
  2825. }
  2826. }
  2827. return true;
  2828. }
  2829. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2830. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2831. {
  2832. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2833. }
  2834. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2835. enum
  2836. {
  2837. byteOrderMarkBE1 = 0xfe,
  2838. byteOrderMarkBE2 = 0xff,
  2839. byteOrderMarkLE1 = 0xff,
  2840. byteOrderMarkLE2 = 0xfe
  2841. };
  2842. private:
  2843. CharType* data;
  2844. static int findNullIndex (const CharType* const t) noexcept
  2845. {
  2846. int n = 0;
  2847. while (t[n] != 0)
  2848. ++n;
  2849. return n;
  2850. }
  2851. };
  2852. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2853. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2854. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2855. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2856. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2857. /**
  2858. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2859. various methods to operate on the data.
  2860. @see CharPointer_UTF8, CharPointer_UTF16
  2861. */
  2862. class CharPointer_UTF32
  2863. {
  2864. public:
  2865. typedef juce_wchar CharType;
  2866. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) noexcept
  2867. : data (const_cast <CharType*> (rawPointer))
  2868. {
  2869. }
  2870. inline CharPointer_UTF32 (const CharPointer_UTF32& other) noexcept
  2871. : data (other.data)
  2872. {
  2873. }
  2874. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) noexcept
  2875. {
  2876. data = other.data;
  2877. return *this;
  2878. }
  2879. inline CharPointer_UTF32& operator= (const CharType* text) noexcept
  2880. {
  2881. data = const_cast <CharType*> (text);
  2882. return *this;
  2883. }
  2884. /** This is a pointer comparison, it doesn't compare the actual text. */
  2885. inline bool operator== (const CharPointer_UTF32& other) const noexcept { return data == other.data; }
  2886. inline bool operator!= (const CharPointer_UTF32& other) const noexcept { return data != other.data; }
  2887. inline bool operator<= (const CharPointer_UTF32& other) const noexcept { return data <= other.data; }
  2888. inline bool operator< (const CharPointer_UTF32& other) const noexcept { return data < other.data; }
  2889. inline bool operator>= (const CharPointer_UTF32& other) const noexcept { return data >= other.data; }
  2890. inline bool operator> (const CharPointer_UTF32& other) const noexcept { return data > other.data; }
  2891. /** Returns the address that this pointer is pointing to. */
  2892. inline CharType* getAddress() const noexcept { return data; }
  2893. /** Returns the address that this pointer is pointing to. */
  2894. inline operator const CharType*() const noexcept { return data; }
  2895. /** Returns true if this pointer is pointing to a null character. */
  2896. inline bool isEmpty() const noexcept { return *data == 0; }
  2897. /** Returns the unicode character that this pointer is pointing to. */
  2898. inline juce_wchar operator*() const noexcept { return *data; }
  2899. /** Moves this pointer along to the next character in the string. */
  2900. inline CharPointer_UTF32& operator++() noexcept
  2901. {
  2902. ++data;
  2903. return *this;
  2904. }
  2905. /** Moves this pointer to the previous character in the string. */
  2906. inline CharPointer_UTF32& operator--() noexcept
  2907. {
  2908. --data;
  2909. return *this;
  2910. }
  2911. /** Returns the character that this pointer is currently pointing to, and then
  2912. advances the pointer to point to the next character. */
  2913. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  2914. /** Moves this pointer along to the next character in the string. */
  2915. CharPointer_UTF32 operator++ (int) noexcept
  2916. {
  2917. CharPointer_UTF32 temp (*this);
  2918. ++data;
  2919. return temp;
  2920. }
  2921. /** Moves this pointer forwards by the specified number of characters. */
  2922. inline void operator+= (const int numToSkip) noexcept
  2923. {
  2924. data += numToSkip;
  2925. }
  2926. inline void operator-= (const int numToSkip) noexcept
  2927. {
  2928. data -= numToSkip;
  2929. }
  2930. /** Returns the character at a given character index from the start of the string. */
  2931. inline juce_wchar& operator[] (const int characterIndex) const noexcept
  2932. {
  2933. return data [characterIndex];
  2934. }
  2935. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2936. CharPointer_UTF32 operator+ (const int numToSkip) const noexcept
  2937. {
  2938. return CharPointer_UTF32 (data + numToSkip);
  2939. }
  2940. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2941. CharPointer_UTF32 operator- (const int numToSkip) const noexcept
  2942. {
  2943. return CharPointer_UTF32 (data - numToSkip);
  2944. }
  2945. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2946. inline void write (const juce_wchar charToWrite) noexcept
  2947. {
  2948. *data++ = charToWrite;
  2949. }
  2950. inline void replaceChar (const juce_wchar newChar) noexcept
  2951. {
  2952. *data = newChar;
  2953. }
  2954. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2955. inline void writeNull() const noexcept
  2956. {
  2957. *data = 0;
  2958. }
  2959. /** Returns the number of characters in this string. */
  2960. size_t length() const noexcept
  2961. {
  2962. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  2963. return wcslen (data);
  2964. #else
  2965. size_t n = 0;
  2966. while (data[n] != 0)
  2967. ++n;
  2968. return n;
  2969. #endif
  2970. }
  2971. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2972. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2973. {
  2974. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2975. }
  2976. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2977. size_t lengthUpTo (const CharPointer_UTF32& end) const noexcept
  2978. {
  2979. return CharacterFunctions::lengthUpTo (*this, end);
  2980. }
  2981. /** Returns the number of bytes that are used to represent this string.
  2982. This includes the terminating null character.
  2983. */
  2984. size_t sizeInBytes() const noexcept
  2985. {
  2986. return sizeof (CharType) * (length() + 1);
  2987. }
  2988. /** Returns the number of bytes that would be needed to represent the given
  2989. unicode character in this encoding format.
  2990. */
  2991. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  2992. {
  2993. return sizeof (CharType);
  2994. }
  2995. /** Returns the number of bytes that would be needed to represent the given
  2996. string in this encoding format.
  2997. The value returned does NOT include the terminating null character.
  2998. */
  2999. template <class CharPointer>
  3000. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3001. {
  3002. return sizeof (CharType) * text.length();
  3003. }
  3004. /** Returns a pointer to the null character that terminates this string. */
  3005. CharPointer_UTF32 findTerminatingNull() const noexcept
  3006. {
  3007. return CharPointer_UTF32 (data + length());
  3008. }
  3009. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3010. template <typename CharPointer>
  3011. void writeAll (const CharPointer& src) noexcept
  3012. {
  3013. CharacterFunctions::copyAll (*this, src);
  3014. }
  3015. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3016. void writeAll (const CharPointer_UTF32& src) noexcept
  3017. {
  3018. const CharType* s = src.data;
  3019. while ((*data = *s) != 0)
  3020. {
  3021. ++data;
  3022. ++s;
  3023. }
  3024. }
  3025. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3026. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3027. to the destination buffer before stopping.
  3028. */
  3029. template <typename CharPointer>
  3030. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3031. {
  3032. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3033. }
  3034. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3035. The maxChars parameter specifies the maximum number of characters that can be
  3036. written to the destination buffer before stopping (including the terminating null).
  3037. */
  3038. template <typename CharPointer>
  3039. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3040. {
  3041. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3042. }
  3043. /** Compares this string with another one. */
  3044. template <typename CharPointer>
  3045. int compare (const CharPointer& other) const noexcept
  3046. {
  3047. return CharacterFunctions::compare (*this, other);
  3048. }
  3049. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3050. /** Compares this string with another one. */
  3051. int compare (const CharPointer_UTF32& other) const noexcept
  3052. {
  3053. return wcscmp (data, other.data);
  3054. }
  3055. #endif
  3056. /** Compares this string with another one, up to a specified number of characters. */
  3057. template <typename CharPointer>
  3058. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3059. {
  3060. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3061. }
  3062. /** Compares this string with another one. */
  3063. template <typename CharPointer>
  3064. int compareIgnoreCase (const CharPointer& other) const
  3065. {
  3066. return CharacterFunctions::compareIgnoreCase (*this, other);
  3067. }
  3068. /** Compares this string with another one, up to a specified number of characters. */
  3069. template <typename CharPointer>
  3070. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3071. {
  3072. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3073. }
  3074. /** Returns the character index of a substring, or -1 if it isn't found. */
  3075. template <typename CharPointer>
  3076. int indexOf (const CharPointer& stringToFind) const noexcept
  3077. {
  3078. return CharacterFunctions::indexOf (*this, stringToFind);
  3079. }
  3080. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3081. int indexOf (const juce_wchar charToFind) const noexcept
  3082. {
  3083. int i = 0;
  3084. while (data[i] != 0)
  3085. {
  3086. if (data[i] == charToFind)
  3087. return i;
  3088. ++i;
  3089. }
  3090. return -1;
  3091. }
  3092. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3093. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3094. {
  3095. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3096. : CharacterFunctions::indexOfChar (*this, charToFind);
  3097. }
  3098. /** Returns true if the first character of this string is whitespace. */
  3099. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3100. /** Returns true if the first character of this string is a digit. */
  3101. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3102. /** Returns true if the first character of this string is a letter. */
  3103. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3104. /** Returns true if the first character of this string is a letter or digit. */
  3105. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3106. /** Returns true if the first character of this string is upper-case. */
  3107. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3108. /** Returns true if the first character of this string is lower-case. */
  3109. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3110. /** Returns an upper-case version of the first character of this string. */
  3111. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3112. /** Returns a lower-case version of the first character of this string. */
  3113. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3114. /** Parses this string as a 32-bit integer. */
  3115. int getIntValue32() const noexcept { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3116. /** Parses this string as a 64-bit integer. */
  3117. int64 getIntValue64() const noexcept { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3118. /** Parses this string as a floating point double. */
  3119. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3120. /** Returns the first non-whitespace character in the string. */
  3121. CharPointer_UTF32 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3122. /** Returns true if the given unicode character can be represented in this encoding. */
  3123. static bool canRepresent (juce_wchar character) noexcept
  3124. {
  3125. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3126. }
  3127. /** Returns true if this data contains a valid string in this encoding. */
  3128. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3129. {
  3130. maxBytesToRead /= sizeof (CharType);
  3131. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3132. if (! canRepresent (*dataToTest++))
  3133. return false;
  3134. return true;
  3135. }
  3136. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3137. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3138. {
  3139. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3140. }
  3141. private:
  3142. CharType* data;
  3143. };
  3144. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3145. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3146. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3147. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3148. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3149. /**
  3150. Wraps a pointer to a null-terminated ASCII character string, and provides
  3151. various methods to operate on the data.
  3152. A valid ASCII string is assumed to not contain any characters above 127.
  3153. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3154. */
  3155. class CharPointer_ASCII
  3156. {
  3157. public:
  3158. typedef char CharType;
  3159. inline explicit CharPointer_ASCII (const CharType* const rawPointer) noexcept
  3160. : data (const_cast <CharType*> (rawPointer))
  3161. {
  3162. }
  3163. inline CharPointer_ASCII (const CharPointer_ASCII& other) noexcept
  3164. : data (other.data)
  3165. {
  3166. }
  3167. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) noexcept
  3168. {
  3169. data = other.data;
  3170. return *this;
  3171. }
  3172. inline CharPointer_ASCII& operator= (const CharType* text) noexcept
  3173. {
  3174. data = const_cast <CharType*> (text);
  3175. return *this;
  3176. }
  3177. /** This is a pointer comparison, it doesn't compare the actual text. */
  3178. inline bool operator== (const CharPointer_ASCII& other) const noexcept { return data == other.data; }
  3179. inline bool operator!= (const CharPointer_ASCII& other) const noexcept { return data != other.data; }
  3180. inline bool operator<= (const CharPointer_ASCII& other) const noexcept { return data <= other.data; }
  3181. inline bool operator< (const CharPointer_ASCII& other) const noexcept { return data < other.data; }
  3182. inline bool operator>= (const CharPointer_ASCII& other) const noexcept { return data >= other.data; }
  3183. inline bool operator> (const CharPointer_ASCII& other) const noexcept { return data > other.data; }
  3184. /** Returns the address that this pointer is pointing to. */
  3185. inline CharType* getAddress() const noexcept { return data; }
  3186. /** Returns the address that this pointer is pointing to. */
  3187. inline operator const CharType*() const noexcept { return data; }
  3188. /** Returns true if this pointer is pointing to a null character. */
  3189. inline bool isEmpty() const noexcept { return *data == 0; }
  3190. /** Returns the unicode character that this pointer is pointing to. */
  3191. inline juce_wchar operator*() const noexcept { return *data; }
  3192. /** Moves this pointer along to the next character in the string. */
  3193. inline CharPointer_ASCII& operator++() noexcept
  3194. {
  3195. ++data;
  3196. return *this;
  3197. }
  3198. /** Moves this pointer to the previous character in the string. */
  3199. inline CharPointer_ASCII& operator--() noexcept
  3200. {
  3201. --data;
  3202. return *this;
  3203. }
  3204. /** Returns the character that this pointer is currently pointing to, and then
  3205. advances the pointer to point to the next character. */
  3206. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  3207. /** Moves this pointer along to the next character in the string. */
  3208. CharPointer_ASCII operator++ (int) noexcept
  3209. {
  3210. CharPointer_ASCII temp (*this);
  3211. ++data;
  3212. return temp;
  3213. }
  3214. /** Moves this pointer forwards by the specified number of characters. */
  3215. inline void operator+= (const int numToSkip) noexcept
  3216. {
  3217. data += numToSkip;
  3218. }
  3219. inline void operator-= (const int numToSkip) noexcept
  3220. {
  3221. data -= numToSkip;
  3222. }
  3223. /** Returns the character at a given character index from the start of the string. */
  3224. inline juce_wchar operator[] (const int characterIndex) const noexcept
  3225. {
  3226. return (juce_wchar) (unsigned char) data [characterIndex];
  3227. }
  3228. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3229. CharPointer_ASCII operator+ (const int numToSkip) const noexcept
  3230. {
  3231. return CharPointer_ASCII (data + numToSkip);
  3232. }
  3233. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3234. CharPointer_ASCII operator- (const int numToSkip) const noexcept
  3235. {
  3236. return CharPointer_ASCII (data - numToSkip);
  3237. }
  3238. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3239. inline void write (const juce_wchar charToWrite) noexcept
  3240. {
  3241. *data++ = (char) charToWrite;
  3242. }
  3243. inline void replaceChar (const juce_wchar newChar) noexcept
  3244. {
  3245. *data = (char) newChar;
  3246. }
  3247. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3248. inline void writeNull() const noexcept
  3249. {
  3250. *data = 0;
  3251. }
  3252. /** Returns the number of characters in this string. */
  3253. size_t length() const noexcept
  3254. {
  3255. return (size_t) strlen (data);
  3256. }
  3257. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3258. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3259. {
  3260. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3261. }
  3262. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3263. size_t lengthUpTo (const CharPointer_ASCII& end) const noexcept
  3264. {
  3265. return CharacterFunctions::lengthUpTo (*this, end);
  3266. }
  3267. /** Returns the number of bytes that are used to represent this string.
  3268. This includes the terminating null character.
  3269. */
  3270. size_t sizeInBytes() const noexcept
  3271. {
  3272. return length() + 1;
  3273. }
  3274. /** Returns the number of bytes that would be needed to represent the given
  3275. unicode character in this encoding format.
  3276. */
  3277. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3278. {
  3279. return 1;
  3280. }
  3281. /** Returns the number of bytes that would be needed to represent the given
  3282. string in this encoding format.
  3283. The value returned does NOT include the terminating null character.
  3284. */
  3285. template <class CharPointer>
  3286. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3287. {
  3288. return text.length();
  3289. }
  3290. /** Returns a pointer to the null character that terminates this string. */
  3291. CharPointer_ASCII findTerminatingNull() const noexcept
  3292. {
  3293. return CharPointer_ASCII (data + length());
  3294. }
  3295. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3296. template <typename CharPointer>
  3297. void writeAll (const CharPointer& src) noexcept
  3298. {
  3299. CharacterFunctions::copyAll (*this, src);
  3300. }
  3301. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3302. void writeAll (const CharPointer_ASCII& src) noexcept
  3303. {
  3304. strcpy (data, src.data);
  3305. }
  3306. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3307. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3308. to the destination buffer before stopping.
  3309. */
  3310. template <typename CharPointer>
  3311. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3312. {
  3313. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3314. }
  3315. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3316. The maxChars parameter specifies the maximum number of characters that can be
  3317. written to the destination buffer before stopping (including the terminating null).
  3318. */
  3319. template <typename CharPointer>
  3320. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3321. {
  3322. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3323. }
  3324. /** Compares this string with another one. */
  3325. template <typename CharPointer>
  3326. int compare (const CharPointer& other) const noexcept
  3327. {
  3328. return CharacterFunctions::compare (*this, other);
  3329. }
  3330. /** Compares this string with another one. */
  3331. int compare (const CharPointer_ASCII& other) const noexcept
  3332. {
  3333. return strcmp (data, other.data);
  3334. }
  3335. /** Compares this string with another one, up to a specified number of characters. */
  3336. template <typename CharPointer>
  3337. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3338. {
  3339. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3340. }
  3341. /** Compares this string with another one, up to a specified number of characters. */
  3342. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const noexcept
  3343. {
  3344. return strncmp (data, other.data, (size_t) maxChars);
  3345. }
  3346. /** Compares this string with another one. */
  3347. template <typename CharPointer>
  3348. int compareIgnoreCase (const CharPointer& other) const
  3349. {
  3350. return CharacterFunctions::compareIgnoreCase (*this, other);
  3351. }
  3352. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3353. {
  3354. #if JUCE_WINDOWS
  3355. return stricmp (data, other.data);
  3356. #else
  3357. return strcasecmp (data, other.data);
  3358. #endif
  3359. }
  3360. /** Compares this string with another one, up to a specified number of characters. */
  3361. template <typename CharPointer>
  3362. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3363. {
  3364. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3365. }
  3366. /** Returns the character index of a substring, or -1 if it isn't found. */
  3367. template <typename CharPointer>
  3368. int indexOf (const CharPointer& stringToFind) const noexcept
  3369. {
  3370. return CharacterFunctions::indexOf (*this, stringToFind);
  3371. }
  3372. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3373. int indexOf (const juce_wchar charToFind) const noexcept
  3374. {
  3375. int i = 0;
  3376. while (data[i] != 0)
  3377. {
  3378. if (data[i] == (char) charToFind)
  3379. return i;
  3380. ++i;
  3381. }
  3382. return -1;
  3383. }
  3384. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3385. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3386. {
  3387. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3388. : CharacterFunctions::indexOfChar (*this, charToFind);
  3389. }
  3390. /** Returns true if the first character of this string is whitespace. */
  3391. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3392. /** Returns true if the first character of this string is a digit. */
  3393. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3394. /** Returns true if the first character of this string is a letter. */
  3395. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3396. /** Returns true if the first character of this string is a letter or digit. */
  3397. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3398. /** Returns true if the first character of this string is upper-case. */
  3399. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3400. /** Returns true if the first character of this string is lower-case. */
  3401. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3402. /** Returns an upper-case version of the first character of this string. */
  3403. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3404. /** Returns a lower-case version of the first character of this string. */
  3405. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3406. /** Parses this string as a 32-bit integer. */
  3407. int getIntValue32() const noexcept { return atoi (data); }
  3408. /** Parses this string as a 64-bit integer. */
  3409. int64 getIntValue64() const noexcept
  3410. {
  3411. #if JUCE_LINUX || JUCE_ANDROID
  3412. return atoll (data);
  3413. #elif JUCE_WINDOWS
  3414. return _atoi64 (data);
  3415. #else
  3416. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3417. #endif
  3418. }
  3419. /** Parses this string as a floating point double. */
  3420. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3421. /** Returns the first non-whitespace character in the string. */
  3422. CharPointer_ASCII findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3423. /** Returns true if the given unicode character can be represented in this encoding. */
  3424. static bool canRepresent (juce_wchar character) noexcept
  3425. {
  3426. return ((unsigned int) character) < (unsigned int) 128;
  3427. }
  3428. /** Returns true if this data contains a valid string in this encoding. */
  3429. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3430. {
  3431. while (--maxBytesToRead >= 0)
  3432. {
  3433. if (((signed char) *dataToTest) <= 0)
  3434. return *dataToTest == 0;
  3435. ++dataToTest;
  3436. }
  3437. return true;
  3438. }
  3439. private:
  3440. CharType* data;
  3441. };
  3442. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3443. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3444. #if JUCE_MSVC
  3445. #pragma warning (pop)
  3446. #endif
  3447. class OutputStream;
  3448. /**
  3449. The JUCE String class!
  3450. Using a reference-counted internal representation, these strings are fast
  3451. and efficient, and there are methods to do just about any operation you'll ever
  3452. dream of.
  3453. @see StringArray, StringPairArray
  3454. */
  3455. class JUCE_API String
  3456. {
  3457. public:
  3458. /** Creates an empty string.
  3459. @see empty
  3460. */
  3461. String() noexcept;
  3462. /** Creates a copy of another string. */
  3463. String (const String& other) noexcept;
  3464. /** Creates a string from a zero-terminated ascii text string.
  3465. The string passed-in must not contain any characters with a value above 127, because
  3466. these can't be converted to unicode without knowing the original encoding that was
  3467. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3468. assertion.
  3469. To create strings with extended characters from UTF-8, you should explicitly call
  3470. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3471. use UTF-8 with escape characters in your source code to represent extended characters,
  3472. because there's no other way to represent unicode strings in a way that isn't dependent
  3473. on the compiler, source code editor and platform.
  3474. */
  3475. String (const char* text);
  3476. /** Creates a string from a string of 8-bit ascii characters.
  3477. The string passed-in must not contain any characters with a value above 127, because
  3478. these can't be converted to unicode without knowing the original encoding that was
  3479. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3480. assertion.
  3481. To create strings with extended characters from UTF-8, you should explicitly call
  3482. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3483. use UTF-8 with escape characters in your source code to represent extended characters,
  3484. because there's no other way to represent unicode strings in a way that isn't dependent
  3485. on the compiler, source code editor and platform.
  3486. This will use up the the first maxChars characters of the string (or less if the string
  3487. is actually shorter).
  3488. */
  3489. String (const char* text, size_t maxChars);
  3490. /** Creates a string from a whcar_t character string.
  3491. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3492. */
  3493. String (const wchar_t* text);
  3494. /** Creates a string from a whcar_t character string.
  3495. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3496. */
  3497. String (const wchar_t* text, size_t maxChars);
  3498. /** Creates a string from a UTF-8 character string */
  3499. String (const CharPointer_UTF8& text);
  3500. /** Creates a string from a UTF-8 character string */
  3501. String (const CharPointer_UTF8& text, size_t maxChars);
  3502. /** Creates a string from a UTF-8 character string */
  3503. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3504. /** Creates a string from a UTF-16 character string */
  3505. String (const CharPointer_UTF16& text);
  3506. /** Creates a string from a UTF-16 character string */
  3507. String (const CharPointer_UTF16& text, size_t maxChars);
  3508. /** Creates a string from a UTF-16 character string */
  3509. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3510. /** Creates a string from a UTF-32 character string */
  3511. String (const CharPointer_UTF32& text);
  3512. /** Creates a string from a UTF-32 character string */
  3513. String (const CharPointer_UTF32& text, size_t maxChars);
  3514. /** Creates a string from a UTF-32 character string */
  3515. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3516. /** Creates a string from an ASCII character string */
  3517. String (const CharPointer_ASCII& text);
  3518. /** Creates a string from a single character. */
  3519. static String charToString (juce_wchar character);
  3520. /** Destructor. */
  3521. ~String() noexcept;
  3522. /** This is an empty string that can be used whenever one is needed.
  3523. It's better to use this than String() because it explains what's going on
  3524. and is more efficient.
  3525. */
  3526. static const String empty;
  3527. /** This is the character encoding type used internally to store the string.
  3528. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3529. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3530. contain few extended characters), but call operator[] involves iterating the string to find
  3531. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3532. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3533. but is the native wchar_t format used in Windows.
  3534. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3535. toUTF32() methods let you access the string's content in any of the other formats.
  3536. */
  3537. #if (JUCE_STRING_UTF_TYPE == 32)
  3538. typedef CharPointer_UTF32 CharPointerType;
  3539. #elif (JUCE_STRING_UTF_TYPE == 16)
  3540. typedef CharPointer_UTF16 CharPointerType;
  3541. #elif (JUCE_STRING_UTF_TYPE == 8)
  3542. typedef CharPointer_UTF8 CharPointerType;
  3543. #else
  3544. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3545. #endif
  3546. /** Generates a probably-unique 32-bit hashcode from this string. */
  3547. int hashCode() const noexcept;
  3548. /** Generates a probably-unique 64-bit hashcode from this string. */
  3549. int64 hashCode64() const noexcept;
  3550. /** Returns the number of characters in the string. */
  3551. int length() const noexcept;
  3552. // Assignment and concatenation operators..
  3553. /** Replaces this string's contents with another string. */
  3554. String& operator= (const String& other) noexcept;
  3555. /** Appends another string at the end of this one. */
  3556. String& operator+= (const String& stringToAppend);
  3557. /** Appends another string at the end of this one. */
  3558. String& operator+= (const char* textToAppend);
  3559. /** Appends another string at the end of this one. */
  3560. String& operator+= (const wchar_t* textToAppend);
  3561. /** Appends a decimal number at the end of this string. */
  3562. String& operator+= (int numberToAppend);
  3563. /** Appends a character at the end of this string. */
  3564. String& operator+= (char characterToAppend);
  3565. /** Appends a character at the end of this string. */
  3566. String& operator+= (wchar_t characterToAppend);
  3567. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3568. /** Appends a character at the end of this string. */
  3569. String& operator+= (juce_wchar characterToAppend);
  3570. #endif
  3571. /** Appends a string to the end of this one.
  3572. @param textToAppend the string to add
  3573. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3574. */
  3575. void append (const String& textToAppend, size_t maxCharsToTake);
  3576. /** Appends a string to the end of this one.
  3577. @param textToAppend the string to add
  3578. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3579. */
  3580. template <class CharPointer>
  3581. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3582. {
  3583. if (textToAppend.getAddress() != nullptr)
  3584. {
  3585. size_t extraBytesNeeded = 0;
  3586. size_t numChars = 0;
  3587. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3588. {
  3589. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3590. ++numChars;
  3591. }
  3592. if (numChars > 0)
  3593. {
  3594. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3595. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3596. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3597. }
  3598. }
  3599. }
  3600. /** Appends a string to the end of this one. */
  3601. template <class CharPointer>
  3602. void appendCharPointer (const CharPointer& textToAppend)
  3603. {
  3604. if (textToAppend.getAddress() != nullptr)
  3605. {
  3606. size_t extraBytesNeeded = 0;
  3607. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3608. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3609. if (extraBytesNeeded > 0)
  3610. {
  3611. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3612. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3613. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3614. }
  3615. }
  3616. }
  3617. // Comparison methods..
  3618. /** Returns true if the string contains no characters.
  3619. Note that there's also an isNotEmpty() method to help write readable code.
  3620. @see containsNonWhitespaceChars()
  3621. */
  3622. inline bool isEmpty() const noexcept { return text[0] == 0; }
  3623. /** Returns true if the string contains at least one character.
  3624. Note that there's also an isEmpty() method to help write readable code.
  3625. @see containsNonWhitespaceChars()
  3626. */
  3627. inline bool isNotEmpty() const noexcept { return text[0] != 0; }
  3628. /** Case-insensitive comparison with another string. */
  3629. bool equalsIgnoreCase (const String& other) const noexcept;
  3630. /** Case-insensitive comparison with another string. */
  3631. bool equalsIgnoreCase (const wchar_t* other) const noexcept;
  3632. /** Case-insensitive comparison with another string. */
  3633. bool equalsIgnoreCase (const char* other) const noexcept;
  3634. /** Case-sensitive comparison with another string.
  3635. @returns 0 if the two strings are identical; negative if this string comes before
  3636. the other one alphabetically, or positive if it comes after it.
  3637. */
  3638. int compare (const String& other) const noexcept;
  3639. /** Case-sensitive comparison with another string.
  3640. @returns 0 if the two strings are identical; negative if this string comes before
  3641. the other one alphabetically, or positive if it comes after it.
  3642. */
  3643. int compare (const char* other) const noexcept;
  3644. /** Case-sensitive comparison with another string.
  3645. @returns 0 if the two strings are identical; negative if this string comes before
  3646. the other one alphabetically, or positive if it comes after it.
  3647. */
  3648. int compare (const wchar_t* other) const noexcept;
  3649. /** Case-insensitive comparison with another string.
  3650. @returns 0 if the two strings are identical; negative if this string comes before
  3651. the other one alphabetically, or positive if it comes after it.
  3652. */
  3653. int compareIgnoreCase (const String& other) const noexcept;
  3654. /** Lexicographic comparison with another string.
  3655. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3656. characters, making it good for sorting human-readable strings.
  3657. @returns 0 if the two strings are identical; negative if this string comes before
  3658. the other one alphabetically, or positive if it comes after it.
  3659. */
  3660. int compareLexicographically (const String& other) const noexcept;
  3661. /** Tests whether the string begins with another string.
  3662. If the parameter is an empty string, this will always return true.
  3663. Uses a case-sensitive comparison.
  3664. */
  3665. bool startsWith (const String& text) const noexcept;
  3666. /** Tests whether the string begins with a particular character.
  3667. If the character is 0, this will always return false.
  3668. Uses a case-sensitive comparison.
  3669. */
  3670. bool startsWithChar (juce_wchar character) const noexcept;
  3671. /** Tests whether the string begins with another string.
  3672. If the parameter is an empty string, this will always return true.
  3673. Uses a case-insensitive comparison.
  3674. */
  3675. bool startsWithIgnoreCase (const String& text) const noexcept;
  3676. /** Tests whether the string ends with another string.
  3677. If the parameter is an empty string, this will always return true.
  3678. Uses a case-sensitive comparison.
  3679. */
  3680. bool endsWith (const String& text) const noexcept;
  3681. /** Tests whether the string ends with a particular character.
  3682. If the character is 0, this will always return false.
  3683. Uses a case-sensitive comparison.
  3684. */
  3685. bool endsWithChar (juce_wchar character) const noexcept;
  3686. /** Tests whether the string ends with another string.
  3687. If the parameter is an empty string, this will always return true.
  3688. Uses a case-insensitive comparison.
  3689. */
  3690. bool endsWithIgnoreCase (const String& text) const noexcept;
  3691. /** Tests whether the string contains another substring.
  3692. If the parameter is an empty string, this will always return true.
  3693. Uses a case-sensitive comparison.
  3694. */
  3695. bool contains (const String& text) const noexcept;
  3696. /** Tests whether the string contains a particular character.
  3697. Uses a case-sensitive comparison.
  3698. */
  3699. bool containsChar (juce_wchar character) const noexcept;
  3700. /** Tests whether the string contains another substring.
  3701. Uses a case-insensitive comparison.
  3702. */
  3703. bool containsIgnoreCase (const String& text) const noexcept;
  3704. /** Tests whether the string contains another substring as a distict word.
  3705. @returns true if the string contains this word, surrounded by
  3706. non-alphanumeric characters
  3707. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3708. */
  3709. bool containsWholeWord (const String& wordToLookFor) const noexcept;
  3710. /** Tests whether the string contains another substring as a distict word.
  3711. @returns true if the string contains this word, surrounded by
  3712. non-alphanumeric characters
  3713. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3714. */
  3715. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3716. /** Finds an instance of another substring if it exists as a distict word.
  3717. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3718. then this will return the index of the start of the substring. If it isn't
  3719. found, then it will return -1
  3720. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3721. */
  3722. int indexOfWholeWord (const String& wordToLookFor) const noexcept;
  3723. /** Finds an instance of another substring if it exists as a distict word.
  3724. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3725. then this will return the index of the start of the substring. If it isn't
  3726. found, then it will return -1
  3727. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3728. */
  3729. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3730. /** Looks for any of a set of characters in the string.
  3731. Uses a case-sensitive comparison.
  3732. @returns true if the string contains any of the characters from
  3733. the string that is passed in.
  3734. */
  3735. bool containsAnyOf (const String& charactersItMightContain) const noexcept;
  3736. /** Looks for a set of characters in the string.
  3737. Uses a case-sensitive comparison.
  3738. @returns Returns false if any of the characters in this string do not occur in
  3739. the parameter string. If this string is empty, the return value will
  3740. always be true.
  3741. */
  3742. bool containsOnly (const String& charactersItMightContain) const noexcept;
  3743. /** Returns true if this string contains any non-whitespace characters.
  3744. This will return false if the string contains only whitespace characters, or
  3745. if it's empty.
  3746. It is equivalent to calling "myString.trim().isNotEmpty()".
  3747. */
  3748. bool containsNonWhitespaceChars() const noexcept;
  3749. /** Returns true if the string matches this simple wildcard expression.
  3750. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3751. This isn't a full-blown regex though! The only wildcard characters supported
  3752. are "*" and "?". It's mainly intended for filename pattern matching.
  3753. */
  3754. bool matchesWildcard (const String& wildcard, bool ignoreCase) const noexcept;
  3755. // Substring location methods..
  3756. /** Searches for a character inside this string.
  3757. Uses a case-sensitive comparison.
  3758. @returns the index of the first occurrence of the character in this
  3759. string, or -1 if it's not found.
  3760. */
  3761. int indexOfChar (juce_wchar characterToLookFor) const noexcept;
  3762. /** Searches for a character inside this string.
  3763. Uses a case-sensitive comparison.
  3764. @param startIndex the index from which the search should proceed
  3765. @param characterToLookFor the character to look for
  3766. @returns the index of the first occurrence of the character in this
  3767. string, or -1 if it's not found.
  3768. */
  3769. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const noexcept;
  3770. /** Returns the index of the first character that matches one of the characters
  3771. passed-in to this method.
  3772. This scans the string, beginning from the startIndex supplied, and if it finds
  3773. a character that appears in the string charactersToLookFor, it returns its index.
  3774. If none of these characters are found, it returns -1.
  3775. If ignoreCase is true, the comparison will be case-insensitive.
  3776. @see indexOfChar, lastIndexOfAnyOf
  3777. */
  3778. int indexOfAnyOf (const String& charactersToLookFor,
  3779. int startIndex = 0,
  3780. bool ignoreCase = false) const noexcept;
  3781. /** Searches for a substring within this string.
  3782. Uses a case-sensitive comparison.
  3783. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3784. If textToLookFor is an empty string, this will always return 0.
  3785. */
  3786. int indexOf (const String& textToLookFor) const noexcept;
  3787. /** Searches for a substring within this string.
  3788. Uses a case-sensitive comparison.
  3789. @param startIndex the index from which the search should proceed
  3790. @param textToLookFor the string to search for
  3791. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3792. If textToLookFor is an empty string, this will always return -1.
  3793. */
  3794. int indexOf (int startIndex, const String& textToLookFor) const noexcept;
  3795. /** Searches for a substring within this string.
  3796. Uses a case-insensitive comparison.
  3797. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3798. If textToLookFor is an empty string, this will always return 0.
  3799. */
  3800. int indexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3801. /** Searches for a substring within this string.
  3802. Uses a case-insensitive comparison.
  3803. @param startIndex the index from which the search should proceed
  3804. @param textToLookFor the string to search for
  3805. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3806. If textToLookFor is an empty string, this will always return -1.
  3807. */
  3808. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const noexcept;
  3809. /** Searches for a character inside this string (working backwards from the end of the string).
  3810. Uses a case-sensitive comparison.
  3811. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3812. */
  3813. int lastIndexOfChar (juce_wchar character) const noexcept;
  3814. /** Searches for a substring inside this string (working backwards from the end of the string).
  3815. Uses a case-sensitive comparison.
  3816. @returns the index of the start of the last occurrence of the substring within this string,
  3817. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3818. */
  3819. int lastIndexOf (const String& textToLookFor) const noexcept;
  3820. /** Searches for a substring inside this string (working backwards from the end of the string).
  3821. Uses a case-insensitive comparison.
  3822. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3823. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3824. */
  3825. int lastIndexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3826. /** Returns the index of the last character in this string that matches one of the
  3827. characters passed-in to this method.
  3828. This scans the string backwards, starting from its end, and if it finds
  3829. a character that appears in the string charactersToLookFor, it returns its index.
  3830. If none of these characters are found, it returns -1.
  3831. If ignoreCase is true, the comparison will be case-insensitive.
  3832. @see lastIndexOf, indexOfAnyOf
  3833. */
  3834. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3835. bool ignoreCase = false) const noexcept;
  3836. // Substring extraction and manipulation methods..
  3837. /** Returns the character at this index in the string.
  3838. In a release build, no checks are made to see if the index is within a valid range, so be
  3839. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3840. Also beware that depending on the encoding format that the string is using internally, this
  3841. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3842. If you're scanning through a string to inspect its characters, you should never use this operator
  3843. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3844. then to use that to iterate the string.
  3845. @see getCharPointer
  3846. */
  3847. const juce_wchar operator[] (int index) const noexcept;
  3848. /** Returns the final character of the string.
  3849. If the string is empty this will return 0.
  3850. */
  3851. juce_wchar getLastCharacter() const noexcept;
  3852. /** Returns a subsection of the string.
  3853. If the range specified is beyond the limits of the string, as much as
  3854. possible is returned.
  3855. @param startIndex the index of the start of the substring needed
  3856. @param endIndex all characters from startIndex up to (but not including)
  3857. this index are returned
  3858. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3859. */
  3860. String substring (int startIndex, int endIndex) const;
  3861. /** Returns a section of the string, starting from a given position.
  3862. @param startIndex the first character to include. If this is beyond the end
  3863. of the string, an empty string is returned. If it is zero or
  3864. less, the whole string is returned.
  3865. @returns the substring from startIndex up to the end of the string
  3866. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3867. */
  3868. String substring (int startIndex) const;
  3869. /** Returns a version of this string with a number of characters removed
  3870. from the end.
  3871. @param numberToDrop the number of characters to drop from the end of the
  3872. string. If this is greater than the length of the string,
  3873. an empty string will be returned. If zero or less, the
  3874. original string will be returned.
  3875. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3876. */
  3877. String dropLastCharacters (int numberToDrop) const;
  3878. /** Returns a number of characters from the end of the string.
  3879. This returns the last numCharacters characters from the end of the string. If the
  3880. string is shorter than numCharacters, the whole string is returned.
  3881. @see substring, dropLastCharacters, getLastCharacter
  3882. */
  3883. String getLastCharacters (int numCharacters) const;
  3884. /** Returns a section of the string starting from a given substring.
  3885. This will search for the first occurrence of the given substring, and
  3886. return the section of the string starting from the point where this is
  3887. found (optionally not including the substring itself).
  3888. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3889. fromFirstOccurrenceOf ("34", false) would return "56".
  3890. If the substring isn't found, the method will return an empty string.
  3891. If ignoreCase is true, the comparison will be case-insensitive.
  3892. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3893. */
  3894. String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3895. bool includeSubStringInResult,
  3896. bool ignoreCase) const;
  3897. /** Returns a section of the string starting from the last occurrence of a given substring.
  3898. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3899. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3900. return the whole of the original string.
  3901. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3902. */
  3903. String fromLastOccurrenceOf (const String& substringToFind,
  3904. bool includeSubStringInResult,
  3905. bool ignoreCase) const;
  3906. /** Returns the start of this string, up to the first occurrence of a substring.
  3907. This will search for the first occurrence of a given substring, and then
  3908. return a copy of the string, up to the position of this substring,
  3909. optionally including or excluding the substring itself in the result.
  3910. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3911. upTo ("34", true) would return "1234".
  3912. If the substring isn't found, this will return the whole of the original string.
  3913. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3914. */
  3915. String upToFirstOccurrenceOf (const String& substringToEndWith,
  3916. bool includeSubStringInResult,
  3917. bool ignoreCase) const;
  3918. /** Returns the start of this string, up to the last occurrence of a substring.
  3919. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3920. If the substring isn't found, this will return the whole of the original string.
  3921. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3922. */
  3923. String upToLastOccurrenceOf (const String& substringToFind,
  3924. bool includeSubStringInResult,
  3925. bool ignoreCase) const;
  3926. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3927. String trim() const;
  3928. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3929. String trimStart() const;
  3930. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3931. String trimEnd() const;
  3932. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3933. Characters are removed from the start of the string until it finds one that is not in the
  3934. specified set, and then it stops.
  3935. @param charactersToTrim the set of characters to remove.
  3936. @see trim, trimStart, trimCharactersAtEnd
  3937. */
  3938. String trimCharactersAtStart (const String& charactersToTrim) const;
  3939. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3940. Characters are removed from the end of the string until it finds one that is not in the
  3941. specified set, and then it stops.
  3942. @param charactersToTrim the set of characters to remove.
  3943. @see trim, trimEnd, trimCharactersAtStart
  3944. */
  3945. String trimCharactersAtEnd (const String& charactersToTrim) const;
  3946. /** Returns an upper-case version of this string. */
  3947. String toUpperCase() const;
  3948. /** Returns an lower-case version of this string. */
  3949. String toLowerCase() const;
  3950. /** Replaces a sub-section of the string with another string.
  3951. This will return a copy of this string, with a set of characters
  3952. from startIndex to startIndex + numCharsToReplace removed, and with
  3953. a new string inserted in their place.
  3954. Note that this is a const method, and won't alter the string itself.
  3955. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3956. it will be constrained to a valid range.
  3957. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3958. characters will be taken out.
  3959. @param stringToInsert the new string to insert at startIndex after the characters have been
  3960. removed.
  3961. */
  3962. String replaceSection (int startIndex,
  3963. int numCharactersToReplace,
  3964. const String& stringToInsert) const;
  3965. /** Replaces all occurrences of a substring with another string.
  3966. Returns a copy of this string, with any occurrences of stringToReplace
  3967. swapped for stringToInsertInstead.
  3968. Note that this is a const method, and won't alter the string itself.
  3969. */
  3970. String replace (const String& stringToReplace,
  3971. const String& stringToInsertInstead,
  3972. bool ignoreCase = false) const;
  3973. /** Returns a string with all occurrences of a character replaced with a different one. */
  3974. String replaceCharacter (juce_wchar characterToReplace,
  3975. juce_wchar characterToInsertInstead) const;
  3976. /** Replaces a set of characters with another set.
  3977. Returns a string in which each character from charactersToReplace has been replaced
  3978. by the character at the equivalent position in newCharacters (so the two strings
  3979. passed in must be the same length).
  3980. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  3981. Note that this is a const method, and won't affect the string itself.
  3982. */
  3983. String replaceCharacters (const String& charactersToReplace,
  3984. const String& charactersToInsertInstead) const;
  3985. /** Returns a version of this string that only retains a fixed set of characters.
  3986. This will return a copy of this string, omitting any characters which are not
  3987. found in the string passed-in.
  3988. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  3989. Note that this is a const method, and won't alter the string itself.
  3990. */
  3991. String retainCharacters (const String& charactersToRetain) const;
  3992. /** Returns a version of this string with a set of characters removed.
  3993. This will return a copy of this string, omitting any characters which are
  3994. found in the string passed-in.
  3995. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  3996. Note that this is a const method, and won't alter the string itself.
  3997. */
  3998. String removeCharacters (const String& charactersToRemove) const;
  3999. /** Returns a section from the start of the string that only contains a certain set of characters.
  4000. This returns the leftmost section of the string, up to (and not including) the
  4001. first character that doesn't appear in the string passed in.
  4002. */
  4003. String initialSectionContainingOnly (const String& permittedCharacters) const;
  4004. /** Returns a section from the start of the string that only contains a certain set of characters.
  4005. This returns the leftmost section of the string, up to (and not including) the
  4006. first character that occurs in the string passed in. (If none of the specified
  4007. characters are found in the string, the return value will just be the original string).
  4008. */
  4009. String initialSectionNotContaining (const String& charactersToStopAt) const;
  4010. /** Checks whether the string might be in quotation marks.
  4011. @returns true if the string begins with a quote character (either a double or single quote).
  4012. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4013. @see unquoted, quoted
  4014. */
  4015. bool isQuotedString() const;
  4016. /** Removes quotation marks from around the string, (if there are any).
  4017. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4018. at the ends of the string are not affected. If there aren't any quotes, the original string
  4019. is returned.
  4020. Note that this is a const method, and won't alter the string itself.
  4021. @see isQuotedString, quoted
  4022. */
  4023. String unquoted() const;
  4024. /** Adds quotation marks around a string.
  4025. This will return a copy of the string with a quote at the start and end, (but won't
  4026. add the quote if there's already one there, so it's safe to call this on strings that
  4027. may already have quotes around them).
  4028. Note that this is a const method, and won't alter the string itself.
  4029. @param quoteCharacter the character to add at the start and end
  4030. @see isQuotedString, unquoted
  4031. */
  4032. String quoted (juce_wchar quoteCharacter = '"') const;
  4033. /** Creates a string which is a version of a string repeated and joined together.
  4034. @param stringToRepeat the string to repeat
  4035. @param numberOfTimesToRepeat how many times to repeat it
  4036. */
  4037. static String repeatedString (const String& stringToRepeat,
  4038. int numberOfTimesToRepeat);
  4039. /** Returns a copy of this string with the specified character repeatedly added to its
  4040. beginning until the total length is at least the minimum length specified.
  4041. */
  4042. String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4043. /** Returns a copy of this string with the specified character repeatedly added to its
  4044. end until the total length is at least the minimum length specified.
  4045. */
  4046. String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4047. /** Creates a string from data in an unknown format.
  4048. This looks at some binary data and tries to guess whether it's Unicode
  4049. or 8-bit characters, then returns a string that represents it correctly.
  4050. Should be able to handle Unicode endianness correctly, by looking at
  4051. the first two bytes.
  4052. */
  4053. static String createStringFromData (const void* data, int size);
  4054. /** Creates a String from a printf-style parameter list.
  4055. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4056. using the operator<< methods or pretty much anything else instead. It's only provided
  4057. here because of the popular unrest that was stirred-up when I tried to remove it...
  4058. If you're really determined to use it, at least make sure that you never, ever,
  4059. pass any String objects to it as parameters. And bear in mind that internally, depending
  4060. on the platform, it may be using wchar_t or char character types, so that even string
  4061. literals can't be safely used as parameters if you're writing portable code.
  4062. */
  4063. static String formatted (const String formatString, ... );
  4064. // Numeric conversions..
  4065. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4066. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4067. */
  4068. explicit String (int decimalInteger);
  4069. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4070. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4071. */
  4072. explicit String (unsigned int decimalInteger);
  4073. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4074. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4075. */
  4076. explicit String (short decimalInteger);
  4077. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4078. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4079. */
  4080. explicit String (unsigned short decimalInteger);
  4081. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4082. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4083. */
  4084. explicit String (int64 largeIntegerValue);
  4085. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4086. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4087. */
  4088. explicit String (uint64 largeIntegerValue);
  4089. /** Creates a string representing this floating-point number.
  4090. @param floatValue the value to convert to a string
  4091. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4092. decimal places, and will not use exponent notation. If 0 or
  4093. less, it will use exponent notation if necessary.
  4094. @see getDoubleValue, getIntValue
  4095. */
  4096. explicit String (float floatValue,
  4097. int numberOfDecimalPlaces = 0);
  4098. /** Creates a string representing this floating-point number.
  4099. @param doubleValue the value to convert to a string
  4100. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4101. decimal places, and will not use exponent notation. If 0 or
  4102. less, it will use exponent notation if necessary.
  4103. @see getFloatValue, getIntValue
  4104. */
  4105. explicit String (double doubleValue,
  4106. int numberOfDecimalPlaces = 0);
  4107. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4108. @returns the value of the string as a 32 bit signed base-10 integer.
  4109. @see getTrailingIntValue, getHexValue32, getHexValue64
  4110. */
  4111. int getIntValue() const noexcept;
  4112. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4113. @returns the value of the string as a 64 bit signed base-10 integer.
  4114. */
  4115. int64 getLargeIntValue() const noexcept;
  4116. /** Parses a decimal number from the end of the string.
  4117. This will look for a value at the end of the string.
  4118. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4119. Negative numbers are not handled, so "xyz-5" returns 5.
  4120. @see getIntValue
  4121. */
  4122. int getTrailingIntValue() const noexcept;
  4123. /** Parses this string as a floating point number.
  4124. @returns the value of the string as a 32-bit floating point value.
  4125. @see getDoubleValue
  4126. */
  4127. float getFloatValue() const noexcept;
  4128. /** Parses this string as a floating point number.
  4129. @returns the value of the string as a 64-bit floating point value.
  4130. @see getFloatValue
  4131. */
  4132. double getDoubleValue() const noexcept;
  4133. /** Parses the string as a hexadecimal number.
  4134. Non-hexadecimal characters in the string are ignored.
  4135. If the string contains too many characters, then the lowest significant
  4136. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4137. @returns a 32-bit number which is the value of the string in hex.
  4138. */
  4139. int getHexValue32() const noexcept;
  4140. /** Parses the string as a hexadecimal number.
  4141. Non-hexadecimal characters in the string are ignored.
  4142. If the string contains too many characters, then the lowest significant
  4143. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4144. @returns a 64-bit number which is the value of the string in hex.
  4145. */
  4146. int64 getHexValue64() const noexcept;
  4147. /** Creates a string representing this 32-bit value in hexadecimal. */
  4148. static String toHexString (int number);
  4149. /** Creates a string representing this 64-bit value in hexadecimal. */
  4150. static String toHexString (int64 number);
  4151. /** Creates a string representing this 16-bit value in hexadecimal. */
  4152. static String toHexString (short number);
  4153. /** Creates a string containing a hex dump of a block of binary data.
  4154. @param data the binary data to use as input
  4155. @param size how many bytes of data to use
  4156. @param groupSize how many bytes are grouped together before inserting a
  4157. space into the output. e.g. group size 0 has no spaces,
  4158. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4159. like "bea1 c2ff".
  4160. */
  4161. static String toHexString (const void* data, int size, int groupSize = 1);
  4162. /** Returns the character pointer currently being used to store this string.
  4163. Because it returns a reference to the string's internal data, the pointer
  4164. that is returned must not be stored anywhere, as it can be deleted whenever the
  4165. string changes.
  4166. */
  4167. inline const CharPointerType& getCharPointer() const noexcept { return text; }
  4168. /** Returns a pointer to a UTF-8 version of this string.
  4169. Because it returns a reference to the string's internal data, the pointer
  4170. that is returned must not be stored anywhere, as it can be deleted whenever the
  4171. string changes.
  4172. To find out how many bytes you need to store this string as UTF-8, you can call
  4173. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4174. @see getCharPointer, toUTF16, toUTF32
  4175. */
  4176. const CharPointer_UTF8 toUTF8() const;
  4177. /** Returns a pointer to a UTF-32 version of this string.
  4178. Because it returns a reference to the string's internal data, the pointer
  4179. that is returned must not be stored anywhere, as it can be deleted whenever the
  4180. string changes.
  4181. To find out how many bytes you need to store this string as UTF-16, you can call
  4182. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4183. @see getCharPointer, toUTF8, toUTF32
  4184. */
  4185. CharPointer_UTF16 toUTF16() const;
  4186. /** Returns a pointer to a UTF-32 version of this string.
  4187. Because it returns a reference to the string's internal data, the pointer
  4188. that is returned must not be stored anywhere, as it can be deleted whenever the
  4189. string changes.
  4190. @see getCharPointer, toUTF8, toUTF16
  4191. */
  4192. CharPointer_UTF32 toUTF32() const;
  4193. /** Returns a pointer to a wchar_t version of this string.
  4194. Because it returns a reference to the string's internal data, the pointer
  4195. that is returned must not be stored anywhere, as it can be deleted whenever the
  4196. string changes.
  4197. Bear in mind that the wchar_t type is different on different platforms, so on
  4198. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4199. as calling toUTF32(), etc.
  4200. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4201. */
  4202. const wchar_t* toWideCharPointer() const;
  4203. /** Creates a String from a UTF-8 encoded buffer.
  4204. If the size is < 0, it'll keep reading until it hits a zero.
  4205. */
  4206. static String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4207. /** Returns the number of bytes required to represent this string as UTF8.
  4208. The number returned does NOT include the trailing zero.
  4209. @see toUTF8, copyToUTF8
  4210. */
  4211. int getNumBytesAsUTF8() const noexcept;
  4212. /** Copies the string to a buffer as UTF-8 characters.
  4213. Returns the number of bytes copied to the buffer, including the terminating null
  4214. character.
  4215. To find out how many bytes you need to store this string as UTF-8, you can call
  4216. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4217. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4218. returns the number of bytes required (including the terminating null character).
  4219. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4220. put in as many as it can while still allowing for a terminating null char at the
  4221. end, and will return the number of bytes that were actually used.
  4222. @see CharPointer_UTF8::writeWithDestByteLimit
  4223. */
  4224. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4225. /** Copies the string to a buffer as UTF-16 characters.
  4226. Returns the number of bytes copied to the buffer, including the terminating null
  4227. character.
  4228. To find out how many bytes you need to store this string as UTF-16, you can call
  4229. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4230. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4231. returns the number of bytes required (including the terminating null character).
  4232. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4233. put in as many as it can while still allowing for a terminating null char at the
  4234. end, and will return the number of bytes that were actually used.
  4235. @see CharPointer_UTF16::writeWithDestByteLimit
  4236. */
  4237. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4238. /** Copies the string to a buffer as UTF-16 characters.
  4239. Returns the number of bytes copied to the buffer, including the terminating null
  4240. character.
  4241. To find out how many bytes you need to store this string as UTF-32, you can call
  4242. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4243. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4244. returns the number of bytes required (including the terminating null character).
  4245. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4246. put in as many as it can while still allowing for a terminating null char at the
  4247. end, and will return the number of bytes that were actually used.
  4248. @see CharPointer_UTF32::writeWithDestByteLimit
  4249. */
  4250. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4251. /** Increases the string's internally allocated storage.
  4252. Although the string's contents won't be affected by this call, it will
  4253. increase the amount of memory allocated internally for the string to grow into.
  4254. If you're about to make a large number of calls to methods such
  4255. as += or <<, it's more efficient to preallocate enough extra space
  4256. beforehand, so that these methods won't have to keep resizing the string
  4257. to append the extra characters.
  4258. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4259. value is less than the currently allocated size, it will
  4260. have no effect.
  4261. */
  4262. void preallocateBytes (size_t numBytesNeeded);
  4263. /** Swaps the contents of this string with another one.
  4264. This is a very fast operation, as no allocation or copying needs to be done.
  4265. */
  4266. void swapWith (String& other) noexcept;
  4267. /** A helper class to improve performance when concatenating many large strings
  4268. together.
  4269. Because appending one string to another involves measuring the length of
  4270. both strings, repeatedly doing this for many long strings will become
  4271. an exponentially slow operation. This class uses some internal state to
  4272. avoid that, so that each append operation only needs to measure the length
  4273. of the appended string.
  4274. */
  4275. class JUCE_API Concatenator
  4276. {
  4277. public:
  4278. Concatenator (String& stringToAppendTo);
  4279. ~Concatenator();
  4280. void append (const String& s);
  4281. private:
  4282. String& result;
  4283. int nextIndex;
  4284. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4285. };
  4286. private:
  4287. CharPointerType text;
  4288. struct PreallocationBytes
  4289. {
  4290. explicit PreallocationBytes (size_t);
  4291. size_t numBytes;
  4292. };
  4293. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4294. void appendFixedLength (const char* text, int numExtraChars);
  4295. size_t getByteOffsetOfEnd() const noexcept;
  4296. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4297. // This private cast operator should prevent strings being accidentally cast
  4298. // to bools (this is possible because the compiler can add an implicit cast
  4299. // via a const char*)
  4300. operator bool() const noexcept { return false; }
  4301. };
  4302. /** Concatenates two strings. */
  4303. JUCE_API String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4304. /** Concatenates two strings. */
  4305. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4306. /** Concatenates two strings. */
  4307. JUCE_API String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4308. /** Concatenates two strings. */
  4309. JUCE_API String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4310. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4311. /** Concatenates two strings. */
  4312. JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4313. #endif
  4314. /** Concatenates two strings. */
  4315. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4316. /** Concatenates two strings. */
  4317. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4318. /** Concatenates two strings. */
  4319. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4320. /** Concatenates two strings. */
  4321. JUCE_API String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4322. /** Concatenates two strings. */
  4323. JUCE_API String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4324. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4325. /** Concatenates two strings. */
  4326. JUCE_API String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4327. #endif
  4328. /** Appends a character at the end of a string. */
  4329. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4330. /** Appends a character at the end of a string. */
  4331. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4332. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4333. /** Appends a character at the end of a string. */
  4334. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4335. #endif
  4336. /** Appends a string to the end of the first one. */
  4337. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4338. /** Appends a string to the end of the first one. */
  4339. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4340. /** Appends a string to the end of the first one. */
  4341. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4342. /** Appends a decimal number at the end of a string. */
  4343. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4344. /** Appends a decimal number at the end of a string. */
  4345. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4346. /** Appends a decimal number at the end of a string. */
  4347. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4348. /** Appends a decimal number at the end of a string. */
  4349. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4350. /** Appends a decimal number at the end of a string. */
  4351. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4352. /** Case-sensitive comparison of two strings. */
  4353. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept;
  4354. /** Case-sensitive comparison of two strings. */
  4355. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept;
  4356. /** Case-sensitive comparison of two strings. */
  4357. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept;
  4358. /** Case-sensitive comparison of two strings. */
  4359. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4360. /** Case-sensitive comparison of two strings. */
  4361. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4362. /** Case-sensitive comparison of two strings. */
  4363. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4364. /** Case-sensitive comparison of two strings. */
  4365. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept;
  4366. /** Case-sensitive comparison of two strings. */
  4367. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept;
  4368. /** Case-sensitive comparison of two strings. */
  4369. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept;
  4370. /** Case-sensitive comparison of two strings. */
  4371. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4372. /** Case-sensitive comparison of two strings. */
  4373. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4374. /** Case-sensitive comparison of two strings. */
  4375. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4376. /** Case-sensitive comparison of two strings. */
  4377. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) noexcept;
  4378. /** Case-sensitive comparison of two strings. */
  4379. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) noexcept;
  4380. /** Case-sensitive comparison of two strings. */
  4381. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) noexcept;
  4382. /** Case-sensitive comparison of two strings. */
  4383. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) noexcept;
  4384. /** This operator allows you to write a juce String directly to std output streams.
  4385. This is handy for writing strings to std::cout, std::cerr, etc.
  4386. */
  4387. template <class traits>
  4388. std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  4389. {
  4390. return stream << stringToWrite.toUTF8().getAddress();
  4391. }
  4392. /** This operator allows you to write a juce String directly to std output streams.
  4393. This is handy for writing strings to std::wcout, std::wcerr, etc.
  4394. */
  4395. template <class traits>
  4396. std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
  4397. {
  4398. return stream << stringToWrite.toWideCharPointer();
  4399. }
  4400. /** Writes a string to an OutputStream as UTF8. */
  4401. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
  4402. #endif // __JUCE_STRING_JUCEHEADER__
  4403. /*** End of inlined file: juce_String.h ***/
  4404. /**
  4405. Acts as an application-wide logging class.
  4406. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4407. method and this will then be used by all calls to writeToLog.
  4408. The logger class also contains methods for writing messages to the debugger's
  4409. output stream.
  4410. @see FileLogger
  4411. */
  4412. class JUCE_API Logger
  4413. {
  4414. public:
  4415. /** Destructor. */
  4416. virtual ~Logger();
  4417. /** Sets the current logging class to use.
  4418. Note that the object passed in won't be deleted when no longer needed.
  4419. A null pointer can be passed-in to disable any logging.
  4420. If deleteOldLogger is set to true, the existing logger will be
  4421. deleted (if there is one).
  4422. */
  4423. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4424. bool deleteOldLogger = false);
  4425. /** Writes a string to the current logger.
  4426. This will pass the string to the logger's logMessage() method if a logger
  4427. has been set.
  4428. @see logMessage
  4429. */
  4430. static void JUCE_CALLTYPE writeToLog (const String& message);
  4431. /** Writes a message to the standard error stream.
  4432. This can be called directly, or by using the DBG() macro in
  4433. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4434. */
  4435. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4436. protected:
  4437. Logger();
  4438. /** This is overloaded by subclasses to implement custom logging behaviour.
  4439. @see setCurrentLogger
  4440. */
  4441. virtual void logMessage (const String& message) = 0;
  4442. private:
  4443. static Logger* currentLogger;
  4444. };
  4445. #endif // __JUCE_LOGGER_JUCEHEADER__
  4446. /*** End of inlined file: juce_Logger.h ***/
  4447. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4448. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4449. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4450. /**
  4451. Embedding an instance of this class inside another class can be used as a low-overhead
  4452. way of detecting leaked instances.
  4453. This class keeps an internal static count of the number of instances that are
  4454. active, so that when the app is shutdown and the static destructors are called,
  4455. it can check whether there are any left-over instances that may have been leaked.
  4456. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4457. class declaration. Have a look through the juce codebase for examples, it's used
  4458. in most of the classes.
  4459. */
  4460. template <class OwnerClass>
  4461. class LeakedObjectDetector
  4462. {
  4463. public:
  4464. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  4465. LeakedObjectDetector (const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  4466. ~LeakedObjectDetector()
  4467. {
  4468. if (--(getCounter().numObjects) < 0)
  4469. {
  4470. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4471. /** If you hit this, then you've managed to delete more instances of this class than you've
  4472. created.. That indicates that you're deleting some dangling pointers.
  4473. Note that although this assertion will have been triggered during a destructor, it might
  4474. not be this particular deletion that's at fault - the incorrect one may have happened
  4475. at an earlier point in the program, and simply not been detected until now.
  4476. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4477. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4478. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4479. */
  4480. jassertfalse;
  4481. }
  4482. }
  4483. private:
  4484. class LeakCounter
  4485. {
  4486. public:
  4487. LeakCounter() noexcept {}
  4488. ~LeakCounter()
  4489. {
  4490. if (numObjects.value > 0)
  4491. {
  4492. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4493. /** If you hit this, then you've leaked one or more objects of the type specified by
  4494. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4495. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4496. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4497. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4498. */
  4499. jassertfalse;
  4500. }
  4501. }
  4502. Atomic<int> numObjects;
  4503. };
  4504. static const char* getLeakedObjectClassName()
  4505. {
  4506. return OwnerClass::getLeakedObjectClassName();
  4507. }
  4508. static LeakCounter& getCounter() noexcept
  4509. {
  4510. static LeakCounter counter;
  4511. return counter;
  4512. }
  4513. };
  4514. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4515. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4516. /** This macro lets you embed a leak-detecting object inside a class.
  4517. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4518. of the class declaration. E.g.
  4519. @code
  4520. class MyClass
  4521. {
  4522. public:
  4523. MyClass();
  4524. void blahBlah();
  4525. private:
  4526. JUCE_LEAK_DETECTOR (MyClass);
  4527. };@endcode
  4528. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4529. */
  4530. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4531. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4532. static const char* getLeakedObjectClassName() noexcept { return #OwnerClass; } \
  4533. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4534. #else
  4535. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4536. #endif
  4537. #endif
  4538. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4539. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4540. #undef TYPE_BOOL // (stupidly-named CoreServices definition which interferes with other libraries).
  4541. END_JUCE_NAMESPACE
  4542. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4543. /*** End of inlined file: juce_StandardHeader.h ***/
  4544. BEGIN_JUCE_NAMESPACE
  4545. #if JUCE_MSVC
  4546. // this is set explicitly in case the app is using a different packing size.
  4547. #pragma pack (push, 8)
  4548. #pragma warning (push)
  4549. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4550. #ifdef __INTEL_COMPILER
  4551. #pragma warning (disable: 1125)
  4552. #endif
  4553. #endif
  4554. // this is where all the class header files get brought in..
  4555. /*** Start of inlined file: juce_core_includes.h ***/
  4556. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4557. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4558. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4559. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4560. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4561. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4562. /**
  4563. Encapsulates the logic required to implement a lock-free FIFO.
  4564. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4565. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4566. its position and status when reading or writing to it.
  4567. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4568. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4569. outgoing block should be read from.
  4570. e.g.
  4571. @code
  4572. class MyFifo
  4573. {
  4574. public:
  4575. MyFifo() : abstractFifo (1024)
  4576. {
  4577. }
  4578. void addToFifo (const int* someData, int numItems)
  4579. {
  4580. int start1, size1, start2, size2;
  4581. prepareToWrite (numItems, start1, size1, start2, size2);
  4582. if (size1 > 0)
  4583. copySomeData (myBuffer + start1, someData, size1);
  4584. if (size2 > 0)
  4585. copySomeData (myBuffer + start2, someData + size1, size2);
  4586. finishedWrite (size1 + size2);
  4587. }
  4588. void readFromFifo (int* someData, int numItems)
  4589. {
  4590. int start1, size1, start2, size2;
  4591. prepareToRead (numSamples, start1, size1, start2, size2);
  4592. if (size1 > 0)
  4593. copySomeData (someData, myBuffer + start1, size1);
  4594. if (size2 > 0)
  4595. copySomeData (someData + size1, myBuffer + start2, size2);
  4596. finishedRead (size1 + size2);
  4597. }
  4598. private:
  4599. AbstractFifo abstractFifo;
  4600. int myBuffer [1024];
  4601. };
  4602. @endcode
  4603. */
  4604. class JUCE_API AbstractFifo
  4605. {
  4606. public:
  4607. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4608. AbstractFifo (int capacity) noexcept;
  4609. /** Destructor */
  4610. ~AbstractFifo();
  4611. /** Returns the total size of the buffer being managed. */
  4612. int getTotalSize() const noexcept;
  4613. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4614. int getFreeSpace() const noexcept;
  4615. /** Returns the number of items that can currently be read from the buffer. */
  4616. int getNumReady() const noexcept;
  4617. /** Clears the buffer positions, so that it appears empty. */
  4618. void reset() noexcept;
  4619. /** Changes the buffer's total size.
  4620. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4621. might overlap with a call to any other method in this class!
  4622. */
  4623. void setTotalSize (int newSize) noexcept;
  4624. /** Returns the location within the buffer at which an incoming block of data should be written.
  4625. Because the section of data that you want to add to the buffer may overlap the end
  4626. and wrap around to the start, two blocks within your buffer are returned, and you
  4627. should copy your data into the first one, with any remaining data spilling over into
  4628. the second.
  4629. If the number of items you ask for is too large to fit within the buffer's free space, then
  4630. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4631. may decide to keep waiting and re-trying the method until there's enough space available.
  4632. After calling this method, if you choose to write your data into the blocks returned, you
  4633. must call finishedWrite() to tell the FIFO how much data you actually added.
  4634. e.g.
  4635. @code
  4636. void addToFifo (const int* someData, int numItems)
  4637. {
  4638. int start1, size1, start2, size2;
  4639. prepareToWrite (numItems, start1, size1, start2, size2);
  4640. if (size1 > 0)
  4641. copySomeData (myBuffer + start1, someData, size1);
  4642. if (size2 > 0)
  4643. copySomeData (myBuffer + start2, someData + size1, size2);
  4644. finishedWrite (size1 + size2);
  4645. }
  4646. @endcode
  4647. @param numToWrite indicates how many items you'd like to add to the buffer
  4648. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4649. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4650. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4651. the first block should be written
  4652. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4653. @see finishedWrite
  4654. */
  4655. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4656. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4657. @see prepareToWrite
  4658. */
  4659. void finishedWrite (int numWritten) noexcept;
  4660. /** Returns the location within the buffer from which the next block of data should be read.
  4661. Because the section of data that you want to read from the buffer may overlap the end
  4662. and wrap around to the start, two blocks within your buffer are returned, and you
  4663. should read from both of them.
  4664. If the number of items you ask for is greater than the amount of data available, then
  4665. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4666. may decide to keep waiting and re-trying the method until there's enough data available.
  4667. After calling this method, if you choose to read the data, you must call finishedRead() to
  4668. tell the FIFO how much data you have consumed.
  4669. e.g.
  4670. @code
  4671. void readFromFifo (int* someData, int numItems)
  4672. {
  4673. int start1, size1, start2, size2;
  4674. prepareToRead (numSamples, start1, size1, start2, size2);
  4675. if (size1 > 0)
  4676. copySomeData (someData, myBuffer + start1, size1);
  4677. if (size2 > 0)
  4678. copySomeData (someData + size1, myBuffer + start2, size2);
  4679. finishedRead (size1 + size2);
  4680. }
  4681. @endcode
  4682. @param numWanted indicates how many items you'd like to add to the buffer
  4683. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4684. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4685. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4686. the first block should be written
  4687. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4688. @see finishedRead
  4689. */
  4690. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4691. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4692. @see prepareToRead
  4693. */
  4694. void finishedRead (int numRead) noexcept;
  4695. private:
  4696. int bufferSize;
  4697. Atomic <int> validStart, validEnd;
  4698. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4699. };
  4700. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4701. /*** End of inlined file: juce_AbstractFifo.h ***/
  4702. #endif
  4703. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4704. /*** Start of inlined file: juce_Array.h ***/
  4705. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4706. #define __JUCE_ARRAY_JUCEHEADER__
  4707. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4708. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4709. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4710. /*** Start of inlined file: juce_HeapBlock.h ***/
  4711. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4712. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4713. /**
  4714. Very simple container class to hold a pointer to some data on the heap.
  4715. When you need to allocate some heap storage for something, always try to use
  4716. this class instead of allocating the memory directly using malloc/free.
  4717. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4718. as an char*, but as long as you allocate it on the stack or as a class member,
  4719. it's almost impossible for it to leak memory.
  4720. It also makes your code much more concise and readable than doing the same thing
  4721. using direct allocations,
  4722. E.g. instead of this:
  4723. @code
  4724. int* temp = (int*) malloc (1024 * sizeof (int));
  4725. memcpy (temp, xyz, 1024 * sizeof (int));
  4726. free (temp);
  4727. temp = (int*) calloc (2048 * sizeof (int));
  4728. temp[0] = 1234;
  4729. memcpy (foobar, temp, 2048 * sizeof (int));
  4730. free (temp);
  4731. @endcode
  4732. ..you could just write this:
  4733. @code
  4734. HeapBlock <int> temp (1024);
  4735. memcpy (temp, xyz, 1024 * sizeof (int));
  4736. temp.calloc (2048);
  4737. temp[0] = 1234;
  4738. memcpy (foobar, temp, 2048 * sizeof (int));
  4739. @endcode
  4740. The class is extremely lightweight, containing only a pointer to the
  4741. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4742. as their less object-oriented counterparts. Despite adding safety, you probably
  4743. won't sacrifice any performance by using this in place of normal pointers.
  4744. @see Array, OwnedArray, MemoryBlock
  4745. */
  4746. template <class ElementType>
  4747. class HeapBlock
  4748. {
  4749. public:
  4750. /** Creates a HeapBlock which is initially just a null pointer.
  4751. After creation, you can resize the array using the malloc(), calloc(),
  4752. or realloc() methods.
  4753. */
  4754. HeapBlock() noexcept : data (nullptr)
  4755. {
  4756. }
  4757. /** Creates a HeapBlock containing a number of elements.
  4758. The contents of the block are undefined, as it will have been created by a
  4759. malloc call.
  4760. If you want an array of zero values, you can use the calloc() method instead.
  4761. */
  4762. explicit HeapBlock (const size_t numElements)
  4763. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4764. {
  4765. }
  4766. /** Destructor.
  4767. This will free the data, if any has been allocated.
  4768. */
  4769. ~HeapBlock()
  4770. {
  4771. ::free (data);
  4772. }
  4773. /** Returns a raw pointer to the allocated data.
  4774. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4775. freed by calling the free() method.
  4776. */
  4777. inline operator ElementType*() const noexcept { return data; }
  4778. /** Returns a raw pointer to the allocated data.
  4779. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4780. freed by calling the free() method.
  4781. */
  4782. inline ElementType* getData() const noexcept { return data; }
  4783. /** Returns a void pointer to the allocated data.
  4784. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4785. freed by calling the free() method.
  4786. */
  4787. inline operator void*() const noexcept { return static_cast <void*> (data); }
  4788. /** Returns a void pointer to the allocated data.
  4789. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4790. freed by calling the free() method.
  4791. */
  4792. inline operator const void*() const noexcept { return static_cast <const void*> (data); }
  4793. /** Lets you use indirect calls to the first element in the array.
  4794. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4795. be referencing a null pointer.
  4796. */
  4797. inline ElementType* operator->() const noexcept { return data; }
  4798. /** Returns a reference to one of the data elements.
  4799. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4800. has no idea of the size it currently has allocated.
  4801. */
  4802. template <typename IndexType>
  4803. inline ElementType& operator[] (IndexType index) const noexcept { return data [index]; }
  4804. /** Returns a pointer to a data element at an offset from the start of the array.
  4805. This is the same as doing pointer arithmetic on the raw pointer itself.
  4806. */
  4807. template <typename IndexType>
  4808. inline ElementType* operator+ (IndexType index) const noexcept { return data + index; }
  4809. /** Compares the pointer with another pointer.
  4810. This can be handy for checking whether this is a null pointer.
  4811. */
  4812. inline bool operator== (const ElementType* const otherPointer) const noexcept { return otherPointer == data; }
  4813. /** Compares the pointer with another pointer.
  4814. This can be handy for checking whether this is a null pointer.
  4815. */
  4816. inline bool operator!= (const ElementType* const otherPointer) const noexcept { return otherPointer != data; }
  4817. /** Allocates a specified amount of memory.
  4818. This uses the normal malloc to allocate an amount of memory for this object.
  4819. Any previously allocated memory will be freed by this method.
  4820. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4821. you wouldn't need to specify the second parameter, but it can be handy if you need
  4822. to allocate a size in bytes rather than in terms of the number of elements.
  4823. The data that is allocated will be freed when this object is deleted, or when you
  4824. call free() or any of the allocation methods.
  4825. */
  4826. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4827. {
  4828. ::free (data);
  4829. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4830. }
  4831. /** Allocates a specified amount of memory and clears it.
  4832. This does the same job as the malloc() method, but clears the memory that it allocates.
  4833. */
  4834. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4835. {
  4836. ::free (data);
  4837. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4838. }
  4839. /** Allocates a specified amount of memory and optionally clears it.
  4840. This does the same job as either malloc() or calloc(), depending on the
  4841. initialiseToZero parameter.
  4842. */
  4843. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4844. {
  4845. ::free (data);
  4846. if (initialiseToZero)
  4847. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4848. else
  4849. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4850. }
  4851. /** Re-allocates a specified amount of memory.
  4852. The semantics of this method are the same as malloc() and calloc(), but it
  4853. uses realloc() to keep as much of the existing data as possible.
  4854. */
  4855. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4856. {
  4857. if (data == nullptr)
  4858. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4859. else
  4860. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4861. }
  4862. /** Frees any currently-allocated data.
  4863. This will free the data and reset this object to be a null pointer.
  4864. */
  4865. void free()
  4866. {
  4867. ::free (data);
  4868. data = nullptr;
  4869. }
  4870. /** Swaps this object's data with the data of another HeapBlock.
  4871. The two objects simply exchange their data pointers.
  4872. */
  4873. void swapWith (HeapBlock <ElementType>& other) noexcept
  4874. {
  4875. std::swap (data, other.data);
  4876. }
  4877. /** This fills the block with zeros, up to the number of elements specified.
  4878. Since the block has no way of knowing its own size, you must make sure that the number of
  4879. elements you specify doesn't exceed the allocated size.
  4880. */
  4881. void clear (size_t numElements) noexcept
  4882. {
  4883. zeromem (data, sizeof (ElementType) * numElements);
  4884. }
  4885. private:
  4886. ElementType* data;
  4887. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4888. };
  4889. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4890. /*** End of inlined file: juce_HeapBlock.h ***/
  4891. /**
  4892. Implements some basic array storage allocation functions.
  4893. This class isn't really for public use - it's used by the other
  4894. array classes, but might come in handy for some purposes.
  4895. It inherits from a critical section class to allow the arrays to use
  4896. the "empty base class optimisation" pattern to reduce their footprint.
  4897. @see Array, OwnedArray, ReferenceCountedArray
  4898. */
  4899. template <class ElementType, class TypeOfCriticalSectionToUse>
  4900. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4901. {
  4902. public:
  4903. /** Creates an empty array. */
  4904. ArrayAllocationBase() noexcept
  4905. : numAllocated (0)
  4906. {
  4907. }
  4908. /** Destructor. */
  4909. ~ArrayAllocationBase()
  4910. {
  4911. }
  4912. /** Changes the amount of storage allocated.
  4913. This will retain any data currently held in the array, and either add or
  4914. remove extra space at the end.
  4915. @param numElements the number of elements that are needed
  4916. */
  4917. void setAllocatedSize (const int numElements)
  4918. {
  4919. if (numAllocated != numElements)
  4920. {
  4921. if (numElements > 0)
  4922. elements.realloc (numElements);
  4923. else
  4924. elements.free();
  4925. numAllocated = numElements;
  4926. }
  4927. }
  4928. /** Increases the amount of storage allocated if it is less than a given amount.
  4929. This will retain any data currently held in the array, but will add
  4930. extra space at the end to make sure there it's at least as big as the size
  4931. passed in. If it's already bigger, no action is taken.
  4932. @param minNumElements the minimum number of elements that are needed
  4933. */
  4934. void ensureAllocatedSize (const int minNumElements)
  4935. {
  4936. if (minNumElements > numAllocated)
  4937. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4938. }
  4939. /** Minimises the amount of storage allocated so that it's no more than
  4940. the given number of elements.
  4941. */
  4942. void shrinkToNoMoreThan (const int maxNumElements)
  4943. {
  4944. if (maxNumElements < numAllocated)
  4945. setAllocatedSize (maxNumElements);
  4946. }
  4947. /** Swap the contents of two objects. */
  4948. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) noexcept
  4949. {
  4950. elements.swapWith (other.elements);
  4951. std::swap (numAllocated, other.numAllocated);
  4952. }
  4953. HeapBlock <ElementType> elements;
  4954. int numAllocated;
  4955. private:
  4956. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4957. };
  4958. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4959. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4960. /*** Start of inlined file: juce_ElementComparator.h ***/
  4961. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4962. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4963. /**
  4964. Sorts a range of elements in an array.
  4965. The comparator object that is passed-in must define a public method with the following
  4966. signature:
  4967. @code
  4968. int compareElements (ElementType first, ElementType second);
  4969. @endcode
  4970. ..and this method must return:
  4971. - a value of < 0 if the first comes before the second
  4972. - a value of 0 if the two objects are equivalent
  4973. - a value of > 0 if the second comes before the first
  4974. To improve performance, the compareElements() method can be declared as static or const.
  4975. @param comparator an object which defines a compareElements() method
  4976. @param array the array to sort
  4977. @param firstElement the index of the first element of the range to be sorted
  4978. @param lastElement the index of the last element in the range that needs
  4979. sorting (this is inclusive)
  4980. @param retainOrderOfEquivalentItems if true, the order of items that the
  4981. comparator deems the same will be maintained - this will be
  4982. a slower algorithm than if they are allowed to be moved around.
  4983. @see sortArrayRetainingOrder
  4984. */
  4985. template <class ElementType, class ElementComparator>
  4986. static void sortArray (ElementComparator& comparator,
  4987. ElementType* const array,
  4988. int firstElement,
  4989. int lastElement,
  4990. const bool retainOrderOfEquivalentItems)
  4991. {
  4992. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4993. // avoids getting warning messages about the parameter being unused
  4994. if (lastElement > firstElement)
  4995. {
  4996. if (retainOrderOfEquivalentItems)
  4997. {
  4998. for (int i = firstElement; i < lastElement; ++i)
  4999. {
  5000. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5001. {
  5002. std::swap (array[i], array[i + 1]);
  5003. if (i > firstElement)
  5004. i -= 2;
  5005. }
  5006. }
  5007. }
  5008. else
  5009. {
  5010. int fromStack[30], toStack[30];
  5011. int stackIndex = 0;
  5012. for (;;)
  5013. {
  5014. const int size = (lastElement - firstElement) + 1;
  5015. if (size <= 8)
  5016. {
  5017. int j = lastElement;
  5018. int maxIndex;
  5019. while (j > firstElement)
  5020. {
  5021. maxIndex = firstElement;
  5022. for (int k = firstElement + 1; k <= j; ++k)
  5023. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5024. maxIndex = k;
  5025. std::swap (array[j], array[maxIndex]);
  5026. --j;
  5027. }
  5028. }
  5029. else
  5030. {
  5031. const int mid = firstElement + (size >> 1);
  5032. std::swap (array[mid], array[firstElement]);
  5033. int i = firstElement;
  5034. int j = lastElement + 1;
  5035. for (;;)
  5036. {
  5037. while (++i <= lastElement
  5038. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5039. {}
  5040. while (--j > firstElement
  5041. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5042. {}
  5043. if (j < i)
  5044. break;
  5045. std::swap (array[i], array[j]);
  5046. }
  5047. std::swap (array[j], array[firstElement]);
  5048. if (j - 1 - firstElement >= lastElement - i)
  5049. {
  5050. if (firstElement + 1 < j)
  5051. {
  5052. fromStack [stackIndex] = firstElement;
  5053. toStack [stackIndex] = j - 1;
  5054. ++stackIndex;
  5055. }
  5056. if (i < lastElement)
  5057. {
  5058. firstElement = i;
  5059. continue;
  5060. }
  5061. }
  5062. else
  5063. {
  5064. if (i < lastElement)
  5065. {
  5066. fromStack [stackIndex] = i;
  5067. toStack [stackIndex] = lastElement;
  5068. ++stackIndex;
  5069. }
  5070. if (firstElement + 1 < j)
  5071. {
  5072. lastElement = j - 1;
  5073. continue;
  5074. }
  5075. }
  5076. }
  5077. if (--stackIndex < 0)
  5078. break;
  5079. jassert (stackIndex < numElementsInArray (fromStack));
  5080. firstElement = fromStack [stackIndex];
  5081. lastElement = toStack [stackIndex];
  5082. }
  5083. }
  5084. }
  5085. }
  5086. /**
  5087. Searches a sorted array of elements, looking for the index at which a specified value
  5088. should be inserted for it to be in the correct order.
  5089. The comparator object that is passed-in must define a public method with the following
  5090. signature:
  5091. @code
  5092. int compareElements (ElementType first, ElementType second);
  5093. @endcode
  5094. ..and this method must return:
  5095. - a value of < 0 if the first comes before the second
  5096. - a value of 0 if the two objects are equivalent
  5097. - a value of > 0 if the second comes before the first
  5098. To improve performance, the compareElements() method can be declared as static or const.
  5099. @param comparator an object which defines a compareElements() method
  5100. @param array the array to search
  5101. @param newElement the value that is going to be inserted
  5102. @param firstElement the index of the first element to search
  5103. @param lastElement the index of the last element in the range (this is non-inclusive)
  5104. */
  5105. template <class ElementType, class ElementComparator>
  5106. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5107. ElementType* const array,
  5108. const ElementType newElement,
  5109. int firstElement,
  5110. int lastElement)
  5111. {
  5112. jassert (firstElement <= lastElement);
  5113. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5114. // avoids getting warning messages about the parameter being unused
  5115. while (firstElement < lastElement)
  5116. {
  5117. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5118. {
  5119. ++firstElement;
  5120. break;
  5121. }
  5122. else
  5123. {
  5124. const int halfway = (firstElement + lastElement) >> 1;
  5125. if (halfway == firstElement)
  5126. {
  5127. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5128. ++firstElement;
  5129. break;
  5130. }
  5131. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5132. {
  5133. firstElement = halfway;
  5134. }
  5135. else
  5136. {
  5137. lastElement = halfway;
  5138. }
  5139. }
  5140. }
  5141. return firstElement;
  5142. }
  5143. /**
  5144. A simple ElementComparator class that can be used to sort an array of
  5145. objects that support the '<' operator.
  5146. This will work for primitive types and objects that implement operator<().
  5147. Example: @code
  5148. Array <int> myArray;
  5149. DefaultElementComparator<int> sorter;
  5150. myArray.sort (sorter);
  5151. @endcode
  5152. @see ElementComparator
  5153. */
  5154. template <class ElementType>
  5155. class DefaultElementComparator
  5156. {
  5157. private:
  5158. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5159. public:
  5160. static int compareElements (ParameterType first, ParameterType second)
  5161. {
  5162. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5163. }
  5164. };
  5165. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5166. /*** End of inlined file: juce_ElementComparator.h ***/
  5167. /*** Start of inlined file: juce_CriticalSection.h ***/
  5168. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5169. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5170. /*** Start of inlined file: juce_ScopedLock.h ***/
  5171. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5172. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5173. /**
  5174. Automatically locks and unlocks a mutex object.
  5175. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5176. The templated class could be a CriticalSection, SpinLock, or anything else that
  5177. provides enter() and exit() methods.
  5178. e.g. @code
  5179. CriticalSection myCriticalSection;
  5180. for (;;)
  5181. {
  5182. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5183. // myCriticalSection is now locked
  5184. ...do some stuff...
  5185. // myCriticalSection gets unlocked here.
  5186. }
  5187. @endcode
  5188. @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock
  5189. */
  5190. template <class LockType>
  5191. class GenericScopedLock
  5192. {
  5193. public:
  5194. /** Creates a GenericScopedLock.
  5195. As soon as it is created, this will acquire the lock, and when the GenericScopedLock
  5196. object is deleted, the lock will be released.
  5197. Make sure this object is created and deleted by the same thread,
  5198. otherwise there are no guarantees what will happen! Best just to use it
  5199. as a local stack object, rather than creating one with the new() operator.
  5200. */
  5201. inline explicit GenericScopedLock (const LockType& lock) noexcept : lock_ (lock) { lock.enter(); }
  5202. /** Destructor.
  5203. The lock will be released when the destructor is called.
  5204. Make sure this object is created and deleted by the same thread, otherwise there are
  5205. no guarantees what will happen!
  5206. */
  5207. inline ~GenericScopedLock() noexcept { lock_.exit(); }
  5208. private:
  5209. const LockType& lock_;
  5210. JUCE_DECLARE_NON_COPYABLE (GenericScopedLock);
  5211. };
  5212. /**
  5213. Automatically unlocks and re-locks a mutex object.
  5214. This is the reverse of a GenericScopedLock object - instead of locking the mutex
  5215. for the lifetime of this object, it unlocks it.
  5216. Make sure you don't try to unlock mutexes that aren't actually locked!
  5217. e.g. @code
  5218. CriticalSection myCriticalSection;
  5219. for (;;)
  5220. {
  5221. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5222. // myCriticalSection is now locked
  5223. ... do some stuff with it locked ..
  5224. while (xyz)
  5225. {
  5226. ... do some stuff with it locked ..
  5227. const GenericScopedUnlock<CriticalSection> unlocker (myCriticalSection);
  5228. // myCriticalSection is now unlocked for the remainder of this block,
  5229. // and re-locked at the end.
  5230. ...do some stuff with it unlocked ...
  5231. }
  5232. // myCriticalSection gets unlocked here.
  5233. }
  5234. @endcode
  5235. @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock
  5236. */
  5237. template <class LockType>
  5238. class GenericScopedUnlock
  5239. {
  5240. public:
  5241. /** Creates a GenericScopedUnlock.
  5242. As soon as it is created, this will unlock the CriticalSection, and
  5243. when the ScopedLock object is deleted, the CriticalSection will
  5244. be re-locked.
  5245. Make sure this object is created and deleted by the same thread,
  5246. otherwise there are no guarantees what will happen! Best just to use it
  5247. as a local stack object, rather than creating one with the new() operator.
  5248. */
  5249. inline explicit GenericScopedUnlock (const LockType& lock) noexcept : lock_ (lock) { lock.exit(); }
  5250. /** Destructor.
  5251. The CriticalSection will be unlocked when the destructor is called.
  5252. Make sure this object is created and deleted by the same thread,
  5253. otherwise there are no guarantees what will happen!
  5254. */
  5255. inline ~GenericScopedUnlock() noexcept { lock_.enter(); }
  5256. private:
  5257. const LockType& lock_;
  5258. JUCE_DECLARE_NON_COPYABLE (GenericScopedUnlock);
  5259. };
  5260. /**
  5261. Automatically locks and unlocks a mutex object.
  5262. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5263. The templated class could be a CriticalSection, SpinLock, or anything else that
  5264. provides enter() and exit() methods.
  5265. e.g. @code
  5266. CriticalSection myCriticalSection;
  5267. for (;;)
  5268. {
  5269. const GenericScopedTryLock<CriticalSection> myScopedTryLock (myCriticalSection);
  5270. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5271. // should test this with the isLocked() method before doing your thread-unsafe
  5272. // action..
  5273. if (myScopedTryLock.isLocked())
  5274. {
  5275. ...do some stuff...
  5276. }
  5277. else
  5278. {
  5279. ..our attempt at locking failed because another thread had already locked it..
  5280. }
  5281. // myCriticalSection gets unlocked here (if it was locked)
  5282. }
  5283. @endcode
  5284. @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock
  5285. */
  5286. template <class LockType>
  5287. class GenericScopedTryLock
  5288. {
  5289. public:
  5290. /** Creates a GenericScopedTryLock.
  5291. As soon as it is created, this will attempt to acquire the lock, and when the
  5292. GenericScopedTryLock is deleted, the lock will be released (if the lock was
  5293. successfully acquired).
  5294. Make sure this object is created and deleted by the same thread,
  5295. otherwise there are no guarantees what will happen! Best just to use it
  5296. as a local stack object, rather than creating one with the new() operator.
  5297. */
  5298. inline explicit GenericScopedTryLock (const LockType& lock) noexcept
  5299. : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  5300. /** Destructor.
  5301. The mutex will be unlocked (if it had been successfully locked) when the
  5302. destructor is called.
  5303. Make sure this object is created and deleted by the same thread,
  5304. otherwise there are no guarantees what will happen!
  5305. */
  5306. inline ~GenericScopedTryLock() noexcept { if (lockWasSuccessful) lock_.exit(); }
  5307. /** Returns true if the mutex was successfully locked. */
  5308. bool isLocked() const noexcept { return lockWasSuccessful; }
  5309. private:
  5310. const LockType& lock_;
  5311. const bool lockWasSuccessful;
  5312. JUCE_DECLARE_NON_COPYABLE (GenericScopedTryLock);
  5313. };
  5314. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5315. /*** End of inlined file: juce_ScopedLock.h ***/
  5316. /**
  5317. A mutex class.
  5318. A CriticalSection acts as a re-entrant mutex lock. The best way to lock and unlock
  5319. one of these is by using RAII in the form of a local ScopedLock object - have a look
  5320. through the codebase for many examples of how to do this.
  5321. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  5322. */
  5323. class JUCE_API CriticalSection
  5324. {
  5325. public:
  5326. /** Creates a CriticalSection object. */
  5327. CriticalSection() noexcept;
  5328. /** Destructor.
  5329. If the critical section is deleted whilst locked, any subsequent behaviour
  5330. is unpredictable.
  5331. */
  5332. ~CriticalSection() noexcept;
  5333. /** Acquires the lock.
  5334. If the lock is already held by the caller thread, the method returns immediately.
  5335. If the lock is currently held by another thread, this will wait until it becomes free.
  5336. It's strongly recommended that you never call this method directly - instead use the
  5337. ScopedLock class to manage the locking using an RAII pattern instead.
  5338. @see exit, tryEnter, ScopedLock
  5339. */
  5340. void enter() const noexcept;
  5341. /** Attempts to lock this critical section without blocking.
  5342. This method behaves identically to CriticalSection::enter, except that the caller thread
  5343. does not wait if the lock is currently held by another thread but returns false immediately.
  5344. @returns false if the lock is currently held by another thread, true otherwise.
  5345. @see enter
  5346. */
  5347. bool tryEnter() const noexcept;
  5348. /** Releases the lock.
  5349. If the caller thread hasn't got the lock, this can have unpredictable results.
  5350. If the enter() method has been called multiple times by the thread, each
  5351. call must be matched by a call to exit() before other threads will be allowed
  5352. to take over the lock.
  5353. @see enter, ScopedLock
  5354. */
  5355. void exit() const noexcept;
  5356. /** Provides the type of scoped lock to use with a CriticalSection. */
  5357. typedef GenericScopedLock <CriticalSection> ScopedLockType;
  5358. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  5359. typedef GenericScopedUnlock <CriticalSection> ScopedUnlockType;
  5360. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  5361. typedef GenericScopedTryLock <CriticalSection> ScopedTryLockType;
  5362. private:
  5363. #if JUCE_WINDOWS
  5364. // To avoid including windows.h in the public JUCE headers, we'll just allocate a
  5365. // block of memory here that's big enough to be used internally as a windows critical
  5366. // section structure.
  5367. #if JUCE_64BIT
  5368. uint8 internal [44];
  5369. #else
  5370. uint8 internal [24];
  5371. #endif
  5372. #else
  5373. mutable pthread_mutex_t internal;
  5374. #endif
  5375. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5376. };
  5377. /**
  5378. A class that can be used in place of a real CriticalSection object, but which
  5379. doesn't perform any locking.
  5380. This is currently used by some templated classes, and most compilers should
  5381. manage to optimise it out of existence.
  5382. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  5383. */
  5384. class JUCE_API DummyCriticalSection
  5385. {
  5386. public:
  5387. inline DummyCriticalSection() noexcept {}
  5388. inline ~DummyCriticalSection() noexcept {}
  5389. inline void enter() const noexcept {}
  5390. inline bool tryEnter() const noexcept { return true; }
  5391. inline void exit() const noexcept {}
  5392. /** A dummy scoped-lock type to use with a dummy critical section. */
  5393. struct ScopedLockType
  5394. {
  5395. ScopedLockType (const DummyCriticalSection&) noexcept {}
  5396. };
  5397. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5398. typedef ScopedLockType ScopedUnlockType;
  5399. private:
  5400. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5401. };
  5402. /**
  5403. Automatically locks and unlocks a CriticalSection object.
  5404. Use one of these as a local variable to provide RAII-based locking of a CriticalSection.
  5405. e.g. @code
  5406. CriticalSection myCriticalSection;
  5407. for (;;)
  5408. {
  5409. const ScopedLock myScopedLock (myCriticalSection);
  5410. // myCriticalSection is now locked
  5411. ...do some stuff...
  5412. // myCriticalSection gets unlocked here.
  5413. }
  5414. @endcode
  5415. @see CriticalSection, ScopedUnlock
  5416. */
  5417. typedef CriticalSection::ScopedLockType ScopedLock;
  5418. /**
  5419. Automatically unlocks and re-locks a CriticalSection object.
  5420. This is the reverse of a ScopedLock object - instead of locking the critical
  5421. section for the lifetime of this object, it unlocks it.
  5422. Make sure you don't try to unlock critical sections that aren't actually locked!
  5423. e.g. @code
  5424. CriticalSection myCriticalSection;
  5425. for (;;)
  5426. {
  5427. const ScopedLock myScopedLock (myCriticalSection);
  5428. // myCriticalSection is now locked
  5429. ... do some stuff with it locked ..
  5430. while (xyz)
  5431. {
  5432. ... do some stuff with it locked ..
  5433. const ScopedUnlock unlocker (myCriticalSection);
  5434. // myCriticalSection is now unlocked for the remainder of this block,
  5435. // and re-locked at the end.
  5436. ...do some stuff with it unlocked ...
  5437. }
  5438. // myCriticalSection gets unlocked here.
  5439. }
  5440. @endcode
  5441. @see CriticalSection, ScopedLock
  5442. */
  5443. typedef CriticalSection::ScopedUnlockType ScopedUnlock;
  5444. /**
  5445. Automatically tries to lock and unlock a CriticalSection object.
  5446. Use one of these as a local variable to control access to a CriticalSection.
  5447. e.g. @code
  5448. CriticalSection myCriticalSection;
  5449. for (;;)
  5450. {
  5451. const ScopedTryLock myScopedTryLock (myCriticalSection);
  5452. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5453. // should test this with the isLocked() method before doing your thread-unsafe
  5454. // action..
  5455. if (myScopedTryLock.isLocked())
  5456. {
  5457. ...do some stuff...
  5458. }
  5459. else
  5460. {
  5461. ..our attempt at locking failed because another thread had already locked it..
  5462. }
  5463. // myCriticalSection gets unlocked here (if it was locked)
  5464. }
  5465. @endcode
  5466. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  5467. */
  5468. typedef CriticalSection::ScopedTryLockType ScopedTryLock;
  5469. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5470. /*** End of inlined file: juce_CriticalSection.h ***/
  5471. /**
  5472. Holds a resizable array of primitive or copy-by-value objects.
  5473. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5474. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5475. do so, the class must fulfil these requirements:
  5476. - it must have a copy constructor and assignment operator
  5477. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5478. objects whose functionality relies on external pointers or references to themselves can be used.
  5479. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5480. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5481. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5482. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5483. specialised class StringArray, which provides more useful functions.
  5484. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5485. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5486. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5487. */
  5488. template <typename ElementType,
  5489. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5490. class Array
  5491. {
  5492. private:
  5493. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5494. public:
  5495. /** Creates an empty array. */
  5496. Array() noexcept
  5497. : numUsed (0)
  5498. {
  5499. }
  5500. /** Creates a copy of another array.
  5501. @param other the array to copy
  5502. */
  5503. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5504. {
  5505. const ScopedLockType lock (other.getLock());
  5506. numUsed = other.numUsed;
  5507. data.setAllocatedSize (other.numUsed);
  5508. for (int i = 0; i < numUsed; ++i)
  5509. new (data.elements + i) ElementType (other.data.elements[i]);
  5510. }
  5511. /** Initalises from a null-terminated C array of values.
  5512. @param values the array to copy from
  5513. */
  5514. template <typename TypeToCreateFrom>
  5515. explicit Array (const TypeToCreateFrom* values)
  5516. : numUsed (0)
  5517. {
  5518. while (*values != TypeToCreateFrom())
  5519. add (*values++);
  5520. }
  5521. /** Initalises from a C array of values.
  5522. @param values the array to copy from
  5523. @param numValues the number of values in the array
  5524. */
  5525. template <typename TypeToCreateFrom>
  5526. Array (const TypeToCreateFrom* values, int numValues)
  5527. : numUsed (numValues)
  5528. {
  5529. data.setAllocatedSize (numValues);
  5530. for (int i = 0; i < numValues; ++i)
  5531. new (data.elements + i) ElementType (values[i]);
  5532. }
  5533. /** Destructor. */
  5534. ~Array()
  5535. {
  5536. for (int i = 0; i < numUsed; ++i)
  5537. data.elements[i].~ElementType();
  5538. }
  5539. /** Copies another array.
  5540. @param other the array to copy
  5541. */
  5542. Array& operator= (const Array& other)
  5543. {
  5544. if (this != &other)
  5545. {
  5546. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5547. swapWithArray (otherCopy);
  5548. }
  5549. return *this;
  5550. }
  5551. /** Compares this array to another one.
  5552. Two arrays are considered equal if they both contain the same set of
  5553. elements, in the same order.
  5554. @param other the other array to compare with
  5555. */
  5556. template <class OtherArrayType>
  5557. bool operator== (const OtherArrayType& other) const
  5558. {
  5559. const ScopedLockType lock (getLock());
  5560. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  5561. if (numUsed != other.numUsed)
  5562. return false;
  5563. for (int i = numUsed; --i >= 0;)
  5564. if (! (data.elements [i] == other.data.elements [i]))
  5565. return false;
  5566. return true;
  5567. }
  5568. /** Compares this array to another one.
  5569. Two arrays are considered equal if they both contain the same set of
  5570. elements, in the same order.
  5571. @param other the other array to compare with
  5572. */
  5573. template <class OtherArrayType>
  5574. bool operator!= (const OtherArrayType& other) const
  5575. {
  5576. return ! operator== (other);
  5577. }
  5578. /** Removes all elements from the array.
  5579. This will remove all the elements, and free any storage that the array is
  5580. using. To clear the array without freeing the storage, use the clearQuick()
  5581. method instead.
  5582. @see clearQuick
  5583. */
  5584. void clear()
  5585. {
  5586. const ScopedLockType lock (getLock());
  5587. for (int i = 0; i < numUsed; ++i)
  5588. data.elements[i].~ElementType();
  5589. data.setAllocatedSize (0);
  5590. numUsed = 0;
  5591. }
  5592. /** Removes all elements from the array without freeing the array's allocated storage.
  5593. @see clear
  5594. */
  5595. void clearQuick()
  5596. {
  5597. const ScopedLockType lock (getLock());
  5598. for (int i = 0; i < numUsed; ++i)
  5599. data.elements[i].~ElementType();
  5600. numUsed = 0;
  5601. }
  5602. /** Returns the current number of elements in the array.
  5603. */
  5604. inline int size() const noexcept
  5605. {
  5606. return numUsed;
  5607. }
  5608. /** Returns one of the elements in the array.
  5609. If the index passed in is beyond the range of valid elements, this
  5610. will return zero.
  5611. If you're certain that the index will always be a valid element, you
  5612. can call getUnchecked() instead, which is faster.
  5613. @param index the index of the element being requested (0 is the first element in the array)
  5614. @see getUnchecked, getFirst, getLast
  5615. */
  5616. const ElementType operator[] (const int index) const
  5617. {
  5618. const ScopedLockType lock (getLock());
  5619. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5620. : ElementType();
  5621. }
  5622. /** Returns one of the elements in the array, without checking the index passed in.
  5623. Unlike the operator[] method, this will try to return an element without
  5624. checking that the index is within the bounds of the array, so should only
  5625. be used when you're confident that it will always be a valid index.
  5626. @param index the index of the element being requested (0 is the first element in the array)
  5627. @see operator[], getFirst, getLast
  5628. */
  5629. inline const ElementType getUnchecked (const int index) const
  5630. {
  5631. const ScopedLockType lock (getLock());
  5632. jassert (isPositiveAndBelow (index, numUsed));
  5633. return data.elements [index];
  5634. }
  5635. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5636. This is like getUnchecked, but returns a direct reference to the element, so that
  5637. you can alter it directly. Obviously this can be dangerous, so only use it when
  5638. absolutely necessary.
  5639. @param index the index of the element being requested (0 is the first element in the array)
  5640. @see operator[], getFirst, getLast
  5641. */
  5642. inline ElementType& getReference (const int index) const noexcept
  5643. {
  5644. const ScopedLockType lock (getLock());
  5645. jassert (isPositiveAndBelow (index, numUsed));
  5646. return data.elements [index];
  5647. }
  5648. /** Returns the first element in the array, or 0 if the array is empty.
  5649. @see operator[], getUnchecked, getLast
  5650. */
  5651. inline ElementType getFirst() const
  5652. {
  5653. const ScopedLockType lock (getLock());
  5654. return (numUsed > 0) ? data.elements [0]
  5655. : ElementType();
  5656. }
  5657. /** Returns the last element in the array, or 0 if the array is empty.
  5658. @see operator[], getUnchecked, getFirst
  5659. */
  5660. inline ElementType getLast() const
  5661. {
  5662. const ScopedLockType lock (getLock());
  5663. return (numUsed > 0) ? data.elements [numUsed - 1]
  5664. : ElementType();
  5665. }
  5666. /** Returns a pointer to the actual array data.
  5667. This pointer will only be valid until the next time a non-const method
  5668. is called on the array.
  5669. */
  5670. inline ElementType* getRawDataPointer() noexcept
  5671. {
  5672. return data.elements;
  5673. }
  5674. /** Returns a pointer to the first element in the array.
  5675. This method is provided for compatibility with standard C++ iteration mechanisms.
  5676. */
  5677. inline ElementType* begin() const noexcept
  5678. {
  5679. return data.elements;
  5680. }
  5681. /** Returns a pointer to the element which follows the last element in the array.
  5682. This method is provided for compatibility with standard C++ iteration mechanisms.
  5683. */
  5684. inline ElementType* end() const noexcept
  5685. {
  5686. return data.elements + numUsed;
  5687. }
  5688. /** Finds the index of the first element which matches the value passed in.
  5689. This will search the array for the given object, and return the index
  5690. of its first occurrence. If the object isn't found, the method will return -1.
  5691. @param elementToLookFor the value or object to look for
  5692. @returns the index of the object, or -1 if it's not found
  5693. */
  5694. int indexOf (ParameterType elementToLookFor) const
  5695. {
  5696. const ScopedLockType lock (getLock());
  5697. const ElementType* e = data.elements.getData();
  5698. const ElementType* const end = e + numUsed;
  5699. for (; e != end; ++e)
  5700. if (elementToLookFor == *e)
  5701. return static_cast <int> (e - data.elements.getData());
  5702. return -1;
  5703. }
  5704. /** Returns true if the array contains at least one occurrence of an object.
  5705. @param elementToLookFor the value or object to look for
  5706. @returns true if the item is found
  5707. */
  5708. bool contains (ParameterType elementToLookFor) const
  5709. {
  5710. const ScopedLockType lock (getLock());
  5711. const ElementType* e = data.elements.getData();
  5712. const ElementType* const end = e + numUsed;
  5713. for (; e != end; ++e)
  5714. if (elementToLookFor == *e)
  5715. return true;
  5716. return false;
  5717. }
  5718. /** Appends a new element at the end of the array.
  5719. @param newElement the new object to add to the array
  5720. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5721. */
  5722. void add (ParameterType newElement)
  5723. {
  5724. const ScopedLockType lock (getLock());
  5725. data.ensureAllocatedSize (numUsed + 1);
  5726. new (data.elements + numUsed++) ElementType (newElement);
  5727. }
  5728. /** Inserts a new element into the array at a given position.
  5729. If the index is less than 0 or greater than the size of the array, the
  5730. element will be added to the end of the array.
  5731. Otherwise, it will be inserted into the array, moving all the later elements
  5732. along to make room.
  5733. @param indexToInsertAt the index at which the new element should be
  5734. inserted (pass in -1 to add it to the end)
  5735. @param newElement the new object to add to the array
  5736. @see add, addSorted, addUsingDefaultSort, set
  5737. */
  5738. void insert (int indexToInsertAt, ParameterType newElement)
  5739. {
  5740. const ScopedLockType lock (getLock());
  5741. data.ensureAllocatedSize (numUsed + 1);
  5742. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5743. {
  5744. ElementType* const insertPos = data.elements + indexToInsertAt;
  5745. const int numberToMove = numUsed - indexToInsertAt;
  5746. if (numberToMove > 0)
  5747. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5748. new (insertPos) ElementType (newElement);
  5749. ++numUsed;
  5750. }
  5751. else
  5752. {
  5753. new (data.elements + numUsed++) ElementType (newElement);
  5754. }
  5755. }
  5756. /** Inserts multiple copies of an element into the array at a given position.
  5757. If the index is less than 0 or greater than the size of the array, the
  5758. element will be added to the end of the array.
  5759. Otherwise, it will be inserted into the array, moving all the later elements
  5760. along to make room.
  5761. @param indexToInsertAt the index at which the new element should be inserted
  5762. @param newElement the new object to add to the array
  5763. @param numberOfTimesToInsertIt how many copies of the value to insert
  5764. @see insert, add, addSorted, set
  5765. */
  5766. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5767. int numberOfTimesToInsertIt)
  5768. {
  5769. if (numberOfTimesToInsertIt > 0)
  5770. {
  5771. const ScopedLockType lock (getLock());
  5772. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5773. ElementType* insertPos;
  5774. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5775. {
  5776. insertPos = data.elements + indexToInsertAt;
  5777. const int numberToMove = numUsed - indexToInsertAt;
  5778. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5779. }
  5780. else
  5781. {
  5782. insertPos = data.elements + numUsed;
  5783. }
  5784. numUsed += numberOfTimesToInsertIt;
  5785. while (--numberOfTimesToInsertIt >= 0)
  5786. new (insertPos++) ElementType (newElement);
  5787. }
  5788. }
  5789. /** Inserts an array of values into this array at a given position.
  5790. If the index is less than 0 or greater than the size of the array, the
  5791. new elements will be added to the end of the array.
  5792. Otherwise, they will be inserted into the array, moving all the later elements
  5793. along to make room.
  5794. @param indexToInsertAt the index at which the first new element should be inserted
  5795. @param newElements the new values to add to the array
  5796. @param numberOfElements how many items are in the array
  5797. @see insert, add, addSorted, set
  5798. */
  5799. void insertArray (int indexToInsertAt,
  5800. const ElementType* newElements,
  5801. int numberOfElements)
  5802. {
  5803. if (numberOfElements > 0)
  5804. {
  5805. const ScopedLockType lock (getLock());
  5806. data.ensureAllocatedSize (numUsed + numberOfElements);
  5807. ElementType* insertPos;
  5808. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5809. {
  5810. insertPos = data.elements + indexToInsertAt;
  5811. const int numberToMove = numUsed - indexToInsertAt;
  5812. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5813. }
  5814. else
  5815. {
  5816. insertPos = data.elements + numUsed;
  5817. }
  5818. numUsed += numberOfElements;
  5819. while (--numberOfElements >= 0)
  5820. new (insertPos++) ElementType (*newElements++);
  5821. }
  5822. }
  5823. /** Appends a new element at the end of the array as long as the array doesn't
  5824. already contain it.
  5825. If the array already contains an element that matches the one passed in, nothing
  5826. will be done.
  5827. @param newElement the new object to add to the array
  5828. */
  5829. void addIfNotAlreadyThere (ParameterType newElement)
  5830. {
  5831. const ScopedLockType lock (getLock());
  5832. if (! contains (newElement))
  5833. add (newElement);
  5834. }
  5835. /** Replaces an element with a new value.
  5836. If the index is less than zero, this method does nothing.
  5837. If the index is beyond the end of the array, the item is added to the end of the array.
  5838. @param indexToChange the index whose value you want to change
  5839. @param newValue the new value to set for this index.
  5840. @see add, insert
  5841. */
  5842. void set (const int indexToChange, ParameterType newValue)
  5843. {
  5844. jassert (indexToChange >= 0);
  5845. const ScopedLockType lock (getLock());
  5846. if (isPositiveAndBelow (indexToChange, numUsed))
  5847. {
  5848. data.elements [indexToChange] = newValue;
  5849. }
  5850. else if (indexToChange >= 0)
  5851. {
  5852. data.ensureAllocatedSize (numUsed + 1);
  5853. new (data.elements + numUsed++) ElementType (newValue);
  5854. }
  5855. }
  5856. /** Replaces an element with a new value without doing any bounds-checking.
  5857. This just sets a value directly in the array's internal storage, so you'd
  5858. better make sure it's in range!
  5859. @param indexToChange the index whose value you want to change
  5860. @param newValue the new value to set for this index.
  5861. @see set, getUnchecked
  5862. */
  5863. void setUnchecked (const int indexToChange, ParameterType newValue)
  5864. {
  5865. const ScopedLockType lock (getLock());
  5866. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5867. data.elements [indexToChange] = newValue;
  5868. }
  5869. /** Adds elements from an array to the end of this array.
  5870. @param elementsToAdd the array of elements to add
  5871. @param numElementsToAdd how many elements are in this other array
  5872. @see add
  5873. */
  5874. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5875. {
  5876. const ScopedLockType lock (getLock());
  5877. if (numElementsToAdd > 0)
  5878. {
  5879. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5880. while (--numElementsToAdd >= 0)
  5881. {
  5882. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5883. ++numUsed;
  5884. }
  5885. }
  5886. }
  5887. /** This swaps the contents of this array with those of another array.
  5888. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5889. because it just swaps their internal pointers.
  5890. */
  5891. void swapWithArray (Array& otherArray) noexcept
  5892. {
  5893. const ScopedLockType lock1 (getLock());
  5894. const ScopedLockType lock2 (otherArray.getLock());
  5895. data.swapWith (otherArray.data);
  5896. swapVariables (numUsed, otherArray.numUsed);
  5897. }
  5898. /** Adds elements from another array to the end of this array.
  5899. @param arrayToAddFrom the array from which to copy the elements
  5900. @param startIndex the first element of the other array to start copying from
  5901. @param numElementsToAdd how many elements to add from the other array. If this
  5902. value is negative or greater than the number of available elements,
  5903. all available elements will be copied.
  5904. @see add
  5905. */
  5906. template <class OtherArrayType>
  5907. void addArray (const OtherArrayType& arrayToAddFrom,
  5908. int startIndex = 0,
  5909. int numElementsToAdd = -1)
  5910. {
  5911. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5912. {
  5913. const ScopedLockType lock2 (getLock());
  5914. if (startIndex < 0)
  5915. {
  5916. jassertfalse;
  5917. startIndex = 0;
  5918. }
  5919. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5920. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5921. while (--numElementsToAdd >= 0)
  5922. add (arrayToAddFrom.getUnchecked (startIndex++));
  5923. }
  5924. }
  5925. /** This will enlarge or shrink the array to the given number of elements, by adding
  5926. or removing items from its end.
  5927. If the array is smaller than the given target size, empty elements will be appended
  5928. until its size is as specified. If its size is larger than the target, items will be
  5929. removed from its end to shorten it.
  5930. */
  5931. void resize (const int targetNumItems)
  5932. {
  5933. jassert (targetNumItems >= 0);
  5934. const int numToAdd = targetNumItems - numUsed;
  5935. if (numToAdd > 0)
  5936. insertMultiple (numUsed, ElementType(), numToAdd);
  5937. else if (numToAdd < 0)
  5938. removeRange (targetNumItems, -numToAdd);
  5939. }
  5940. /** Inserts a new element into the array, assuming that the array is sorted.
  5941. This will use a comparator to find the position at which the new element
  5942. should go. If the array isn't sorted, the behaviour of this
  5943. method will be unpredictable.
  5944. @param comparator the comparator to use to compare the elements - see the sort()
  5945. method for details about the form this object should take
  5946. @param newElement the new element to insert to the array
  5947. @returns the index at which the new item was added
  5948. @see addUsingDefaultSort, add, sort
  5949. */
  5950. template <class ElementComparator>
  5951. int addSorted (ElementComparator& comparator, ParameterType newElement)
  5952. {
  5953. const ScopedLockType lock (getLock());
  5954. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  5955. insert (index, newElement);
  5956. return index;
  5957. }
  5958. /** Inserts a new element into the array, assuming that the array is sorted.
  5959. This will use the DefaultElementComparator class for sorting, so your ElementType
  5960. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5961. method will be unpredictable.
  5962. @param newElement the new element to insert to the array
  5963. @see addSorted, sort
  5964. */
  5965. void addUsingDefaultSort (ParameterType newElement)
  5966. {
  5967. DefaultElementComparator <ElementType> comparator;
  5968. addSorted (comparator, newElement);
  5969. }
  5970. /** Finds the index of an element in the array, assuming that the array is sorted.
  5971. This will use a comparator to do a binary-chop to find the index of the given
  5972. element, if it exists. If the array isn't sorted, the behaviour of this
  5973. method will be unpredictable.
  5974. @param comparator the comparator to use to compare the elements - see the sort()
  5975. method for details about the form this object should take
  5976. @param elementToLookFor the element to search for
  5977. @returns the index of the element, or -1 if it's not found
  5978. @see addSorted, sort
  5979. */
  5980. template <class ElementComparator>
  5981. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  5982. {
  5983. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5984. // avoids getting warning messages about the parameter being unused
  5985. const ScopedLockType lock (getLock());
  5986. int start = 0;
  5987. int end = numUsed;
  5988. for (;;)
  5989. {
  5990. if (start >= end)
  5991. {
  5992. return -1;
  5993. }
  5994. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  5995. {
  5996. return start;
  5997. }
  5998. else
  5999. {
  6000. const int halfway = (start + end) >> 1;
  6001. if (halfway == start)
  6002. return -1;
  6003. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  6004. start = halfway;
  6005. else
  6006. end = halfway;
  6007. }
  6008. }
  6009. }
  6010. /** Removes an element from the array.
  6011. This will remove the element at a given index, and move back
  6012. all the subsequent elements to close the gap.
  6013. If the index passed in is out-of-range, nothing will happen.
  6014. @param indexToRemove the index of the element to remove
  6015. @returns the element that has been removed
  6016. @see removeValue, removeRange
  6017. */
  6018. ElementType remove (const int indexToRemove)
  6019. {
  6020. const ScopedLockType lock (getLock());
  6021. if (isPositiveAndBelow (indexToRemove, numUsed))
  6022. {
  6023. --numUsed;
  6024. ElementType* const e = data.elements + indexToRemove;
  6025. ElementType removed (*e);
  6026. e->~ElementType();
  6027. const int numberToShift = numUsed - indexToRemove;
  6028. if (numberToShift > 0)
  6029. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  6030. if ((numUsed << 1) < data.numAllocated)
  6031. minimiseStorageOverheads();
  6032. return removed;
  6033. }
  6034. else
  6035. {
  6036. return ElementType();
  6037. }
  6038. }
  6039. /** Removes an item from the array.
  6040. This will remove the first occurrence of the given element from the array.
  6041. If the item isn't found, no action is taken.
  6042. @param valueToRemove the object to try to remove
  6043. @see remove, removeRange
  6044. */
  6045. void removeValue (ParameterType valueToRemove)
  6046. {
  6047. const ScopedLockType lock (getLock());
  6048. ElementType* const e = data.elements;
  6049. for (int i = 0; i < numUsed; ++i)
  6050. {
  6051. if (valueToRemove == e[i])
  6052. {
  6053. remove (i);
  6054. break;
  6055. }
  6056. }
  6057. }
  6058. /** Removes a range of elements from the array.
  6059. This will remove a set of elements, starting from the given index,
  6060. and move subsequent elements down to close the gap.
  6061. If the range extends beyond the bounds of the array, it will
  6062. be safely clipped to the size of the array.
  6063. @param startIndex the index of the first element to remove
  6064. @param numberToRemove how many elements should be removed
  6065. @see remove, removeValue
  6066. */
  6067. void removeRange (int startIndex, int numberToRemove)
  6068. {
  6069. const ScopedLockType lock (getLock());
  6070. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  6071. startIndex = jlimit (0, numUsed, startIndex);
  6072. if (endIndex > startIndex)
  6073. {
  6074. ElementType* const e = data.elements + startIndex;
  6075. numberToRemove = endIndex - startIndex;
  6076. for (int i = 0; i < numberToRemove; ++i)
  6077. e[i].~ElementType();
  6078. const int numToShift = numUsed - endIndex;
  6079. if (numToShift > 0)
  6080. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  6081. numUsed -= numberToRemove;
  6082. if ((numUsed << 1) < data.numAllocated)
  6083. minimiseStorageOverheads();
  6084. }
  6085. }
  6086. /** Removes the last n elements from the array.
  6087. @param howManyToRemove how many elements to remove from the end of the array
  6088. @see remove, removeValue, removeRange
  6089. */
  6090. void removeLast (int howManyToRemove = 1)
  6091. {
  6092. const ScopedLockType lock (getLock());
  6093. if (howManyToRemove > numUsed)
  6094. howManyToRemove = numUsed;
  6095. for (int i = 1; i <= howManyToRemove; ++i)
  6096. data.elements [numUsed - i].~ElementType();
  6097. numUsed -= howManyToRemove;
  6098. if ((numUsed << 1) < data.numAllocated)
  6099. minimiseStorageOverheads();
  6100. }
  6101. /** Removes any elements which are also in another array.
  6102. @param otherArray the other array in which to look for elements to remove
  6103. @see removeValuesNotIn, remove, removeValue, removeRange
  6104. */
  6105. template <class OtherArrayType>
  6106. void removeValuesIn (const OtherArrayType& otherArray)
  6107. {
  6108. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6109. const ScopedLockType lock2 (getLock());
  6110. if (this == &otherArray)
  6111. {
  6112. clear();
  6113. }
  6114. else
  6115. {
  6116. if (otherArray.size() > 0)
  6117. {
  6118. for (int i = numUsed; --i >= 0;)
  6119. if (otherArray.contains (data.elements [i]))
  6120. remove (i);
  6121. }
  6122. }
  6123. }
  6124. /** Removes any elements which are not found in another array.
  6125. Only elements which occur in this other array will be retained.
  6126. @param otherArray the array in which to look for elements NOT to remove
  6127. @see removeValuesIn, remove, removeValue, removeRange
  6128. */
  6129. template <class OtherArrayType>
  6130. void removeValuesNotIn (const OtherArrayType& otherArray)
  6131. {
  6132. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6133. const ScopedLockType lock2 (getLock());
  6134. if (this != &otherArray)
  6135. {
  6136. if (otherArray.size() <= 0)
  6137. {
  6138. clear();
  6139. }
  6140. else
  6141. {
  6142. for (int i = numUsed; --i >= 0;)
  6143. if (! otherArray.contains (data.elements [i]))
  6144. remove (i);
  6145. }
  6146. }
  6147. }
  6148. /** Swaps over two elements in the array.
  6149. This swaps over the elements found at the two indexes passed in.
  6150. If either index is out-of-range, this method will do nothing.
  6151. @param index1 index of one of the elements to swap
  6152. @param index2 index of the other element to swap
  6153. */
  6154. void swap (const int index1,
  6155. const int index2)
  6156. {
  6157. const ScopedLockType lock (getLock());
  6158. if (isPositiveAndBelow (index1, numUsed)
  6159. && isPositiveAndBelow (index2, numUsed))
  6160. {
  6161. swapVariables (data.elements [index1],
  6162. data.elements [index2]);
  6163. }
  6164. }
  6165. /** Moves one of the values to a different position.
  6166. This will move the value to a specified index, shuffling along
  6167. any intervening elements as required.
  6168. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6169. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6170. @param currentIndex the index of the value to be moved. If this isn't a
  6171. valid index, then nothing will be done
  6172. @param newIndex the index at which you'd like this value to end up. If this
  6173. is less than zero, the value will be moved to the end
  6174. of the array
  6175. */
  6176. void move (const int currentIndex, int newIndex) noexcept
  6177. {
  6178. if (currentIndex != newIndex)
  6179. {
  6180. const ScopedLockType lock (getLock());
  6181. if (isPositiveAndBelow (currentIndex, numUsed))
  6182. {
  6183. if (! isPositiveAndBelow (newIndex, numUsed))
  6184. newIndex = numUsed - 1;
  6185. char tempCopy [sizeof (ElementType)];
  6186. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  6187. if (newIndex > currentIndex)
  6188. {
  6189. memmove (data.elements + currentIndex,
  6190. data.elements + currentIndex + 1,
  6191. (newIndex - currentIndex) * sizeof (ElementType));
  6192. }
  6193. else
  6194. {
  6195. memmove (data.elements + newIndex + 1,
  6196. data.elements + newIndex,
  6197. (currentIndex - newIndex) * sizeof (ElementType));
  6198. }
  6199. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  6200. }
  6201. }
  6202. }
  6203. /** Reduces the amount of storage being used by the array.
  6204. Arrays typically allocate slightly more storage than they need, and after
  6205. removing elements, they may have quite a lot of unused space allocated.
  6206. This method will reduce the amount of allocated storage to a minimum.
  6207. */
  6208. void minimiseStorageOverheads()
  6209. {
  6210. const ScopedLockType lock (getLock());
  6211. data.shrinkToNoMoreThan (numUsed);
  6212. }
  6213. /** Increases the array's internal storage to hold a minimum number of elements.
  6214. Calling this before adding a large known number of elements means that
  6215. the array won't have to keep dynamically resizing itself as the elements
  6216. are added, and it'll therefore be more efficient.
  6217. */
  6218. void ensureStorageAllocated (const int minNumElements)
  6219. {
  6220. const ScopedLockType lock (getLock());
  6221. data.ensureAllocatedSize (minNumElements);
  6222. }
  6223. /** Sorts the elements in the array.
  6224. This will use a comparator object to sort the elements into order. The object
  6225. passed must have a method of the form:
  6226. @code
  6227. int compareElements (ElementType first, ElementType second);
  6228. @endcode
  6229. ..and this method must return:
  6230. - a value of < 0 if the first comes before the second
  6231. - a value of 0 if the two objects are equivalent
  6232. - a value of > 0 if the second comes before the first
  6233. To improve performance, the compareElements() method can be declared as static or const.
  6234. @param comparator the comparator to use for comparing elements.
  6235. @param retainOrderOfEquivalentItems if this is true, then items
  6236. which the comparator says are equivalent will be
  6237. kept in the order in which they currently appear
  6238. in the array. This is slower to perform, but may
  6239. be important in some cases. If it's false, a faster
  6240. algorithm is used, but equivalent elements may be
  6241. rearranged.
  6242. @see addSorted, indexOfSorted, sortArray
  6243. */
  6244. template <class ElementComparator>
  6245. void sort (ElementComparator& comparator,
  6246. const bool retainOrderOfEquivalentItems = false) const
  6247. {
  6248. const ScopedLockType lock (getLock());
  6249. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6250. // avoids getting warning messages about the parameter being unused
  6251. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6252. }
  6253. /** Returns the CriticalSection that locks this array.
  6254. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6255. an object of ScopedLockType as an RAII lock for it.
  6256. */
  6257. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  6258. /** Returns the type of scoped lock to use for locking this array */
  6259. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6260. private:
  6261. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6262. int numUsed;
  6263. };
  6264. #endif // __JUCE_ARRAY_JUCEHEADER__
  6265. /*** End of inlined file: juce_Array.h ***/
  6266. #endif
  6267. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6268. #endif
  6269. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6270. /*** Start of inlined file: juce_DynamicObject.h ***/
  6271. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6272. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6273. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6274. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6275. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6276. /*** Start of inlined file: juce_Variant.h ***/
  6277. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6278. #define __JUCE_VARIANT_JUCEHEADER__
  6279. /*** Start of inlined file: juce_Identifier.h ***/
  6280. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6281. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6282. class StringPool;
  6283. /**
  6284. Represents a string identifier, designed for accessing properties by name.
  6285. Identifier objects are very light and fast to copy, but slower to initialise
  6286. from a string, so it's much faster to keep a static identifier object to refer
  6287. to frequently-used names, rather than constructing them each time you need it.
  6288. @see NamedPropertySet, ValueTree
  6289. */
  6290. class JUCE_API Identifier
  6291. {
  6292. public:
  6293. /** Creates a null identifier. */
  6294. Identifier() noexcept;
  6295. /** Creates an identifier with a specified name.
  6296. Because this name may need to be used in contexts such as script variables or XML
  6297. tags, it must only contain ascii letters and digits, or the underscore character.
  6298. */
  6299. Identifier (const char* name);
  6300. /** Creates an identifier with a specified name.
  6301. Because this name may need to be used in contexts such as script variables or XML
  6302. tags, it must only contain ascii letters and digits, or the underscore character.
  6303. */
  6304. Identifier (const String& name);
  6305. /** Creates a copy of another identifier. */
  6306. Identifier (const Identifier& other) noexcept;
  6307. /** Creates a copy of another identifier. */
  6308. Identifier& operator= (const Identifier& other) noexcept;
  6309. /** Destructor */
  6310. ~Identifier();
  6311. /** Compares two identifiers. This is a very fast operation. */
  6312. inline bool operator== (const Identifier& other) const noexcept { return name == other.name; }
  6313. /** Compares two identifiers. This is a very fast operation. */
  6314. inline bool operator!= (const Identifier& other) const noexcept { return name != other.name; }
  6315. /** Returns this identifier as a string. */
  6316. String toString() const { return name; }
  6317. /** Returns this identifier's raw string pointer. */
  6318. operator const String::CharPointerType() const noexcept { return name; }
  6319. /** Checks a given string for characters that might not be valid in an Identifier.
  6320. Since Identifiers are used as a script variables and XML attributes, they should only contain
  6321. alphanumeric characters, underscores, or the '-' and ':' characters.
  6322. */
  6323. static bool isValidIdentifier (const String& possibleIdentifier) noexcept;
  6324. private:
  6325. String::CharPointerType name;
  6326. static StringPool& getPool();
  6327. };
  6328. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6329. /*** End of inlined file: juce_Identifier.h ***/
  6330. /*** Start of inlined file: juce_OutputStream.h ***/
  6331. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6332. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6333. /*** Start of inlined file: juce_NewLine.h ***/
  6334. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6335. #define __JUCE_NEWLINE_JUCEHEADER__
  6336. /** This class is used for represent a new-line character sequence.
  6337. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6338. @code
  6339. myOutputStream << "Hello World" << newLine << newLine;
  6340. @endcode
  6341. The exact character sequence that will be used for the new-line can be set and
  6342. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6343. */
  6344. class JUCE_API NewLine
  6345. {
  6346. public:
  6347. /** Returns the default new-line sequence that the library uses.
  6348. @see OutputStream::setNewLineString()
  6349. */
  6350. static const char* getDefault() noexcept { return "\r\n"; }
  6351. /** Returns the default new-line sequence that the library uses.
  6352. @see getDefault()
  6353. */
  6354. operator String() const { return getDefault(); }
  6355. };
  6356. /** A predefined object representing a new-line, which can be written to a string or stream.
  6357. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6358. @code
  6359. myOutputStream << "Hello World" << newLine << newLine;
  6360. @endcode
  6361. */
  6362. extern NewLine newLine;
  6363. /** Writes a new-line sequence to a string.
  6364. You can use the predefined object 'newLine' to invoke this, e.g.
  6365. @code
  6366. myString << "Hello World" << newLine << newLine;
  6367. @endcode
  6368. */
  6369. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6370. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6371. /*** End of inlined file: juce_NewLine.h ***/
  6372. class InputStream;
  6373. class MemoryBlock;
  6374. class File;
  6375. /**
  6376. The base class for streams that write data to some kind of destination.
  6377. Input and output streams are used throughout the library - subclasses can override
  6378. some or all of the virtual functions to implement their behaviour.
  6379. @see InputStream, MemoryOutputStream, FileOutputStream
  6380. */
  6381. class JUCE_API OutputStream
  6382. {
  6383. protected:
  6384. OutputStream();
  6385. public:
  6386. /** Destructor.
  6387. Some subclasses might want to do things like call flush() during their
  6388. destructors.
  6389. */
  6390. virtual ~OutputStream();
  6391. /** If the stream is using a buffer, this will ensure it gets written
  6392. out to the destination. */
  6393. virtual void flush() = 0;
  6394. /** Tries to move the stream's output position.
  6395. Not all streams will be able to seek to a new position - this will return
  6396. false if it fails to work.
  6397. @see getPosition
  6398. */
  6399. virtual bool setPosition (int64 newPosition) = 0;
  6400. /** Returns the stream's current position.
  6401. @see setPosition
  6402. */
  6403. virtual int64 getPosition() = 0;
  6404. /** Writes a block of data to the stream.
  6405. When creating a subclass of OutputStream, this is the only write method
  6406. that needs to be overloaded - the base class has methods for writing other
  6407. types of data which use this to do the work.
  6408. @returns false if the write operation fails for some reason
  6409. */
  6410. virtual bool write (const void* dataToWrite,
  6411. int howManyBytes) = 0;
  6412. /** Writes a single byte to the stream.
  6413. @see InputStream::readByte
  6414. */
  6415. virtual void writeByte (char byte);
  6416. /** Writes a boolean to the stream as a single byte.
  6417. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6418. @see InputStream::readBool
  6419. */
  6420. virtual void writeBool (bool boolValue);
  6421. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6422. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6423. @see InputStream::readShort
  6424. */
  6425. virtual void writeShort (short value);
  6426. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6427. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6428. @see InputStream::readShortBigEndian
  6429. */
  6430. virtual void writeShortBigEndian (short value);
  6431. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6432. @see InputStream::readInt
  6433. */
  6434. virtual void writeInt (int value);
  6435. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6436. @see InputStream::readIntBigEndian
  6437. */
  6438. virtual void writeIntBigEndian (int value);
  6439. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6440. @see InputStream::readInt64
  6441. */
  6442. virtual void writeInt64 (int64 value);
  6443. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6444. @see InputStream::readInt64BigEndian
  6445. */
  6446. virtual void writeInt64BigEndian (int64 value);
  6447. /** Writes a 32-bit floating point value to the stream in a binary format.
  6448. The binary 32-bit encoding of the float is written as a little-endian int.
  6449. @see InputStream::readFloat
  6450. */
  6451. virtual void writeFloat (float value);
  6452. /** Writes a 32-bit floating point value to the stream in a binary format.
  6453. The binary 32-bit encoding of the float is written as a big-endian int.
  6454. @see InputStream::readFloatBigEndian
  6455. */
  6456. virtual void writeFloatBigEndian (float value);
  6457. /** Writes a 64-bit floating point value to the stream in a binary format.
  6458. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6459. @see InputStream::readDouble
  6460. */
  6461. virtual void writeDouble (double value);
  6462. /** Writes a 64-bit floating point value to the stream in a binary format.
  6463. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6464. @see InputStream::readDoubleBigEndian
  6465. */
  6466. virtual void writeDoubleBigEndian (double value);
  6467. /** Writes a byte to the output stream a given number of times. */
  6468. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6469. /** Writes a condensed binary encoding of a 32-bit integer.
  6470. If you're storing a lot of integers which are unlikely to have very large values,
  6471. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6472. under 0xffff only 3 bytes, etc.
  6473. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6474. @see InputStream::readCompressedInt
  6475. */
  6476. virtual void writeCompressedInt (int value);
  6477. /** Stores a string in the stream in a binary format.
  6478. This isn't the method to use if you're trying to append text to the end of a
  6479. text-file! It's intended for storing a string so that it can be retrieved later
  6480. by InputStream::readString().
  6481. It writes the string to the stream as UTF8, including the null termination character.
  6482. For appending text to a file, instead use writeText, or operator<<
  6483. @see InputStream::readString, writeText, operator<<
  6484. */
  6485. virtual void writeString (const String& text);
  6486. /** Writes a string of text to the stream.
  6487. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6488. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6489. of a file).
  6490. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6491. */
  6492. virtual void writeText (const String& text,
  6493. bool asUTF16,
  6494. bool writeUTF16ByteOrderMark);
  6495. /** Reads data from an input stream and writes it to this stream.
  6496. @param source the stream to read from
  6497. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6498. less than zero, it will keep reading until the input
  6499. is exhausted)
  6500. */
  6501. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6502. /** Sets the string that will be written to the stream when the writeNewLine()
  6503. method is called.
  6504. By default this will be set the the value of NewLine::getDefault().
  6505. */
  6506. void setNewLineString (const String& newLineString);
  6507. /** Returns the current new-line string that was set by setNewLineString(). */
  6508. const String& getNewLineString() const noexcept { return newLineString; }
  6509. private:
  6510. String newLineString;
  6511. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6512. };
  6513. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6514. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6515. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6516. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6517. /** Writes a character to a stream. */
  6518. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6519. /** Writes a null-terminated text string to a stream. */
  6520. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6521. /** Writes a block of data from a MemoryBlock to a stream. */
  6522. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6523. /** Writes the contents of a file to a stream. */
  6524. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6525. /** Writes a new-line to a stream.
  6526. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6527. @code
  6528. myOutputStream << "Hello World" << newLine << newLine;
  6529. @endcode
  6530. @see OutputStream::setNewLineString
  6531. */
  6532. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6533. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6534. /*** End of inlined file: juce_OutputStream.h ***/
  6535. /*** Start of inlined file: juce_InputStream.h ***/
  6536. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6537. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6538. class MemoryBlock;
  6539. /** The base class for streams that read data.
  6540. Input and output streams are used throughout the library - subclasses can override
  6541. some or all of the virtual functions to implement their behaviour.
  6542. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6543. */
  6544. class JUCE_API InputStream
  6545. {
  6546. public:
  6547. /** Destructor. */
  6548. virtual ~InputStream() {}
  6549. /** Returns the total number of bytes available for reading in this stream.
  6550. Note that this is the number of bytes available from the start of the
  6551. stream, not from the current position.
  6552. If the size of the stream isn't actually known, this may return -1.
  6553. */
  6554. virtual int64 getTotalLength() = 0;
  6555. /** Returns true if the stream has no more data to read. */
  6556. virtual bool isExhausted() = 0;
  6557. /** Reads a set of bytes from the stream into a memory buffer.
  6558. This is the only read method that subclasses actually need to implement, as the
  6559. InputStream base class implements the other read methods in terms of this one (although
  6560. it's often more efficient for subclasses to implement them directly).
  6561. @param destBuffer the destination buffer for the data
  6562. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6563. memory block passed in is big enough to contain this
  6564. many bytes.
  6565. @returns the actual number of bytes that were read, which may be less than
  6566. maxBytesToRead if the stream is exhausted before it gets that far
  6567. */
  6568. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6569. /** Reads a byte from the stream.
  6570. If the stream is exhausted, this will return zero.
  6571. @see OutputStream::writeByte
  6572. */
  6573. virtual char readByte();
  6574. /** Reads a boolean from the stream.
  6575. The bool is encoded as a single byte - 1 for true, 0 for false.
  6576. If the stream is exhausted, this will return false.
  6577. @see OutputStream::writeBool
  6578. */
  6579. virtual bool readBool();
  6580. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6581. If the next two bytes read are byte1 and byte2, this returns
  6582. (byte1 | (byte2 << 8)).
  6583. If the stream is exhausted partway through reading the bytes, this will return zero.
  6584. @see OutputStream::writeShort, readShortBigEndian
  6585. */
  6586. virtual short readShort();
  6587. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6588. If the next two bytes read are byte1 and byte2, this returns
  6589. (byte2 | (byte1 << 8)).
  6590. If the stream is exhausted partway through reading the bytes, this will return zero.
  6591. @see OutputStream::writeShortBigEndian, readShort
  6592. */
  6593. virtual short readShortBigEndian();
  6594. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6595. If the next four bytes are byte1 to byte4, this returns
  6596. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6597. If the stream is exhausted partway through reading the bytes, this will return zero.
  6598. @see OutputStream::writeInt, readIntBigEndian
  6599. */
  6600. virtual int readInt();
  6601. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6602. If the next four bytes are byte1 to byte4, this returns
  6603. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6604. If the stream is exhausted partway through reading the bytes, this will return zero.
  6605. @see OutputStream::writeIntBigEndian, readInt
  6606. */
  6607. virtual int readIntBigEndian();
  6608. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6609. If the next eight bytes are byte1 to byte8, this returns
  6610. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6611. If the stream is exhausted partway through reading the bytes, this will return zero.
  6612. @see OutputStream::writeInt64, readInt64BigEndian
  6613. */
  6614. virtual int64 readInt64();
  6615. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6616. If the next eight bytes are byte1 to byte8, this returns
  6617. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6618. If the stream is exhausted partway through reading the bytes, this will return zero.
  6619. @see OutputStream::writeInt64BigEndian, readInt64
  6620. */
  6621. virtual int64 readInt64BigEndian();
  6622. /** Reads four bytes as a 32-bit floating point value.
  6623. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6624. If the stream is exhausted partway through reading the bytes, this will return zero.
  6625. @see OutputStream::writeFloat, readDouble
  6626. */
  6627. virtual float readFloat();
  6628. /** Reads four bytes as a 32-bit floating point value.
  6629. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6630. If the stream is exhausted partway through reading the bytes, this will return zero.
  6631. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6632. */
  6633. virtual float readFloatBigEndian();
  6634. /** Reads eight bytes as a 64-bit floating point value.
  6635. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6636. If the stream is exhausted partway through reading the bytes, this will return zero.
  6637. @see OutputStream::writeDouble, readFloat
  6638. */
  6639. virtual double readDouble();
  6640. /** Reads eight bytes as a 64-bit floating point value.
  6641. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6642. If the stream is exhausted partway through reading the bytes, this will return zero.
  6643. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6644. */
  6645. virtual double readDoubleBigEndian();
  6646. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6647. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6648. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6649. @see OutputStream::writeCompressedInt()
  6650. */
  6651. virtual int readCompressedInt();
  6652. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6653. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6654. After this call, the stream's position will be left pointing to the next character
  6655. following the line-feed, but the linefeeds aren't included in the string that
  6656. is returned.
  6657. */
  6658. virtual String readNextLine();
  6659. /** Reads a zero-terminated UTF8 string from the stream.
  6660. This will read characters from the stream until it hits a zero character or
  6661. end-of-stream.
  6662. @see OutputStream::writeString, readEntireStreamAsString
  6663. */
  6664. virtual String readString();
  6665. /** Tries to read the whole stream and turn it into a string.
  6666. This will read from the stream's current position until the end-of-stream, and
  6667. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6668. */
  6669. virtual String readEntireStreamAsString();
  6670. /** Reads from the stream and appends the data to a MemoryBlock.
  6671. @param destBlock the block to append the data onto
  6672. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6673. of bytes that will be read - if it's negative, data
  6674. will be read until the stream is exhausted.
  6675. @returns the number of bytes that were added to the memory block
  6676. */
  6677. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6678. int maxNumBytesToRead = -1);
  6679. /** Returns the offset of the next byte that will be read from the stream.
  6680. @see setPosition
  6681. */
  6682. virtual int64 getPosition() = 0;
  6683. /** Tries to move the current read position of the stream.
  6684. The position is an absolute number of bytes from the stream's start.
  6685. Some streams might not be able to do this, in which case they should do
  6686. nothing and return false. Others might be able to manage it by resetting
  6687. themselves and skipping to the correct position, although this is
  6688. obviously a bit slow.
  6689. @returns true if the stream manages to reposition itself correctly
  6690. @see getPosition
  6691. */
  6692. virtual bool setPosition (int64 newPosition) = 0;
  6693. /** Reads and discards a number of bytes from the stream.
  6694. Some input streams might implement this efficiently, but the base
  6695. class will just keep reading data until the requisite number of bytes
  6696. have been done.
  6697. */
  6698. virtual void skipNextBytes (int64 numBytesToSkip);
  6699. protected:
  6700. InputStream() noexcept {}
  6701. private:
  6702. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6703. };
  6704. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6705. /*** End of inlined file: juce_InputStream.h ***/
  6706. #ifndef DOXYGEN
  6707. class ReferenceCountedObject;
  6708. class DynamicObject;
  6709. #endif
  6710. /**
  6711. A variant class, that can be used to hold a range of primitive values.
  6712. A var object can hold a range of simple primitive values, strings, or
  6713. any kind of ReferenceCountedObject. The var class is intended to act like
  6714. the kind of values used in dynamic scripting languages.
  6715. @see DynamicObject
  6716. */
  6717. class JUCE_API var
  6718. {
  6719. public:
  6720. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6721. typedef Identifier identifier;
  6722. /** Creates a void variant. */
  6723. var() noexcept;
  6724. /** Destructor. */
  6725. ~var() noexcept;
  6726. /** A static var object that can be used where you need an empty variant object. */
  6727. static const var null;
  6728. var (const var& valueToCopy);
  6729. var (int value) noexcept;
  6730. var (int64 value) noexcept;
  6731. var (bool value) noexcept;
  6732. var (double value) noexcept;
  6733. var (const char* value);
  6734. var (const wchar_t* value);
  6735. var (const String& value);
  6736. var (const Array<var>& value);
  6737. var (ReferenceCountedObject* object);
  6738. var (MethodFunction method) noexcept;
  6739. const var& operator= (const var& valueToCopy);
  6740. const var& operator= (int value);
  6741. const var& operator= (int64 value);
  6742. const var& operator= (bool value);
  6743. const var& operator= (double value);
  6744. const var& operator= (const char* value);
  6745. const var& operator= (const wchar_t* value);
  6746. const var& operator= (const String& value);
  6747. const var& operator= (const Array<var>& value);
  6748. const var& operator= (ReferenceCountedObject* object);
  6749. const var& operator= (MethodFunction method);
  6750. void swapWith (var& other) noexcept;
  6751. operator int() const noexcept;
  6752. operator int64() const noexcept;
  6753. operator bool() const noexcept;
  6754. operator float() const noexcept;
  6755. operator double() const noexcept;
  6756. operator String() const;
  6757. String toString() const;
  6758. Array<var>* getArray() const noexcept;
  6759. ReferenceCountedObject* getObject() const noexcept;
  6760. DynamicObject* getDynamicObject() const noexcept;
  6761. bool isVoid() const noexcept;
  6762. bool isInt() const noexcept;
  6763. bool isInt64() const noexcept;
  6764. bool isBool() const noexcept;
  6765. bool isDouble() const noexcept;
  6766. bool isString() const noexcept;
  6767. bool isObject() const noexcept;
  6768. bool isArray() const noexcept;
  6769. bool isMethod() const noexcept;
  6770. /** Returns true if this var has the same value as the one supplied.
  6771. Note that this ignores the type, so a string var "123" and an integer var with the
  6772. value 123 are considered to be equal.
  6773. @see equalsWithSameType
  6774. */
  6775. bool equals (const var& other) const noexcept;
  6776. /** Returns true if this var has the same value and type as the one supplied.
  6777. This differs from equals() because e.g. "123" and 123 will be considered different.
  6778. @see equals
  6779. */
  6780. bool equalsWithSameType (const var& other) const noexcept;
  6781. /** If the var is an array, this returns the number of elements.
  6782. If the var isn't actually an array, this will return 0.
  6783. */
  6784. int size() const;
  6785. /** If the var is an array, this can be used to return one of its elements.
  6786. To call this method, you must make sure that the var is actually an array, and
  6787. that the index is a valid number. If these conditions aren't met, behaviour is
  6788. undefined.
  6789. For more control over the array's contents, you can call getArray() and manipulate
  6790. it directly as an Array<var>.
  6791. */
  6792. const var& operator[] (int arrayIndex) const;
  6793. /** If the var is an array, this can be used to return one of its elements.
  6794. To call this method, you must make sure that the var is actually an array, and
  6795. that the index is a valid number. If these conditions aren't met, behaviour is
  6796. undefined.
  6797. For more control over the array's contents, you can call getArray() and manipulate
  6798. it directly as an Array<var>.
  6799. */
  6800. var& operator[] (int arrayIndex);
  6801. /** Appends an element to the var, converting it to an array if it isn't already one.
  6802. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6803. this value will be kept as the first element of the new array. The parameter value
  6804. will then be appended to it.
  6805. For more control over the array's contents, you can call getArray() and manipulate
  6806. it directly as an Array<var>.
  6807. */
  6808. void append (const var& valueToAppend);
  6809. /** Inserts an element to the var, converting it to an array if it isn't already one.
  6810. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6811. this value will be kept as the first element of the new array. The parameter value
  6812. will then be inserted into it.
  6813. For more control over the array's contents, you can call getArray() and manipulate
  6814. it directly as an Array<var>.
  6815. */
  6816. void insert (int index, const var& value);
  6817. /** If the var is an array, this removes one of its elements.
  6818. If the index is out-of-range or the var isn't an array, nothing will be done.
  6819. For more control over the array's contents, you can call getArray() and manipulate
  6820. it directly as an Array<var>.
  6821. */
  6822. void remove (int index);
  6823. /** Treating the var as an array, this resizes it to contain the specified number of elements.
  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 before resizing.
  6826. For more control over the array's contents, you can call getArray() and manipulate
  6827. it directly as an Array<var>.
  6828. */
  6829. void resize (int numArrayElementsWanted);
  6830. /** If the var is an array, this searches it for the first occurrence of the specified value,
  6831. and returns its index.
  6832. If the var isn't an array, or if the value isn't found, this returns -1.
  6833. */
  6834. int indexOf (const var& value) const;
  6835. /** If this variant is an object, this returns one of its properties. */
  6836. var operator[] (const Identifier& propertyName) const;
  6837. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6838. var call (const Identifier& method) const;
  6839. /** If this variant is an object, this invokes one of its methods with one argument. */
  6840. var call (const Identifier& method, const var& arg1) const;
  6841. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6842. var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6843. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6844. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6845. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6846. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6847. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6848. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6849. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6850. var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6851. /** Writes a binary representation of this value to a stream.
  6852. The data can be read back later using readFromStream().
  6853. */
  6854. void writeToStream (OutputStream& output) const;
  6855. /** Reads back a stored binary representation of a value.
  6856. The data in the stream must have been written using writeToStream(), or this
  6857. will have unpredictable results.
  6858. */
  6859. static var readFromStream (InputStream& input);
  6860. private:
  6861. class VariantType; friend class VariantType;
  6862. class VariantType_Void; friend class VariantType_Void;
  6863. class VariantType_Int; friend class VariantType_Int;
  6864. class VariantType_Int64; friend class VariantType_Int64;
  6865. class VariantType_Double; friend class VariantType_Double;
  6866. class VariantType_Bool; friend class VariantType_Bool;
  6867. class VariantType_String; friend class VariantType_String;
  6868. class VariantType_Object; friend class VariantType_Object;
  6869. class VariantType_Array; friend class VariantType_Array;
  6870. class VariantType_Method; friend class VariantType_Method;
  6871. union ValueUnion
  6872. {
  6873. int intValue;
  6874. int64 int64Value;
  6875. bool boolValue;
  6876. double doubleValue;
  6877. char stringValue [sizeof (String)];
  6878. ReferenceCountedObject* objectValue;
  6879. Array<var>* arrayValue;
  6880. MethodFunction methodValue;
  6881. };
  6882. const VariantType* type;
  6883. ValueUnion value;
  6884. Array<var>* convertToArray();
  6885. friend class DynamicObject;
  6886. var invokeMethod (DynamicObject*, const var*, int) const;
  6887. };
  6888. /** Compares the values of two var objects, using the var::equals() comparison. */
  6889. bool operator== (const var& v1, const var& v2) noexcept;
  6890. /** Compares the values of two var objects, using the var::equals() comparison. */
  6891. bool operator!= (const var& v1, const var& v2) noexcept;
  6892. bool operator== (const var& v1, const String& v2);
  6893. bool operator!= (const var& v1, const String& v2);
  6894. bool operator== (const var& v1, const char* v2);
  6895. bool operator!= (const var& v1, const char* v2);
  6896. #endif // __JUCE_VARIANT_JUCEHEADER__
  6897. /*** End of inlined file: juce_Variant.h ***/
  6898. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  6899. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6900. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6901. /**
  6902. Helps to manipulate singly-linked lists of objects.
  6903. For objects that are designed to contain a pointer to the subsequent item in the
  6904. list, this class contains methods to deal with the list. To use it, the ObjectType
  6905. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  6906. @code
  6907. struct MyObject
  6908. {
  6909. int x, y, z;
  6910. // A linkable object must contain a member with this name and type, which must be
  6911. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  6912. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  6913. LinkedListPointer<MyObject> nextListItem;
  6914. };
  6915. LinkedListPointer<MyObject> myList;
  6916. myList.append (new MyObject());
  6917. myList.append (new MyObject());
  6918. int numItems = myList.size(); // returns 2
  6919. MyObject* lastInList = myList.getLast();
  6920. @endcode
  6921. */
  6922. template <class ObjectType>
  6923. class LinkedListPointer
  6924. {
  6925. public:
  6926. /** Creates a null pointer to an empty list. */
  6927. LinkedListPointer() noexcept
  6928. : item (nullptr)
  6929. {
  6930. }
  6931. /** Creates a pointer to a list whose head is the item provided. */
  6932. explicit LinkedListPointer (ObjectType* const headItem) noexcept
  6933. : item (headItem)
  6934. {
  6935. }
  6936. /** Sets this pointer to point to a new list. */
  6937. LinkedListPointer& operator= (ObjectType* const newItem) noexcept
  6938. {
  6939. item = newItem;
  6940. return *this;
  6941. }
  6942. /** Returns the item which this pointer points to. */
  6943. inline operator ObjectType*() const noexcept
  6944. {
  6945. return item;
  6946. }
  6947. /** Returns the item which this pointer points to. */
  6948. inline ObjectType* get() const noexcept
  6949. {
  6950. return item;
  6951. }
  6952. /** Returns the last item in the list which this pointer points to.
  6953. This will iterate the list and return the last item found. Obviously the speed
  6954. of this operation will be proportional to the size of the list. If the list is
  6955. empty the return value will be this object.
  6956. If you're planning on appending a number of items to your list, it's much more
  6957. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  6958. */
  6959. LinkedListPointer& getLast() noexcept
  6960. {
  6961. LinkedListPointer* l = this;
  6962. while (l->item != nullptr)
  6963. l = &(l->item->nextListItem);
  6964. return *l;
  6965. }
  6966. /** Returns the number of items in the list.
  6967. Obviously with a simple linked list, getting the size involves iterating the list, so
  6968. this can be a lengthy operation - be careful when using this method in your code.
  6969. */
  6970. int size() const noexcept
  6971. {
  6972. int total = 0;
  6973. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  6974. ++total;
  6975. return total;
  6976. }
  6977. /** Returns the item at a given index in the list.
  6978. Since the only way to find an item is to iterate the list, this operation can obviously
  6979. be slow, depending on its size, so you should be careful when using this in algorithms.
  6980. */
  6981. LinkedListPointer& operator[] (int index) noexcept
  6982. {
  6983. LinkedListPointer* l = this;
  6984. while (--index >= 0 && l->item != nullptr)
  6985. l = &(l->item->nextListItem);
  6986. return *l;
  6987. }
  6988. /** Returns the item at a given index in the list.
  6989. Since the only way to find an item is to iterate the list, this operation can obviously
  6990. be slow, depending on its size, so you should be careful when using this in algorithms.
  6991. */
  6992. const LinkedListPointer& operator[] (int index) const noexcept
  6993. {
  6994. const LinkedListPointer* l = this;
  6995. while (--index >= 0 && l->item != nullptr)
  6996. l = &(l->item->nextListItem);
  6997. return *l;
  6998. }
  6999. /** Returns true if the list contains the given item. */
  7000. bool contains (const ObjectType* const itemToLookFor) const noexcept
  7001. {
  7002. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7003. if (itemToLookFor == i)
  7004. return true;
  7005. return false;
  7006. }
  7007. /** Inserts an item into the list, placing it before the item that this pointer
  7008. currently points to.
  7009. */
  7010. void insertNext (ObjectType* const newItem)
  7011. {
  7012. jassert (newItem != nullptr);
  7013. jassert (newItem->nextListItem == nullptr);
  7014. newItem->nextListItem = item;
  7015. item = newItem;
  7016. }
  7017. /** Inserts an item at a numeric index in the list.
  7018. Obviously this will involve iterating the list to find the item at the given index,
  7019. so be careful about the impact this may have on execution time.
  7020. */
  7021. void insertAtIndex (int index, ObjectType* newItem)
  7022. {
  7023. jassert (newItem != nullptr);
  7024. LinkedListPointer* l = this;
  7025. while (index != 0 && l->item != nullptr)
  7026. {
  7027. l = &(l->item->nextListItem);
  7028. --index;
  7029. }
  7030. l->insertNext (newItem);
  7031. }
  7032. /** Replaces the object that this pointer points to, appending the rest of the list to
  7033. the new object, and returning the old one.
  7034. */
  7035. ObjectType* replaceNext (ObjectType* const newItem) noexcept
  7036. {
  7037. jassert (newItem != nullptr);
  7038. jassert (newItem->nextListItem == nullptr);
  7039. ObjectType* const oldItem = item;
  7040. item = newItem;
  7041. item->nextListItem = oldItem->nextListItem.item;
  7042. oldItem->nextListItem = (ObjectType*) 0;
  7043. return oldItem;
  7044. }
  7045. /** Adds an item to the end of the list.
  7046. This operation involves iterating the whole list, so can be slow - if you need to
  7047. append a number of items to your list, it's much more efficient to use the Appender
  7048. class than to repeatedly call append().
  7049. */
  7050. void append (ObjectType* const newItem)
  7051. {
  7052. getLast().item = newItem;
  7053. }
  7054. /** Creates copies of all the items in another list and adds them to this one.
  7055. This will use the ObjectType's copy constructor to try to create copies of each
  7056. item in the other list, and appends them to this list.
  7057. */
  7058. void addCopyOfList (const LinkedListPointer& other)
  7059. {
  7060. LinkedListPointer* insertPoint = this;
  7061. for (ObjectType* i = other.item; i != nullptr; i = i->nextListItem)
  7062. {
  7063. insertPoint->insertNext (new ObjectType (*i));
  7064. insertPoint = &(insertPoint->item->nextListItem);
  7065. }
  7066. }
  7067. /** Removes the head item from the list.
  7068. This won't delete the object that is removed, but returns it, so the caller can
  7069. delete it if necessary.
  7070. */
  7071. ObjectType* removeNext() noexcept
  7072. {
  7073. ObjectType* const oldItem = item;
  7074. if (oldItem != nullptr)
  7075. {
  7076. item = oldItem->nextListItem;
  7077. oldItem->nextListItem = (ObjectType*) 0;
  7078. }
  7079. return oldItem;
  7080. }
  7081. /** Removes a specific item from the list.
  7082. Note that this will not delete the item, it simply unlinks it from the list.
  7083. */
  7084. void remove (ObjectType* const itemToRemove)
  7085. {
  7086. LinkedListPointer* const l = findPointerTo (itemToRemove);
  7087. if (l != nullptr)
  7088. l->removeNext();
  7089. }
  7090. /** Iterates the list, calling the delete operator on all of its elements and
  7091. leaving this pointer empty.
  7092. */
  7093. void deleteAll()
  7094. {
  7095. while (item != nullptr)
  7096. {
  7097. ObjectType* const oldItem = item;
  7098. item = oldItem->nextListItem;
  7099. delete oldItem;
  7100. }
  7101. }
  7102. /** Finds a pointer to a given item.
  7103. If the item is found in the list, this returns the pointer that points to it. If
  7104. the item isn't found, this returns null.
  7105. */
  7106. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
  7107. {
  7108. LinkedListPointer* l = this;
  7109. while (l->item != nullptr)
  7110. {
  7111. if (l->item == itemToLookFor)
  7112. return l;
  7113. l = &(l->item->nextListItem);
  7114. }
  7115. return nullptr;
  7116. }
  7117. /** Copies the items in the list to an array.
  7118. The destArray must contain enough elements to hold the entire list - no checks are
  7119. made for this!
  7120. */
  7121. void copyToArray (ObjectType** destArray) const noexcept
  7122. {
  7123. jassert (destArray != nullptr);
  7124. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7125. *destArray++ = i;
  7126. }
  7127. /**
  7128. Allows efficient repeated insertions into a list.
  7129. You can create an Appender object which points to the last element in your
  7130. list, and then repeatedly call Appender::append() to add items to the end
  7131. of the list in O(1) time.
  7132. */
  7133. class Appender
  7134. {
  7135. public:
  7136. /** Creates an appender which will add items to the given list.
  7137. */
  7138. Appender (LinkedListPointer& endOfListPointer) noexcept
  7139. : endOfList (&endOfListPointer)
  7140. {
  7141. // This can only be used to add to the end of a list.
  7142. jassert (endOfListPointer.item == nullptr);
  7143. }
  7144. /** Appends an item to the list. */
  7145. void append (ObjectType* const newItem) noexcept
  7146. {
  7147. *endOfList = newItem;
  7148. endOfList = &(newItem->nextListItem);
  7149. }
  7150. private:
  7151. LinkedListPointer* endOfList;
  7152. JUCE_DECLARE_NON_COPYABLE (Appender);
  7153. };
  7154. private:
  7155. ObjectType* item;
  7156. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7157. };
  7158. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7159. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7160. class XmlElement;
  7161. #ifndef DOXYGEN
  7162. class JSONFormatter;
  7163. #endif
  7164. /** Holds a set of named var objects.
  7165. This can be used as a basic structure to hold a set of var object, which can
  7166. be retrieved by using their identifier.
  7167. */
  7168. class JUCE_API NamedValueSet
  7169. {
  7170. public:
  7171. /** Creates an empty set. */
  7172. NamedValueSet() noexcept;
  7173. /** Creates a copy of another set. */
  7174. NamedValueSet (const NamedValueSet& other);
  7175. /** Replaces this set with a copy of another set. */
  7176. NamedValueSet& operator= (const NamedValueSet& other);
  7177. /** Destructor. */
  7178. ~NamedValueSet();
  7179. bool operator== (const NamedValueSet& other) const;
  7180. bool operator!= (const NamedValueSet& other) const;
  7181. /** Returns the total number of values that the set contains. */
  7182. int size() const noexcept;
  7183. /** Returns the value of a named item.
  7184. If the name isn't found, this will return a void variant.
  7185. @see getProperty
  7186. */
  7187. const var& operator[] (const Identifier& name) const;
  7188. /** Tries to return the named value, but if no such value is found, this will
  7189. instead return the supplied default value.
  7190. */
  7191. var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7192. /** Changes or adds a named value.
  7193. @returns true if a value was changed or added; false if the
  7194. value was already set the the value passed-in.
  7195. */
  7196. bool set (const Identifier& name, const var& newValue);
  7197. /** Returns true if the set contains an item with the specified name. */
  7198. bool contains (const Identifier& name) const;
  7199. /** Removes a value from the set.
  7200. @returns true if a value was removed; false if there was no value
  7201. with the name that was given.
  7202. */
  7203. bool remove (const Identifier& name);
  7204. /** Returns the name of the value at a given index.
  7205. The index must be between 0 and size() - 1.
  7206. */
  7207. const Identifier getName (int index) const;
  7208. /** Returns the value of the item at a given index.
  7209. The index must be between 0 and size() - 1.
  7210. */
  7211. const var& getValueAt (int index) const;
  7212. /** Removes all values. */
  7213. void clear();
  7214. /** Returns a pointer to the var that holds a named value, or null if there is
  7215. no value with this name.
  7216. Do not use this method unless you really need access to the internal var object
  7217. for some reason - for normal reading and writing always prefer operator[]() and set().
  7218. */
  7219. var* getVarPointer (const Identifier& name) const noexcept;
  7220. /** Sets properties to the values of all of an XML element's attributes. */
  7221. void setFromXmlAttributes (const XmlElement& xml);
  7222. /** Sets attributes in an XML element corresponding to each of this object's
  7223. properties.
  7224. */
  7225. void copyToXmlAttributes (XmlElement& xml) const;
  7226. private:
  7227. class NamedValue
  7228. {
  7229. public:
  7230. NamedValue() noexcept;
  7231. NamedValue (const NamedValue&);
  7232. NamedValue (const Identifier& name, const var& value);
  7233. NamedValue& operator= (const NamedValue&);
  7234. bool operator== (const NamedValue& other) const noexcept;
  7235. LinkedListPointer<NamedValue> nextListItem;
  7236. Identifier name;
  7237. var value;
  7238. private:
  7239. JUCE_LEAK_DETECTOR (NamedValue);
  7240. };
  7241. friend class LinkedListPointer<NamedValue>;
  7242. LinkedListPointer<NamedValue> values;
  7243. friend class JSONFormatter;
  7244. };
  7245. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7246. /*** End of inlined file: juce_NamedValueSet.h ***/
  7247. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7248. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7249. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7250. /**
  7251. Adds reference-counting to an object.
  7252. To add reference-counting to a class, derive it from this class, and
  7253. use the ReferenceCountedObjectPtr class to point to it.
  7254. e.g. @code
  7255. class MyClass : public ReferenceCountedObject
  7256. {
  7257. void foo();
  7258. // This is a neat way of declaring a typedef for a pointer class,
  7259. // rather than typing out the full templated name each time..
  7260. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7261. };
  7262. MyClass::Ptr p = new MyClass();
  7263. MyClass::Ptr p2 = p;
  7264. p = nullptr;
  7265. p2->foo();
  7266. @endcode
  7267. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7268. careful not to delete the object manually.
  7269. This class uses an Atomic<int> value to hold the reference count, so that it
  7270. the pointers can be passed between threads safely. For a faster but non-thread-safe
  7271. version, use SingleThreadedReferenceCountedObject instead.
  7272. @see ReferenceCountedObjectPtr, ReferenceCountedArray, SingleThreadedReferenceCountedObject
  7273. */
  7274. class JUCE_API ReferenceCountedObject
  7275. {
  7276. public:
  7277. /** Increments the object's reference count.
  7278. This is done automatically by the smart pointer, but is public just
  7279. in case it's needed for nefarious purposes.
  7280. */
  7281. inline void incReferenceCount() noexcept
  7282. {
  7283. ++refCount;
  7284. }
  7285. /** Decreases the object's reference count.
  7286. If the count gets to zero, the object will be deleted.
  7287. */
  7288. inline void decReferenceCount() noexcept
  7289. {
  7290. jassert (getReferenceCount() > 0);
  7291. if (--refCount == 0)
  7292. delete this;
  7293. }
  7294. /** Returns the object's current reference count. */
  7295. inline int getReferenceCount() const noexcept { return refCount.get(); }
  7296. protected:
  7297. /** Creates the reference-counted object (with an initial ref count of zero). */
  7298. ReferenceCountedObject()
  7299. {
  7300. }
  7301. /** Destructor. */
  7302. virtual ~ReferenceCountedObject()
  7303. {
  7304. // it's dangerous to delete an object that's still referenced by something else!
  7305. jassert (getReferenceCount() == 0);
  7306. }
  7307. private:
  7308. Atomic <int> refCount;
  7309. };
  7310. /**
  7311. Adds reference-counting to an object.
  7312. This is efectively a version of the ReferenceCountedObject class, but which
  7313. uses a non-atomic counter, and so is not thread-safe (but which will be more
  7314. efficient).
  7315. For more details on how to use it, see the ReferenceCountedObject class notes.
  7316. @see ReferenceCountedObject, ReferenceCountedObjectPtr, ReferenceCountedArray
  7317. */
  7318. class JUCE_API SingleThreadedReferenceCountedObject
  7319. {
  7320. public:
  7321. /** Increments the object's reference count.
  7322. This is done automatically by the smart pointer, but is public just
  7323. in case it's needed for nefarious purposes.
  7324. */
  7325. inline void incReferenceCount() noexcept
  7326. {
  7327. ++refCount;
  7328. }
  7329. /** Decreases the object's reference count.
  7330. If the count gets to zero, the object will be deleted.
  7331. */
  7332. inline void decReferenceCount() noexcept
  7333. {
  7334. jassert (getReferenceCount() > 0);
  7335. if (--refCount == 0)
  7336. delete this;
  7337. }
  7338. /** Returns the object's current reference count. */
  7339. inline int getReferenceCount() const noexcept { return refCount; }
  7340. protected:
  7341. /** Creates the reference-counted object (with an initial ref count of zero). */
  7342. SingleThreadedReferenceCountedObject() : refCount (0) {}
  7343. /** Destructor. */
  7344. virtual ~SingleThreadedReferenceCountedObject()
  7345. {
  7346. // it's dangerous to delete an object that's still referenced by something else!
  7347. jassert (getReferenceCount() == 0);
  7348. }
  7349. private:
  7350. int refCount;
  7351. };
  7352. /**
  7353. A smart-pointer class which points to a reference-counted object.
  7354. The template parameter specifies the class of the object you want to point to - the easiest
  7355. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7356. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7357. mathods called incReferenceCount() and decReferenceCount().
  7358. When using this class, you'll probably want to create a typedef to abbreviate the full
  7359. templated name - e.g.
  7360. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7361. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7362. */
  7363. template <class ReferenceCountedObjectClass>
  7364. class ReferenceCountedObjectPtr
  7365. {
  7366. public:
  7367. /** The class being referenced by this pointer. */
  7368. typedef ReferenceCountedObjectClass ReferencedType;
  7369. /** Creates a pointer to a null object. */
  7370. inline ReferenceCountedObjectPtr() noexcept
  7371. : referencedObject (nullptr)
  7372. {
  7373. }
  7374. /** Creates a pointer to an object.
  7375. This will increment the object's reference-count if it is non-null.
  7376. */
  7377. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) noexcept
  7378. : referencedObject (refCountedObject)
  7379. {
  7380. if (refCountedObject != nullptr)
  7381. refCountedObject->incReferenceCount();
  7382. }
  7383. /** Copies another pointer.
  7384. This will increment the object's reference-count (if it is non-null).
  7385. */
  7386. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) noexcept
  7387. : referencedObject (other.referencedObject)
  7388. {
  7389. if (referencedObject != nullptr)
  7390. referencedObject->incReferenceCount();
  7391. }
  7392. /** Changes this pointer to point at a different object.
  7393. The reference count of the old object is decremented, and it might be
  7394. deleted if it hits zero. The new object's count is incremented.
  7395. */
  7396. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7397. {
  7398. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7399. if (newObject != referencedObject)
  7400. {
  7401. if (newObject != nullptr)
  7402. newObject->incReferenceCount();
  7403. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7404. referencedObject = newObject;
  7405. if (oldObject != nullptr)
  7406. oldObject->decReferenceCount();
  7407. }
  7408. return *this;
  7409. }
  7410. /** Changes this pointer to point at a different object.
  7411. The reference count of the old object is decremented, and it might be
  7412. deleted if it hits zero. The new object's count is incremented.
  7413. */
  7414. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7415. {
  7416. if (referencedObject != newObject)
  7417. {
  7418. if (newObject != nullptr)
  7419. newObject->incReferenceCount();
  7420. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7421. referencedObject = newObject;
  7422. if (oldObject != nullptr)
  7423. oldObject->decReferenceCount();
  7424. }
  7425. return *this;
  7426. }
  7427. /** Destructor.
  7428. This will decrement the object's reference-count, and may delete it if it
  7429. gets to zero.
  7430. */
  7431. inline ~ReferenceCountedObjectPtr()
  7432. {
  7433. if (referencedObject != nullptr)
  7434. referencedObject->decReferenceCount();
  7435. }
  7436. /** Returns the object that this pointer references.
  7437. The pointer returned may be zero, of course.
  7438. */
  7439. inline operator ReferenceCountedObjectClass*() const noexcept
  7440. {
  7441. return referencedObject;
  7442. }
  7443. // the -> operator is called on the referenced object
  7444. inline ReferenceCountedObjectClass* operator->() const noexcept
  7445. {
  7446. return referencedObject;
  7447. }
  7448. /** Returns the object that this pointer references.
  7449. The pointer returned may be zero, of course.
  7450. */
  7451. inline ReferenceCountedObjectClass* getObject() const noexcept
  7452. {
  7453. return referencedObject;
  7454. }
  7455. private:
  7456. ReferenceCountedObjectClass* referencedObject;
  7457. };
  7458. /** Compares two ReferenceCountedObjectPointers. */
  7459. template <class ReferenceCountedObjectClass>
  7460. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) noexcept
  7461. {
  7462. return object1.getObject() == object2;
  7463. }
  7464. /** Compares two ReferenceCountedObjectPointers. */
  7465. template <class ReferenceCountedObjectClass>
  7466. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7467. {
  7468. return object1.getObject() == object2.getObject();
  7469. }
  7470. /** Compares two ReferenceCountedObjectPointers. */
  7471. template <class ReferenceCountedObjectClass>
  7472. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7473. {
  7474. return object1 == object2.getObject();
  7475. }
  7476. /** Compares two ReferenceCountedObjectPointers. */
  7477. template <class ReferenceCountedObjectClass>
  7478. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) noexcept
  7479. {
  7480. return object1.getObject() != object2;
  7481. }
  7482. /** Compares two ReferenceCountedObjectPointers. */
  7483. template <class ReferenceCountedObjectClass>
  7484. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7485. {
  7486. return object1.getObject() != object2.getObject();
  7487. }
  7488. /** Compares two ReferenceCountedObjectPointers. */
  7489. template <class ReferenceCountedObjectClass>
  7490. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7491. {
  7492. return object1 != object2.getObject();
  7493. }
  7494. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7495. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7496. /**
  7497. Represents a dynamically implemented object.
  7498. This class is primarily intended for wrapping scripting language objects,
  7499. but could be used for other purposes.
  7500. An instance of a DynamicObject can be used to store named properties, and
  7501. by subclassing hasMethod() and invokeMethod(), you can give your object
  7502. methods.
  7503. */
  7504. class JUCE_API DynamicObject : public ReferenceCountedObject
  7505. {
  7506. public:
  7507. DynamicObject();
  7508. /** Destructor. */
  7509. virtual ~DynamicObject();
  7510. /** Returns true if the object has a property with this name.
  7511. Note that if the property is actually a method, this will return false.
  7512. */
  7513. virtual bool hasProperty (const Identifier& propertyName) const;
  7514. /** Returns a named property.
  7515. This returns a void if no such property exists.
  7516. */
  7517. virtual const var getProperty (const Identifier& propertyName) const;
  7518. /** Sets a named property. */
  7519. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7520. /** Removes a named property. */
  7521. virtual void removeProperty (const Identifier& propertyName);
  7522. /** Checks whether this object has the specified method.
  7523. The default implementation of this just checks whether there's a property
  7524. with this name that's actually a method, but this can be overridden for
  7525. building objects with dynamic invocation.
  7526. */
  7527. virtual bool hasMethod (const Identifier& methodName) const;
  7528. /** Invokes a named method on this object.
  7529. The default implementation looks up the named property, and if it's a method
  7530. call, then it invokes it.
  7531. This method is virtual to allow more dynamic invocation to used for objects
  7532. where the methods may not already be set as properies.
  7533. */
  7534. virtual const var invokeMethod (const Identifier& methodName,
  7535. const var* parameters,
  7536. int numParameters);
  7537. /** Sets up a method.
  7538. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7539. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7540. the code easier to read,
  7541. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7542. @code
  7543. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7544. @endcode
  7545. */
  7546. void setMethod (const Identifier& methodName,
  7547. var::MethodFunction methodFunction);
  7548. /** Removes all properties and methods from the object. */
  7549. void clear();
  7550. /** Returns the NamedValueSet that holds the object's properties. */
  7551. NamedValueSet& getProperties() noexcept { return properties; }
  7552. private:
  7553. NamedValueSet properties;
  7554. JUCE_LEAK_DETECTOR (DynamicObject);
  7555. };
  7556. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7557. /*** End of inlined file: juce_DynamicObject.h ***/
  7558. #endif
  7559. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7560. #endif
  7561. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7562. /*** Start of inlined file: juce_HashMap.h ***/
  7563. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7564. #define __JUCE_HASHMAP_JUCEHEADER__
  7565. /*** Start of inlined file: juce_OwnedArray.h ***/
  7566. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7567. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7568. /** An array designed for holding objects.
  7569. This holds a list of pointers to objects, and will automatically
  7570. delete the objects when they are removed from the array, or when the
  7571. array is itself deleted.
  7572. Declare it in the form: OwnedArray<MyObjectClass>
  7573. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7574. After adding objects, they are 'owned' by the array and will be deleted when
  7575. removed or replaced.
  7576. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7577. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7578. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7579. */
  7580. template <class ObjectClass,
  7581. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7582. class OwnedArray
  7583. {
  7584. public:
  7585. /** Creates an empty array. */
  7586. OwnedArray() noexcept
  7587. : numUsed (0)
  7588. {
  7589. }
  7590. /** Deletes the array and also deletes any objects inside it.
  7591. To get rid of the array without deleting its objects, use its
  7592. clear (false) method before deleting it.
  7593. */
  7594. ~OwnedArray()
  7595. {
  7596. clear (true);
  7597. }
  7598. /** Clears the array, optionally deleting the objects inside it first. */
  7599. void clear (const bool deleteObjects = true)
  7600. {
  7601. const ScopedLockType lock (getLock());
  7602. if (deleteObjects)
  7603. {
  7604. while (numUsed > 0)
  7605. delete data.elements [--numUsed];
  7606. }
  7607. data.setAllocatedSize (0);
  7608. numUsed = 0;
  7609. }
  7610. /** Returns the number of items currently in the array.
  7611. @see operator[]
  7612. */
  7613. inline int size() const noexcept
  7614. {
  7615. return numUsed;
  7616. }
  7617. /** Returns a pointer to the object at this index in the array.
  7618. If the index is out-of-range, this will return a null pointer, (and
  7619. it could be null anyway, because it's ok for the array to hold null
  7620. pointers as well as objects).
  7621. @see getUnchecked
  7622. */
  7623. inline ObjectClass* operator[] (const int index) const noexcept
  7624. {
  7625. const ScopedLockType lock (getLock());
  7626. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7627. : static_cast <ObjectClass*> (nullptr);
  7628. }
  7629. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7630. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7631. it can be used when you're sure the index if always going to be legal.
  7632. */
  7633. inline ObjectClass* getUnchecked (const int index) const noexcept
  7634. {
  7635. const ScopedLockType lock (getLock());
  7636. jassert (isPositiveAndBelow (index, numUsed));
  7637. return data.elements [index];
  7638. }
  7639. /** Returns a pointer to the first object in the array.
  7640. This will return a null pointer if the array's empty.
  7641. @see getLast
  7642. */
  7643. inline ObjectClass* getFirst() const noexcept
  7644. {
  7645. const ScopedLockType lock (getLock());
  7646. return numUsed > 0 ? data.elements [0]
  7647. : static_cast <ObjectClass*> (nullptr);
  7648. }
  7649. /** Returns a pointer to the last object in the array.
  7650. This will return a null pointer if the array's empty.
  7651. @see getFirst
  7652. */
  7653. inline ObjectClass* getLast() const noexcept
  7654. {
  7655. const ScopedLockType lock (getLock());
  7656. return numUsed > 0 ? data.elements [numUsed - 1]
  7657. : static_cast <ObjectClass*> (nullptr);
  7658. }
  7659. /** Returns a pointer to the actual array data.
  7660. This pointer will only be valid until the next time a non-const method
  7661. is called on the array.
  7662. */
  7663. inline ObjectClass** getRawDataPointer() noexcept
  7664. {
  7665. return data.elements;
  7666. }
  7667. /** Returns a pointer to the first element in the array.
  7668. This method is provided for compatibility with standard C++ iteration mechanisms.
  7669. */
  7670. inline ObjectClass** begin() const noexcept
  7671. {
  7672. return data.elements;
  7673. }
  7674. /** Returns a pointer to the element which follows the last element in the array.
  7675. This method is provided for compatibility with standard C++ iteration mechanisms.
  7676. */
  7677. inline ObjectClass** end() const noexcept
  7678. {
  7679. return data.elements + numUsed;
  7680. }
  7681. /** Finds the index of an object which might be in the array.
  7682. @param objectToLookFor the object to look for
  7683. @returns the index at which the object was found, or -1 if it's not found
  7684. */
  7685. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  7686. {
  7687. const ScopedLockType lock (getLock());
  7688. ObjectClass* const* e = data.elements.getData();
  7689. ObjectClass* const* const end = e + numUsed;
  7690. for (; e != end; ++e)
  7691. if (objectToLookFor == *e)
  7692. return static_cast <int> (e - data.elements.getData());
  7693. return -1;
  7694. }
  7695. /** Returns true if the array contains a specified object.
  7696. @param objectToLookFor the object to look for
  7697. @returns true if the object is in the array
  7698. */
  7699. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  7700. {
  7701. const ScopedLockType lock (getLock());
  7702. ObjectClass* const* e = data.elements.getData();
  7703. ObjectClass* const* const end = e + numUsed;
  7704. for (; e != end; ++e)
  7705. if (objectToLookFor == *e)
  7706. return true;
  7707. return false;
  7708. }
  7709. /** Appends a new object to the end of the array.
  7710. Note that the this object will be deleted by the OwnedArray when it
  7711. is removed, so be careful not to delete it somewhere else.
  7712. Also be careful not to add the same object to the array more than once,
  7713. as this will obviously cause deletion of dangling pointers.
  7714. @param newObject the new object to add to the array
  7715. @see set, insert, addIfNotAlreadyThere, addSorted
  7716. */
  7717. void add (const ObjectClass* const newObject) noexcept
  7718. {
  7719. const ScopedLockType lock (getLock());
  7720. data.ensureAllocatedSize (numUsed + 1);
  7721. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7722. }
  7723. /** Inserts a new object into the array at the given index.
  7724. Note that the this object will be deleted by the OwnedArray when it
  7725. is removed, so be careful not to delete it somewhere else.
  7726. If the index is less than 0 or greater than the size of the array, the
  7727. element will be added to the end of the array.
  7728. Otherwise, it will be inserted into the array, moving all the later elements
  7729. along to make room.
  7730. Be careful not to add the same object to the array more than once,
  7731. as this will obviously cause deletion of dangling pointers.
  7732. @param indexToInsertAt the index at which the new element should be inserted
  7733. @param newObject the new object to add to the array
  7734. @see add, addSorted, addIfNotAlreadyThere, set
  7735. */
  7736. void insert (int indexToInsertAt,
  7737. const ObjectClass* const newObject) noexcept
  7738. {
  7739. if (indexToInsertAt >= 0)
  7740. {
  7741. const ScopedLockType lock (getLock());
  7742. if (indexToInsertAt > numUsed)
  7743. indexToInsertAt = numUsed;
  7744. data.ensureAllocatedSize (numUsed + 1);
  7745. ObjectClass** const e = data.elements + indexToInsertAt;
  7746. const int numToMove = numUsed - indexToInsertAt;
  7747. if (numToMove > 0)
  7748. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7749. *e = const_cast <ObjectClass*> (newObject);
  7750. ++numUsed;
  7751. }
  7752. else
  7753. {
  7754. add (newObject);
  7755. }
  7756. }
  7757. /** Appends a new object at the end of the array as long as the array doesn't
  7758. already contain it.
  7759. If the array already contains a matching object, nothing will be done.
  7760. @param newObject the new object to add to the array
  7761. */
  7762. void addIfNotAlreadyThere (const ObjectClass* const newObject) noexcept
  7763. {
  7764. const ScopedLockType lock (getLock());
  7765. if (! contains (newObject))
  7766. add (newObject);
  7767. }
  7768. /** Replaces an object in the array with a different one.
  7769. If the index is less than zero, this method does nothing.
  7770. If the index is beyond the end of the array, the new object is added to the end of the array.
  7771. Be careful not to add the same object to the array more than once,
  7772. as this will obviously cause deletion of dangling pointers.
  7773. @param indexToChange the index whose value you want to change
  7774. @param newObject the new value to set for this index.
  7775. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7776. @see add, insert, remove
  7777. */
  7778. void set (const int indexToChange,
  7779. const ObjectClass* const newObject,
  7780. const bool deleteOldElement = true)
  7781. {
  7782. if (indexToChange >= 0)
  7783. {
  7784. ObjectClass* toDelete = nullptr;
  7785. {
  7786. const ScopedLockType lock (getLock());
  7787. if (indexToChange < numUsed)
  7788. {
  7789. if (deleteOldElement)
  7790. {
  7791. toDelete = data.elements [indexToChange];
  7792. if (toDelete == newObject)
  7793. toDelete = nullptr;
  7794. }
  7795. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7796. }
  7797. else
  7798. {
  7799. data.ensureAllocatedSize (numUsed + 1);
  7800. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7801. }
  7802. }
  7803. delete toDelete; // don't want to use a ScopedPointer here because if the
  7804. // object has a private destructor, both OwnedArray and
  7805. // ScopedPointer would need to be friend classes..
  7806. }
  7807. else
  7808. {
  7809. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7810. // any effect - but since the object is not being added, it may be leaking..
  7811. }
  7812. }
  7813. /** Adds elements from another array to the end of this array.
  7814. @param arrayToAddFrom the array from which to copy the elements
  7815. @param startIndex the first element of the other array to start copying from
  7816. @param numElementsToAdd how many elements to add from the other array. If this
  7817. value is negative or greater than the number of available elements,
  7818. all available elements will be copied.
  7819. @see add
  7820. */
  7821. template <class OtherArrayType>
  7822. void addArray (const OtherArrayType& arrayToAddFrom,
  7823. int startIndex = 0,
  7824. int numElementsToAdd = -1)
  7825. {
  7826. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7827. const ScopedLockType lock2 (getLock());
  7828. if (startIndex < 0)
  7829. {
  7830. jassertfalse;
  7831. startIndex = 0;
  7832. }
  7833. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7834. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7835. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7836. while (--numElementsToAdd >= 0)
  7837. {
  7838. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7839. ++numUsed;
  7840. }
  7841. }
  7842. /** Adds copies of the elements in another array to the end of this array.
  7843. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7844. containing pointers to the same kind of object. The objects involved must provide
  7845. a copy constructor, and this will be used to create new copies of each element, and
  7846. add them to this array.
  7847. @param arrayToAddFrom the array from which to copy the elements
  7848. @param startIndex the first element of the other array to start copying from
  7849. @param numElementsToAdd how many elements to add from the other array. If this
  7850. value is negative or greater than the number of available elements,
  7851. all available elements will be copied.
  7852. @see add
  7853. */
  7854. template <class OtherArrayType>
  7855. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7856. int startIndex = 0,
  7857. int numElementsToAdd = -1)
  7858. {
  7859. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7860. const ScopedLockType lock2 (getLock());
  7861. if (startIndex < 0)
  7862. {
  7863. jassertfalse;
  7864. startIndex = 0;
  7865. }
  7866. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7867. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7868. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7869. while (--numElementsToAdd >= 0)
  7870. {
  7871. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7872. ++numUsed;
  7873. }
  7874. }
  7875. /** Inserts a new object into the array assuming that the array is sorted.
  7876. This will use a comparator to find the position at which the new object
  7877. should go. If the array isn't sorted, the behaviour of this
  7878. method will be unpredictable.
  7879. @param comparator the comparator to use to compare the elements - see the sort method
  7880. for details about this object's structure
  7881. @param newObject the new object to insert to the array
  7882. @returns the index at which the new object was added
  7883. @see add, sort, indexOfSorted
  7884. */
  7885. template <class ElementComparator>
  7886. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept
  7887. {
  7888. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7889. // avoids getting warning messages about the parameter being unused
  7890. const ScopedLockType lock (getLock());
  7891. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  7892. insert (index, newObject);
  7893. return index;
  7894. }
  7895. /** Finds the index of an object in the array, assuming that the array is sorted.
  7896. This will use a comparator to do a binary-chop to find the index of the given
  7897. element, if it exists. If the array isn't sorted, the behaviour of this
  7898. method will be unpredictable.
  7899. @param comparator the comparator to use to compare the elements - see the sort()
  7900. method for details about the form this object should take
  7901. @param objectToLookFor the object to search for
  7902. @returns the index of the element, or -1 if it's not found
  7903. @see addSorted, sort
  7904. */
  7905. template <class ElementComparator>
  7906. int indexOfSorted (ElementComparator& comparator,
  7907. const ObjectClass* const objectToLookFor) const noexcept
  7908. {
  7909. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7910. // avoids getting warning messages about the parameter being unused
  7911. const ScopedLockType lock (getLock());
  7912. int start = 0;
  7913. int end = numUsed;
  7914. for (;;)
  7915. {
  7916. if (start >= end)
  7917. {
  7918. return -1;
  7919. }
  7920. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7921. {
  7922. return start;
  7923. }
  7924. else
  7925. {
  7926. const int halfway = (start + end) >> 1;
  7927. if (halfway == start)
  7928. return -1;
  7929. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7930. start = halfway;
  7931. else
  7932. end = halfway;
  7933. }
  7934. }
  7935. }
  7936. /** Removes an object from the array.
  7937. This will remove the object at a given index (optionally also
  7938. deleting it) and move back all the subsequent objects to close the gap.
  7939. If the index passed in is out-of-range, nothing will happen.
  7940. @param indexToRemove the index of the element to remove
  7941. @param deleteObject whether to delete the object that is removed
  7942. @see removeObject, removeRange
  7943. */
  7944. void remove (const int indexToRemove,
  7945. const bool deleteObject = true)
  7946. {
  7947. ObjectClass* toDelete = nullptr;
  7948. {
  7949. const ScopedLockType lock (getLock());
  7950. if (isPositiveAndBelow (indexToRemove, numUsed))
  7951. {
  7952. ObjectClass** const e = data.elements + indexToRemove;
  7953. if (deleteObject)
  7954. toDelete = *e;
  7955. --numUsed;
  7956. const int numToShift = numUsed - indexToRemove;
  7957. if (numToShift > 0)
  7958. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7959. }
  7960. }
  7961. delete toDelete; // don't want to use a ScopedPointer here because if the
  7962. // object has a private destructor, both OwnedArray and
  7963. // ScopedPointer would need to be friend classes..
  7964. if ((numUsed << 1) < data.numAllocated)
  7965. minimiseStorageOverheads();
  7966. }
  7967. /** Removes and returns an object from the array without deleting it.
  7968. This will remove the object at a given index and return it, moving back all
  7969. the subsequent objects to close the gap. If the index passed in is out-of-range,
  7970. nothing will happen.
  7971. @param indexToRemove the index of the element to remove
  7972. @see remove, removeObject, removeRange
  7973. */
  7974. ObjectClass* removeAndReturn (const int indexToRemove)
  7975. {
  7976. ObjectClass* removedItem = nullptr;
  7977. const ScopedLockType lock (getLock());
  7978. if (isPositiveAndBelow (indexToRemove, numUsed))
  7979. {
  7980. ObjectClass** const e = data.elements + indexToRemove;
  7981. removedItem = *e;
  7982. --numUsed;
  7983. const int numToShift = numUsed - indexToRemove;
  7984. if (numToShift > 0)
  7985. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7986. if ((numUsed << 1) < data.numAllocated)
  7987. minimiseStorageOverheads();
  7988. }
  7989. return removedItem;
  7990. }
  7991. /** Removes a specified object from the array.
  7992. If the item isn't found, no action is taken.
  7993. @param objectToRemove the object to try to remove
  7994. @param deleteObject whether to delete the object (if it's found)
  7995. @see remove, removeRange
  7996. */
  7997. void removeObject (const ObjectClass* const objectToRemove,
  7998. const bool deleteObject = true)
  7999. {
  8000. const ScopedLockType lock (getLock());
  8001. ObjectClass** const e = data.elements.getData();
  8002. for (int i = 0; i < numUsed; ++i)
  8003. {
  8004. if (objectToRemove == e[i])
  8005. {
  8006. remove (i, deleteObject);
  8007. break;
  8008. }
  8009. }
  8010. }
  8011. /** Removes a range of objects from the array.
  8012. This will remove a set of objects, starting from the given index,
  8013. and move any subsequent elements down to close the gap.
  8014. If the range extends beyond the bounds of the array, it will
  8015. be safely clipped to the size of the array.
  8016. @param startIndex the index of the first object to remove
  8017. @param numberToRemove how many objects should be removed
  8018. @param deleteObjects whether to delete the objects that get removed
  8019. @see remove, removeObject
  8020. */
  8021. void removeRange (int startIndex,
  8022. const int numberToRemove,
  8023. const bool deleteObjects = true)
  8024. {
  8025. const ScopedLockType lock (getLock());
  8026. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  8027. startIndex = jlimit (0, numUsed, startIndex);
  8028. if (endIndex > startIndex)
  8029. {
  8030. if (deleteObjects)
  8031. {
  8032. for (int i = startIndex; i < endIndex; ++i)
  8033. {
  8034. delete data.elements [i];
  8035. data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8036. }
  8037. }
  8038. const int rangeSize = endIndex - startIndex;
  8039. ObjectClass** e = data.elements + startIndex;
  8040. int numToShift = numUsed - endIndex;
  8041. numUsed -= rangeSize;
  8042. while (--numToShift >= 0)
  8043. {
  8044. *e = e [rangeSize];
  8045. ++e;
  8046. }
  8047. if ((numUsed << 1) < data.numAllocated)
  8048. minimiseStorageOverheads();
  8049. }
  8050. }
  8051. /** Removes the last n objects from the array.
  8052. @param howManyToRemove how many objects to remove from the end of the array
  8053. @param deleteObjects whether to also delete the objects that are removed
  8054. @see remove, removeObject, removeRange
  8055. */
  8056. void removeLast (int howManyToRemove = 1,
  8057. const bool deleteObjects = true)
  8058. {
  8059. const ScopedLockType lock (getLock());
  8060. if (howManyToRemove >= numUsed)
  8061. clear (deleteObjects);
  8062. else
  8063. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  8064. }
  8065. /** Swaps a pair of objects in the array.
  8066. If either of the indexes passed in is out-of-range, nothing will happen,
  8067. otherwise the two objects at these positions will be exchanged.
  8068. */
  8069. void swap (const int index1,
  8070. const int index2) noexcept
  8071. {
  8072. const ScopedLockType lock (getLock());
  8073. if (isPositiveAndBelow (index1, numUsed)
  8074. && isPositiveAndBelow (index2, numUsed))
  8075. {
  8076. swapVariables (data.elements [index1],
  8077. data.elements [index2]);
  8078. }
  8079. }
  8080. /** Moves one of the objects to a different position.
  8081. This will move the object to a specified index, shuffling along
  8082. any intervening elements as required.
  8083. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8084. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8085. @param currentIndex the index of the object to be moved. If this isn't a
  8086. valid index, then nothing will be done
  8087. @param newIndex the index at which you'd like this object to end up. If this
  8088. is less than zero, it will be moved to the end of the array
  8089. */
  8090. void move (const int currentIndex,
  8091. int newIndex) noexcept
  8092. {
  8093. if (currentIndex != newIndex)
  8094. {
  8095. const ScopedLockType lock (getLock());
  8096. if (isPositiveAndBelow (currentIndex, numUsed))
  8097. {
  8098. if (! isPositiveAndBelow (newIndex, numUsed))
  8099. newIndex = numUsed - 1;
  8100. ObjectClass* const value = data.elements [currentIndex];
  8101. if (newIndex > currentIndex)
  8102. {
  8103. memmove (data.elements + currentIndex,
  8104. data.elements + currentIndex + 1,
  8105. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8106. }
  8107. else
  8108. {
  8109. memmove (data.elements + newIndex + 1,
  8110. data.elements + newIndex,
  8111. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8112. }
  8113. data.elements [newIndex] = value;
  8114. }
  8115. }
  8116. }
  8117. /** This swaps the contents of this array with those of another array.
  8118. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8119. because it just swaps their internal pointers.
  8120. */
  8121. void swapWithArray (OwnedArray& otherArray) noexcept
  8122. {
  8123. const ScopedLockType lock1 (getLock());
  8124. const ScopedLockType lock2 (otherArray.getLock());
  8125. data.swapWith (otherArray.data);
  8126. swapVariables (numUsed, otherArray.numUsed);
  8127. }
  8128. /** Reduces the amount of storage being used by the array.
  8129. Arrays typically allocate slightly more storage than they need, and after
  8130. removing elements, they may have quite a lot of unused space allocated.
  8131. This method will reduce the amount of allocated storage to a minimum.
  8132. */
  8133. void minimiseStorageOverheads() noexcept
  8134. {
  8135. const ScopedLockType lock (getLock());
  8136. data.shrinkToNoMoreThan (numUsed);
  8137. }
  8138. /** Increases the array's internal storage to hold a minimum number of elements.
  8139. Calling this before adding a large known number of elements means that
  8140. the array won't have to keep dynamically resizing itself as the elements
  8141. are added, and it'll therefore be more efficient.
  8142. */
  8143. void ensureStorageAllocated (const int minNumElements) noexcept
  8144. {
  8145. const ScopedLockType lock (getLock());
  8146. data.ensureAllocatedSize (minNumElements);
  8147. }
  8148. /** Sorts the elements in the array.
  8149. This will use a comparator object to sort the elements into order. The object
  8150. passed must have a method of the form:
  8151. @code
  8152. int compareElements (ElementType first, ElementType second);
  8153. @endcode
  8154. ..and this method must return:
  8155. - a value of < 0 if the first comes before the second
  8156. - a value of 0 if the two objects are equivalent
  8157. - a value of > 0 if the second comes before the first
  8158. To improve performance, the compareElements() method can be declared as static or const.
  8159. @param comparator the comparator to use for comparing elements.
  8160. @param retainOrderOfEquivalentItems if this is true, then items
  8161. which the comparator says are equivalent will be
  8162. kept in the order in which they currently appear
  8163. in the array. This is slower to perform, but may
  8164. be important in some cases. If it's false, a faster
  8165. algorithm is used, but equivalent elements may be
  8166. rearranged.
  8167. @see sortArray, indexOfSorted
  8168. */
  8169. template <class ElementComparator>
  8170. void sort (ElementComparator& comparator,
  8171. const bool retainOrderOfEquivalentItems = false) const noexcept
  8172. {
  8173. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8174. // avoids getting warning messages about the parameter being unused
  8175. const ScopedLockType lock (getLock());
  8176. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8177. }
  8178. /** Returns the CriticalSection that locks this array.
  8179. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8180. an object of ScopedLockType as an RAII lock for it.
  8181. */
  8182. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  8183. /** Returns the type of scoped lock to use for locking this array */
  8184. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8185. private:
  8186. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8187. int numUsed;
  8188. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8189. };
  8190. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8191. /*** End of inlined file: juce_OwnedArray.h ***/
  8192. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8193. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8194. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8195. /**
  8196. This class holds a pointer which is automatically deleted when this object goes
  8197. out of scope.
  8198. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8199. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8200. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8201. created objects.
  8202. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8203. to an object. If you use the assignment operator to assign a different object to a
  8204. ScopedPointer, the old one will be automatically deleted.
  8205. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8206. object to which it points during its lifetime. This means that making a copy of a const
  8207. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8208. old one.
  8209. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8210. can use the release() method.
  8211. */
  8212. template <class ObjectType>
  8213. class ScopedPointer
  8214. {
  8215. public:
  8216. /** Creates a ScopedPointer containing a null pointer. */
  8217. inline ScopedPointer() noexcept : object (nullptr)
  8218. {
  8219. }
  8220. /** Creates a ScopedPointer that owns the specified object. */
  8221. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) noexcept
  8222. : object (objectToTakePossessionOf)
  8223. {
  8224. }
  8225. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8226. Because a pointer can only belong to one ScopedPointer, this transfers
  8227. the pointer from the other object to this one, and the other object is reset to
  8228. be a null pointer.
  8229. */
  8230. ScopedPointer (ScopedPointer& objectToTransferFrom) noexcept
  8231. : object (objectToTransferFrom.object)
  8232. {
  8233. objectToTransferFrom.object = nullptr;
  8234. }
  8235. /** Destructor.
  8236. This will delete the object that this ScopedPointer currently refers to.
  8237. */
  8238. inline ~ScopedPointer() { delete object; }
  8239. /** Changes this ScopedPointer to point to a new object.
  8240. Because a pointer can only belong to one ScopedPointer, this transfers
  8241. the pointer from the other object to this one, and the other object is reset to
  8242. be a null pointer.
  8243. If this ScopedPointer already points to an object, that object
  8244. will first be deleted.
  8245. */
  8246. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8247. {
  8248. if (this != objectToTransferFrom.getAddress())
  8249. {
  8250. // Two ScopedPointers should never be able to refer to the same object - if
  8251. // this happens, you must have done something dodgy!
  8252. jassert (object == nullptr || object != objectToTransferFrom.object);
  8253. ObjectType* const oldObject = object;
  8254. object = objectToTransferFrom.object;
  8255. objectToTransferFrom.object = nullptr;
  8256. delete oldObject;
  8257. }
  8258. return *this;
  8259. }
  8260. /** Changes this ScopedPointer to point to a new object.
  8261. If this ScopedPointer already points to an object, that object
  8262. will first be deleted.
  8263. The pointer that you pass is may be null.
  8264. */
  8265. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8266. {
  8267. if (object != newObjectToTakePossessionOf)
  8268. {
  8269. ObjectType* const oldObject = object;
  8270. object = newObjectToTakePossessionOf;
  8271. delete oldObject;
  8272. }
  8273. return *this;
  8274. }
  8275. /** Returns the object that this ScopedPointer refers to. */
  8276. inline operator ObjectType*() const noexcept { return object; }
  8277. /** Returns the object that this ScopedPointer refers to. */
  8278. inline ObjectType& operator*() const noexcept { return *object; }
  8279. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8280. inline ObjectType* operator->() const noexcept { return object; }
  8281. /** Removes the current object from this ScopedPointer without deleting it.
  8282. This will return the current object, and set the ScopedPointer to a null pointer.
  8283. */
  8284. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  8285. /** Swaps this object with that of another ScopedPointer.
  8286. The two objects simply exchange their pointers.
  8287. */
  8288. void swapWith (ScopedPointer <ObjectType>& other) noexcept
  8289. {
  8290. // Two ScopedPointers should never be able to refer to the same object - if
  8291. // this happens, you must have done something dodgy!
  8292. jassert (object != other.object);
  8293. std::swap (object, other.object);
  8294. }
  8295. private:
  8296. ObjectType* object;
  8297. // (Required as an alternative to the overloaded & operator).
  8298. const ScopedPointer* getAddress() const noexcept { return this; }
  8299. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8300. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8301. would let you do so by implicitly casting the source to its raw object pointer).
  8302. A side effect of this is that you may hit a puzzling compiler error when you write something
  8303. like this:
  8304. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8305. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8306. copy constructor is private. It's very easy to fis though - just write it like this:
  8307. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8308. It's good practice to always use the latter form when writing your object declarations anyway,
  8309. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8310. smart enough to replace your construction + assignment with a single constructor.
  8311. */
  8312. ScopedPointer (const ScopedPointer&);
  8313. #endif
  8314. };
  8315. /** Compares a ScopedPointer with another pointer.
  8316. This can be handy for checking whether this is a null pointer.
  8317. */
  8318. template <class ObjectType>
  8319. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8320. {
  8321. return static_cast <ObjectType*> (pointer1) == pointer2;
  8322. }
  8323. /** Compares a ScopedPointer with another pointer.
  8324. This can be handy for checking whether this is a null pointer.
  8325. */
  8326. template <class ObjectType>
  8327. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8328. {
  8329. return static_cast <ObjectType*> (pointer1) != pointer2;
  8330. }
  8331. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8332. /*** End of inlined file: juce_ScopedPointer.h ***/
  8333. /**
  8334. A simple class to generate hash functions for some primitive types, intended for
  8335. use with the HashMap class.
  8336. @see HashMap
  8337. */
  8338. class DefaultHashFunctions
  8339. {
  8340. public:
  8341. /** Generates a simple hash from an integer. */
  8342. static int generateHash (const int key, const int upperLimit) noexcept { return std::abs (key) % upperLimit; }
  8343. /** Generates a simple hash from a string. */
  8344. static int generateHash (const String& key, const int upperLimit) noexcept { return (int) (((uint32) key.hashCode()) % upperLimit); }
  8345. /** Generates a simple hash from a variant. */
  8346. static int generateHash (const var& key, const int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
  8347. };
  8348. /**
  8349. Holds a set of mappings between some key/value pairs.
  8350. The types of the key and value objects are set as template parameters.
  8351. You can also specify a class to supply a hash function that converts a key value
  8352. into an hashed integer. This class must have the form:
  8353. @code
  8354. struct MyHashGenerator
  8355. {
  8356. static int generateHash (MyKeyType key, int upperLimit)
  8357. {
  8358. // The function must return a value 0 <= x < upperLimit
  8359. return someFunctionOfMyKeyType (key) % upperLimit;
  8360. }
  8361. };
  8362. @endcode
  8363. Like the Array class, the key and value types are expected to be copy-by-value types, so
  8364. if you define them to be pointer types, this class won't delete the objects that they
  8365. point to.
  8366. If you don't supply a class for the HashFunctionToUse template parameter, the
  8367. default one provides some simple mappings for strings and ints.
  8368. @code
  8369. HashMap<int, String> hash;
  8370. hash.set (1, "item1");
  8371. hash.set (2, "item2");
  8372. DBG (hash [1]); // prints "item1"
  8373. DBG (hash [2]); // prints "item2"
  8374. // This iterates the map, printing all of its key -> value pairs..
  8375. for (HashMap<int, String>::Iterator i (hash); i.next();)
  8376. DBG (i.getKey() << " -> " << i.getValue());
  8377. @endcode
  8378. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  8379. */
  8380. template <typename KeyType,
  8381. typename ValueType,
  8382. class HashFunctionToUse = DefaultHashFunctions,
  8383. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8384. class HashMap
  8385. {
  8386. private:
  8387. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  8388. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  8389. public:
  8390. /** Creates an empty hash-map.
  8391. The numberOfSlots parameter specifies the number of hash entries the map will use. This
  8392. will be the "upperLimit" parameter that is passed to your generateHash() function. The number
  8393. of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable().
  8394. */
  8395. HashMap (const int numberOfSlots = defaultHashTableSize)
  8396. : totalNumItems (0)
  8397. {
  8398. slots.insertMultiple (0, nullptr, numberOfSlots);
  8399. }
  8400. /** Destructor. */
  8401. ~HashMap()
  8402. {
  8403. clear();
  8404. }
  8405. /** Removes all values from the map.
  8406. Note that this will clear the content, but won't affect the number of slots (see
  8407. remapTable and getNumSlots).
  8408. */
  8409. void clear()
  8410. {
  8411. const ScopedLockType sl (getLock());
  8412. for (int i = slots.size(); --i >= 0;)
  8413. {
  8414. HashEntry* h = slots.getUnchecked(i);
  8415. while (h != nullptr)
  8416. {
  8417. const ScopedPointer<HashEntry> deleter (h);
  8418. h = h->nextEntry;
  8419. }
  8420. slots.set (i, nullptr);
  8421. }
  8422. totalNumItems = 0;
  8423. }
  8424. /** Returns the current number of items in the map. */
  8425. inline int size() const noexcept
  8426. {
  8427. return totalNumItems;
  8428. }
  8429. /** Returns the value corresponding to a given key.
  8430. If the map doesn't contain the key, a default instance of the value type is returned.
  8431. @param keyToLookFor the key of the item being requested
  8432. */
  8433. inline const ValueType operator[] (KeyTypeParameter keyToLookFor) const
  8434. {
  8435. const ScopedLockType sl (getLock());
  8436. for (const HashEntry* entry = slots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  8437. if (entry->key == keyToLookFor)
  8438. return entry->value;
  8439. return ValueType();
  8440. }
  8441. /** Returns true if the map contains an item with the specied key. */
  8442. bool contains (KeyTypeParameter keyToLookFor) const
  8443. {
  8444. const ScopedLockType sl (getLock());
  8445. for (const HashEntry* entry = slots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  8446. if (entry->key == keyToLookFor)
  8447. return true;
  8448. return false;
  8449. }
  8450. /** Returns true if the hash contains at least one occurrence of a given value. */
  8451. bool containsValue (ValueTypeParameter valueToLookFor) const
  8452. {
  8453. const ScopedLockType sl (getLock());
  8454. for (int i = getNumSlots(); --i >= 0;)
  8455. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8456. if (entry->value == valueToLookFor)
  8457. return true;
  8458. return false;
  8459. }
  8460. /** Adds or replaces an element in the hash-map.
  8461. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  8462. will be added to the map.
  8463. */
  8464. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  8465. {
  8466. const ScopedLockType sl (getLock());
  8467. const int hashIndex = generateHashFor (newKey);
  8468. HashEntry* const firstEntry = slots.getUnchecked (hashIndex);
  8469. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  8470. {
  8471. if (entry->key == newKey)
  8472. {
  8473. entry->value = newValue;
  8474. return;
  8475. }
  8476. }
  8477. slots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  8478. ++totalNumItems;
  8479. if (totalNumItems > (getNumSlots() * 3) / 2)
  8480. remapTable (getNumSlots() * 2);
  8481. }
  8482. /** Removes an item with the given key. */
  8483. void remove (KeyTypeParameter keyToRemove)
  8484. {
  8485. const ScopedLockType sl (getLock());
  8486. const int hashIndex = generateHashFor (keyToRemove);
  8487. HashEntry* entry = slots.getUnchecked (hashIndex);
  8488. HashEntry* previous = nullptr;
  8489. while (entry != nullptr)
  8490. {
  8491. if (entry->key == keyToRemove)
  8492. {
  8493. const ScopedPointer<HashEntry> deleter (entry);
  8494. entry = entry->nextEntry;
  8495. if (previous != nullptr)
  8496. previous->nextEntry = entry;
  8497. else
  8498. slots.set (hashIndex, entry);
  8499. --totalNumItems;
  8500. }
  8501. else
  8502. {
  8503. previous = entry;
  8504. entry = entry->nextEntry;
  8505. }
  8506. }
  8507. }
  8508. /** Removes all items with the given value. */
  8509. void removeValue (ValueTypeParameter valueToRemove)
  8510. {
  8511. const ScopedLockType sl (getLock());
  8512. for (int i = getNumSlots(); --i >= 0;)
  8513. {
  8514. HashEntry* entry = slots.getUnchecked(i);
  8515. HashEntry* previous = nullptr;
  8516. while (entry != nullptr)
  8517. {
  8518. if (entry->value == valueToRemove)
  8519. {
  8520. const ScopedPointer<HashEntry> deleter (entry);
  8521. entry = entry->nextEntry;
  8522. if (previous != nullptr)
  8523. previous->nextEntry = entry;
  8524. else
  8525. slots.set (i, entry);
  8526. --totalNumItems;
  8527. }
  8528. else
  8529. {
  8530. previous = entry;
  8531. entry = entry->nextEntry;
  8532. }
  8533. }
  8534. }
  8535. }
  8536. /** Remaps the hash-map to use a different number of slots for its hash function.
  8537. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8538. @see getNumSlots()
  8539. */
  8540. void remapTable (int newNumberOfSlots)
  8541. {
  8542. HashMap newTable (newNumberOfSlots);
  8543. for (int i = getNumSlots(); --i >= 0;)
  8544. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8545. newTable.set (entry->key, entry->value);
  8546. swapWith (newTable);
  8547. }
  8548. /** Returns the number of slots which are available for hashing.
  8549. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8550. @see getNumSlots()
  8551. */
  8552. inline int getNumSlots() const noexcept
  8553. {
  8554. return slots.size();
  8555. }
  8556. /** Efficiently swaps the contents of two hash-maps. */
  8557. void swapWith (HashMap& otherHashMap) noexcept
  8558. {
  8559. const ScopedLockType lock1 (getLock());
  8560. const ScopedLockType lock2 (otherHashMap.getLock());
  8561. slots.swapWithArray (otherHashMap.slots);
  8562. std::swap (totalNumItems, otherHashMap.totalNumItems);
  8563. }
  8564. /** Returns the CriticalSection that locks this structure.
  8565. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8566. an object of ScopedLockType as an RAII lock for it.
  8567. */
  8568. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  8569. /** Returns the type of scoped lock to use for locking this array */
  8570. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8571. private:
  8572. class HashEntry
  8573. {
  8574. public:
  8575. HashEntry (KeyTypeParameter key_, ValueTypeParameter value_, HashEntry* const nextEntry_)
  8576. : key (key_), value (value_), nextEntry (nextEntry_)
  8577. {}
  8578. const KeyType key;
  8579. ValueType value;
  8580. HashEntry* nextEntry;
  8581. JUCE_DECLARE_NON_COPYABLE (HashEntry);
  8582. };
  8583. public:
  8584. /** Iterates over the items in a HashMap.
  8585. To use it, repeatedly call next() until it returns false, e.g.
  8586. @code
  8587. HashMap <String, String> myMap;
  8588. HashMap<String, String>::Iterator i (myMap);
  8589. while (i.next())
  8590. {
  8591. DBG (i.getKey() << " -> " << i.getValue());
  8592. }
  8593. @endcode
  8594. The order in which items are iterated bears no resemblence to the order in which
  8595. they were originally added!
  8596. Obviously as soon as you call any non-const methods on the original hash-map, any
  8597. iterators that were created beforehand will cease to be valid, and should not be used.
  8598. @see HashMap
  8599. */
  8600. class Iterator
  8601. {
  8602. public:
  8603. Iterator (const HashMap& hashMapToIterate)
  8604. : hashMap (hashMapToIterate), entry (0), index (0)
  8605. {}
  8606. /** Moves to the next item, if one is available.
  8607. When this returns true, you can get the item's key and value using getKey() and
  8608. getValue(). If it returns false, the iteration has finished and you should stop.
  8609. */
  8610. bool next()
  8611. {
  8612. if (entry != nullptr)
  8613. entry = entry->nextEntry;
  8614. while (entry == nullptr)
  8615. {
  8616. if (index >= hashMap.getNumSlots())
  8617. return false;
  8618. entry = hashMap.slots.getUnchecked (index++);
  8619. }
  8620. return true;
  8621. }
  8622. /** Returns the current item's key.
  8623. This should only be called when a call to next() has just returned true.
  8624. */
  8625. const KeyType getKey() const
  8626. {
  8627. return entry != nullptr ? entry->key : KeyType();
  8628. }
  8629. /** Returns the current item's value.
  8630. This should only be called when a call to next() has just returned true.
  8631. */
  8632. const ValueType getValue() const
  8633. {
  8634. return entry != nullptr ? entry->value : ValueType();
  8635. }
  8636. private:
  8637. const HashMap& hashMap;
  8638. HashEntry* entry;
  8639. int index;
  8640. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator);
  8641. };
  8642. private:
  8643. enum { defaultHashTableSize = 101 };
  8644. friend class Iterator;
  8645. Array <HashEntry*> slots;
  8646. int totalNumItems;
  8647. TypeOfCriticalSectionToUse lock;
  8648. int generateHashFor (KeyTypeParameter key) const
  8649. {
  8650. const int hash = HashFunctionToUse::generateHash (key, getNumSlots());
  8651. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  8652. return hash;
  8653. }
  8654. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap);
  8655. };
  8656. #endif // __JUCE_HASHMAP_JUCEHEADER__
  8657. /*** End of inlined file: juce_HashMap.h ***/
  8658. #endif
  8659. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  8660. #endif
  8661. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  8662. #endif
  8663. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  8664. #endif
  8665. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8666. /*** Start of inlined file: juce_PropertySet.h ***/
  8667. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8668. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8669. /*** Start of inlined file: juce_StringPairArray.h ***/
  8670. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8671. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8672. /*** Start of inlined file: juce_StringArray.h ***/
  8673. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8674. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8675. /**
  8676. A special array for holding a list of strings.
  8677. @see String, StringPairArray
  8678. */
  8679. class JUCE_API StringArray
  8680. {
  8681. public:
  8682. /** Creates an empty string array */
  8683. StringArray() noexcept;
  8684. /** Creates a copy of another string array */
  8685. StringArray (const StringArray& other);
  8686. /** Creates an array containing a single string. */
  8687. explicit StringArray (const String& firstValue);
  8688. /** Creates a copy of an array of string literals.
  8689. @param strings an array of strings to add. Null pointers in the array will be
  8690. treated as empty strings
  8691. @param numberOfStrings how many items there are in the array
  8692. */
  8693. StringArray (const char* const* strings, int numberOfStrings);
  8694. /** Creates a copy of a null-terminated array of string literals.
  8695. Each item from the array passed-in is added, until it encounters a null pointer,
  8696. at which point it stops.
  8697. */
  8698. explicit StringArray (const char* const* strings);
  8699. /** Creates a copy of a null-terminated array of string literals.
  8700. Each item from the array passed-in is added, until it encounters a null pointer,
  8701. at which point it stops.
  8702. */
  8703. explicit StringArray (const wchar_t* const* strings);
  8704. /** Creates a copy of an array of string literals.
  8705. @param strings an array of strings to add. Null pointers in the array will be
  8706. treated as empty strings
  8707. @param numberOfStrings how many items there are in the array
  8708. */
  8709. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8710. /** Destructor. */
  8711. ~StringArray();
  8712. /** Copies the contents of another string array into this one */
  8713. StringArray& operator= (const StringArray& other);
  8714. /** Compares two arrays.
  8715. Comparisons are case-sensitive.
  8716. @returns true only if the other array contains exactly the same strings in the same order
  8717. */
  8718. bool operator== (const StringArray& other) const noexcept;
  8719. /** Compares two arrays.
  8720. Comparisons are case-sensitive.
  8721. @returns false if the other array contains exactly the same strings in the same order
  8722. */
  8723. bool operator!= (const StringArray& other) const noexcept;
  8724. /** Returns the number of strings in the array */
  8725. inline int size() const noexcept { return strings.size(); };
  8726. /** Returns one of the strings from the array.
  8727. If the index is out-of-range, an empty string is returned.
  8728. Obviously the reference returned shouldn't be stored for later use, as the
  8729. string it refers to may disappear when the array changes.
  8730. */
  8731. const String& operator[] (int index) const noexcept;
  8732. /** Returns a reference to one of the strings in the array.
  8733. This lets you modify a string in-place in the array, but you must be sure that
  8734. the index is in-range.
  8735. */
  8736. String& getReference (int index) noexcept;
  8737. /** Searches for a string in the array.
  8738. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8739. @returns true if the string is found inside the array
  8740. */
  8741. bool contains (const String& stringToLookFor,
  8742. bool ignoreCase = false) const;
  8743. /** Searches for a string in the array.
  8744. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8745. @param stringToLookFor the string to try to find
  8746. @param ignoreCase whether the comparison should be case-insensitive
  8747. @param startIndex the first index to start searching from
  8748. @returns the index of the first occurrence of the string in this array,
  8749. or -1 if it isn't found.
  8750. */
  8751. int indexOf (const String& stringToLookFor,
  8752. bool ignoreCase = false,
  8753. int startIndex = 0) const;
  8754. /** Appends a string at the end of the array. */
  8755. void add (const String& stringToAdd);
  8756. /** Inserts a string into the array.
  8757. This will insert a string into the array at the given index, moving
  8758. up the other elements to make room for it.
  8759. If the index is less than zero or greater than the size of the array,
  8760. the new string will be added to the end of the array.
  8761. */
  8762. void insert (int index, const String& stringToAdd);
  8763. /** Adds a string to the array as long as it's not already in there.
  8764. The search can optionally be case-insensitive.
  8765. */
  8766. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8767. /** Replaces one of the strings in the array with another one.
  8768. If the index is higher than the array's size, the new string will be
  8769. added to the end of the array; if it's less than zero nothing happens.
  8770. */
  8771. void set (int index, const String& newString);
  8772. /** Appends some strings from another array to the end of this one.
  8773. @param other the array to add
  8774. @param startIndex the first element of the other array to add
  8775. @param numElementsToAdd the maximum number of elements to add (if this is
  8776. less than zero, they are all added)
  8777. */
  8778. void addArray (const StringArray& other,
  8779. int startIndex = 0,
  8780. int numElementsToAdd = -1);
  8781. /** Breaks up a string into tokens and adds them to this array.
  8782. This will tokenise the given string using whitespace characters as the
  8783. token delimiters, and will add these tokens to the end of the array.
  8784. @returns the number of tokens added
  8785. */
  8786. int addTokens (const String& stringToTokenise,
  8787. bool preserveQuotedStrings);
  8788. /** Breaks up a string into tokens and adds them to this array.
  8789. This will tokenise the given string (using the string passed in to define the
  8790. token delimiters), and will add these tokens to the end of the array.
  8791. @param stringToTokenise the string to tokenise
  8792. @param breakCharacters a string of characters, any of which will be considered
  8793. to be a token delimiter.
  8794. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8795. which are treated as quotes. Any text occurring
  8796. between quotes is not broken up into tokens.
  8797. @returns the number of tokens added
  8798. */
  8799. int addTokens (const String& stringToTokenise,
  8800. const String& breakCharacters,
  8801. const String& quoteCharacters);
  8802. /** Breaks up a string into lines and adds them to this array.
  8803. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8804. to the array. Line-break characters are omitted from the strings that are added to
  8805. the array.
  8806. */
  8807. int addLines (const String& stringToBreakUp);
  8808. /** Removes all elements from the array. */
  8809. void clear();
  8810. /** Removes a string from the array.
  8811. If the index is out-of-range, no action will be taken.
  8812. */
  8813. void remove (int index);
  8814. /** Finds a string in the array and removes it.
  8815. This will remove the first occurrence of the given string from the array. The
  8816. comparison may be case-insensitive depending on the ignoreCase parameter.
  8817. */
  8818. void removeString (const String& stringToRemove,
  8819. bool ignoreCase = false);
  8820. /** Removes a range of elements from the array.
  8821. This will remove a set of elements, starting from the given index,
  8822. and move subsequent elements down to close the gap.
  8823. If the range extends beyond the bounds of the array, it will
  8824. be safely clipped to the size of the array.
  8825. @param startIndex the index of the first element to remove
  8826. @param numberToRemove how many elements should be removed
  8827. */
  8828. void removeRange (int startIndex, int numberToRemove);
  8829. /** Removes any duplicated elements from the array.
  8830. If any string appears in the array more than once, only the first occurrence of
  8831. it will be retained.
  8832. @param ignoreCase whether to use a case-insensitive comparison
  8833. */
  8834. void removeDuplicates (bool ignoreCase);
  8835. /** Removes empty strings from the array.
  8836. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8837. characters will also be removed
  8838. */
  8839. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8840. /** Moves one of the strings to a different position.
  8841. This will move the string to a specified index, shuffling along
  8842. any intervening elements as required.
  8843. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8844. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8845. @param currentIndex the index of the value to be moved. If this isn't a
  8846. valid index, then nothing will be done
  8847. @param newIndex the index at which you'd like this value to end up. If this
  8848. is less than zero, the value will be moved to the end
  8849. of the array
  8850. */
  8851. void move (int currentIndex, int newIndex) noexcept;
  8852. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8853. void trim();
  8854. /** Adds numbers to the strings in the array, to make each string unique.
  8855. This will add numbers to the ends of groups of similar strings.
  8856. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8857. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8858. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8859. also has a number appended to it.
  8860. @param preNumberString when adding a number, this string is added before the number.
  8861. If you pass 0, a default string will be used, which adds
  8862. brackets around the number.
  8863. @param postNumberString this string is appended after any numbers that are added.
  8864. If you pass 0, a default string will be used, which adds
  8865. brackets around the number.
  8866. */
  8867. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8868. bool appendNumberToFirstInstance,
  8869. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (nullptr),
  8870. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (nullptr));
  8871. /** Joins the strings in the array together into one string.
  8872. This will join a range of elements from the array into a string, separating
  8873. them with a given string.
  8874. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8875. @param separatorString the string to insert between all the strings
  8876. @param startIndex the first element to join
  8877. @param numberOfElements how many elements to join together. If this is less
  8878. than zero, all available elements will be used.
  8879. */
  8880. String joinIntoString (const String& separatorString,
  8881. int startIndex = 0,
  8882. int numberOfElements = -1) const;
  8883. /** Sorts the array into alphabetical order.
  8884. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8885. */
  8886. void sort (bool ignoreCase);
  8887. /** Reduces the amount of storage being used by the array.
  8888. Arrays typically allocate slightly more storage than they need, and after
  8889. removing elements, they may have quite a lot of unused space allocated.
  8890. This method will reduce the amount of allocated storage to a minimum.
  8891. */
  8892. void minimiseStorageOverheads();
  8893. private:
  8894. Array <String> strings;
  8895. JUCE_LEAK_DETECTOR (StringArray);
  8896. };
  8897. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8898. /*** End of inlined file: juce_StringArray.h ***/
  8899. /**
  8900. A container for holding a set of strings which are keyed by another string.
  8901. @see StringArray
  8902. */
  8903. class JUCE_API StringPairArray
  8904. {
  8905. public:
  8906. /** Creates an empty array */
  8907. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8908. /** Creates a copy of another array */
  8909. StringPairArray (const StringPairArray& other);
  8910. /** Destructor. */
  8911. ~StringPairArray();
  8912. /** Copies the contents of another string array into this one */
  8913. StringPairArray& operator= (const StringPairArray& other);
  8914. /** Compares two arrays.
  8915. Comparisons are case-sensitive.
  8916. @returns true only if the other array contains exactly the same strings with the same keys
  8917. */
  8918. bool operator== (const StringPairArray& other) const;
  8919. /** Compares two arrays.
  8920. Comparisons are case-sensitive.
  8921. @returns false if the other array contains exactly the same strings with the same keys
  8922. */
  8923. bool operator!= (const StringPairArray& other) const;
  8924. /** Finds the value corresponding to a key string.
  8925. If no such key is found, this will just return an empty string. To check whether
  8926. a given key actually exists (because it might actually be paired with an empty string), use
  8927. the getAllKeys() method to obtain a list.
  8928. Obviously the reference returned shouldn't be stored for later use, as the
  8929. string it refers to may disappear when the array changes.
  8930. @see getValue
  8931. */
  8932. const String& operator[] (const String& key) const;
  8933. /** Finds the value corresponding to a key string.
  8934. If no such key is found, this will just return the value provided as a default.
  8935. @see operator[]
  8936. */
  8937. String getValue (const String& key, const String& defaultReturnValue) const;
  8938. /** Returns a list of all keys in the array. */
  8939. const StringArray& getAllKeys() const noexcept { return keys; }
  8940. /** Returns a list of all values in the array. */
  8941. const StringArray& getAllValues() const noexcept { return values; }
  8942. /** Returns the number of strings in the array */
  8943. inline int size() const noexcept { return keys.size(); };
  8944. /** Adds or amends a key/value pair.
  8945. If a value already exists with this key, its value will be overwritten,
  8946. otherwise the key/value pair will be added to the array.
  8947. */
  8948. void set (const String& key, const String& value);
  8949. /** Adds the items from another array to this one.
  8950. This is equivalent to using set() to add each of the pairs from the other array.
  8951. */
  8952. void addArray (const StringPairArray& other);
  8953. /** Removes all elements from the array. */
  8954. void clear();
  8955. /** Removes a string from the array based on its key.
  8956. If the key isn't found, nothing will happen.
  8957. */
  8958. void remove (const String& key);
  8959. /** Removes a string from the array based on its index.
  8960. If the index is out-of-range, no action will be taken.
  8961. */
  8962. void remove (int index);
  8963. /** Indicates whether to use a case-insensitive search when looking up a key string.
  8964. */
  8965. void setIgnoresCase (bool shouldIgnoreCase);
  8966. /** Returns a descriptive string containing the items.
  8967. This is handy for dumping the contents of an array.
  8968. */
  8969. String getDescription() const;
  8970. /** Reduces the amount of storage being used by the array.
  8971. Arrays typically allocate slightly more storage than they need, and after
  8972. removing elements, they may have quite a lot of unused space allocated.
  8973. This method will reduce the amount of allocated storage to a minimum.
  8974. */
  8975. void minimiseStorageOverheads();
  8976. private:
  8977. StringArray keys, values;
  8978. bool ignoreCase;
  8979. JUCE_LEAK_DETECTOR (StringPairArray);
  8980. };
  8981. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8982. /*** End of inlined file: juce_StringPairArray.h ***/
  8983. /*** Start of inlined file: juce_XmlElement.h ***/
  8984. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  8985. #define __JUCE_XMLELEMENT_JUCEHEADER__
  8986. /*** Start of inlined file: juce_File.h ***/
  8987. #ifndef __JUCE_FILE_JUCEHEADER__
  8988. #define __JUCE_FILE_JUCEHEADER__
  8989. /*** Start of inlined file: juce_Time.h ***/
  8990. #ifndef __JUCE_TIME_JUCEHEADER__
  8991. #define __JUCE_TIME_JUCEHEADER__
  8992. /*** Start of inlined file: juce_RelativeTime.h ***/
  8993. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  8994. #define __JUCE_RELATIVETIME_JUCEHEADER__
  8995. /** A relative measure of time.
  8996. The time is stored as a number of seconds, at double-precision floating
  8997. point accuracy, and may be positive or negative.
  8998. If you need an absolute time, (i.e. a date + time), see the Time class.
  8999. */
  9000. class JUCE_API RelativeTime
  9001. {
  9002. public:
  9003. /** Creates a RelativeTime.
  9004. @param seconds the number of seconds, which may be +ve or -ve.
  9005. @see milliseconds, minutes, hours, days, weeks
  9006. */
  9007. explicit RelativeTime (double seconds = 0.0) noexcept;
  9008. /** Copies another relative time. */
  9009. RelativeTime (const RelativeTime& other) noexcept;
  9010. /** Copies another relative time. */
  9011. RelativeTime& operator= (const RelativeTime& other) noexcept;
  9012. /** Destructor. */
  9013. ~RelativeTime() noexcept;
  9014. /** Creates a new RelativeTime object representing a number of milliseconds.
  9015. @see minutes, hours, days, weeks
  9016. */
  9017. static const RelativeTime milliseconds (int milliseconds) noexcept;
  9018. /** Creates a new RelativeTime object representing a number of milliseconds.
  9019. @see minutes, hours, days, weeks
  9020. */
  9021. static const RelativeTime milliseconds (int64 milliseconds) noexcept;
  9022. /** Creates a new RelativeTime object representing a number of minutes.
  9023. @see milliseconds, hours, days, weeks
  9024. */
  9025. static const RelativeTime minutes (double numberOfMinutes) noexcept;
  9026. /** Creates a new RelativeTime object representing a number of hours.
  9027. @see milliseconds, minutes, days, weeks
  9028. */
  9029. static const RelativeTime hours (double numberOfHours) noexcept;
  9030. /** Creates a new RelativeTime object representing a number of days.
  9031. @see milliseconds, minutes, hours, weeks
  9032. */
  9033. static const RelativeTime days (double numberOfDays) noexcept;
  9034. /** Creates a new RelativeTime object representing a number of weeks.
  9035. @see milliseconds, minutes, hours, days
  9036. */
  9037. static const RelativeTime weeks (double numberOfWeeks) noexcept;
  9038. /** Returns the number of milliseconds this time represents.
  9039. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9040. */
  9041. int64 inMilliseconds() const noexcept;
  9042. /** Returns the number of seconds this time represents.
  9043. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  9044. */
  9045. double inSeconds() const noexcept { return seconds; }
  9046. /** Returns the number of minutes this time represents.
  9047. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  9048. */
  9049. double inMinutes() const noexcept;
  9050. /** Returns the number of hours this time represents.
  9051. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  9052. */
  9053. double inHours() const noexcept;
  9054. /** Returns the number of days this time represents.
  9055. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  9056. */
  9057. double inDays() const noexcept;
  9058. /** Returns the number of weeks this time represents.
  9059. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  9060. */
  9061. double inWeeks() const noexcept;
  9062. /** Returns a readable textual description of the time.
  9063. The exact format of the string returned will depend on
  9064. the magnitude of the time - e.g.
  9065. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  9066. so that only the two most significant units are printed.
  9067. The returnValueForZeroTime value is the result that is returned if the
  9068. length is zero. Depending on your application you might want to use this
  9069. to return something more relevant like "empty" or "0 secs", etc.
  9070. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9071. */
  9072. String getDescription (const String& returnValueForZeroTime = "0") const;
  9073. /** Adds another RelativeTime to this one. */
  9074. const RelativeTime& operator+= (const RelativeTime& timeToAdd) noexcept;
  9075. /** Subtracts another RelativeTime from this one. */
  9076. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) noexcept;
  9077. /** Adds a number of seconds to this time. */
  9078. const RelativeTime& operator+= (double secondsToAdd) noexcept;
  9079. /** Subtracts a number of seconds from this time. */
  9080. const RelativeTime& operator-= (double secondsToSubtract) noexcept;
  9081. private:
  9082. double seconds;
  9083. };
  9084. /** Compares two RelativeTimes. */
  9085. bool operator== (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9086. /** Compares two RelativeTimes. */
  9087. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9088. /** Compares two RelativeTimes. */
  9089. bool operator> (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9090. /** Compares two RelativeTimes. */
  9091. bool operator< (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9092. /** Compares two RelativeTimes. */
  9093. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9094. /** Compares two RelativeTimes. */
  9095. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9096. /** Adds two RelativeTimes together. */
  9097. RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9098. /** Subtracts two RelativeTimes. */
  9099. RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9100. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  9101. /*** End of inlined file: juce_RelativeTime.h ***/
  9102. /**
  9103. Holds an absolute date and time.
  9104. Internally, the time is stored at millisecond precision.
  9105. @see RelativeTime
  9106. */
  9107. class JUCE_API Time
  9108. {
  9109. public:
  9110. /** Creates a Time object.
  9111. This default constructor creates a time of 1st January 1970, (which is
  9112. represented internally as 0ms).
  9113. To create a time object representing the current time, use getCurrentTime().
  9114. @see getCurrentTime
  9115. */
  9116. Time() noexcept;
  9117. /** Creates a time based on a number of milliseconds.
  9118. The internal millisecond count is set to 0 (1st January 1970). To create a
  9119. time object set to the current time, use getCurrentTime().
  9120. @param millisecondsSinceEpoch the number of milliseconds since the unix
  9121. 'epoch' (midnight Jan 1st 1970).
  9122. @see getCurrentTime, currentTimeMillis
  9123. */
  9124. explicit Time (int64 millisecondsSinceEpoch) noexcept;
  9125. /** Creates a time from a set of date components.
  9126. The timezone is assumed to be whatever the system is using as its locale.
  9127. @param year the year, in 4-digit format, e.g. 2004
  9128. @param month the month, in the range 0 to 11
  9129. @param day the day of the month, in the range 1 to 31
  9130. @param hours hours in 24-hour clock format, 0 to 23
  9131. @param minutes minutes 0 to 59
  9132. @param seconds seconds 0 to 59
  9133. @param milliseconds milliseconds 0 to 999
  9134. @param useLocalTime if true, encode using the current machine's local time; if
  9135. false, it will always work in GMT.
  9136. */
  9137. Time (int year,
  9138. int month,
  9139. int day,
  9140. int hours,
  9141. int minutes,
  9142. int seconds = 0,
  9143. int milliseconds = 0,
  9144. bool useLocalTime = true) noexcept;
  9145. /** Creates a copy of another Time object. */
  9146. Time (const Time& other) noexcept;
  9147. /** Destructor. */
  9148. ~Time() noexcept;
  9149. /** Copies this time from another one. */
  9150. Time& operator= (const Time& other) noexcept;
  9151. /** Returns a Time object that is set to the current system time.
  9152. @see currentTimeMillis
  9153. */
  9154. static Time JUCE_CALLTYPE getCurrentTime() noexcept;
  9155. /** Returns the time as a number of milliseconds.
  9156. @returns the number of milliseconds this Time object represents, since
  9157. midnight jan 1st 1970.
  9158. @see getMilliseconds
  9159. */
  9160. int64 toMilliseconds() const noexcept { return millisSinceEpoch; }
  9161. /** Returns the year.
  9162. A 4-digit format is used, e.g. 2004.
  9163. */
  9164. int getYear() const noexcept;
  9165. /** Returns the number of the month.
  9166. The value returned is in the range 0 to 11.
  9167. @see getMonthName
  9168. */
  9169. int getMonth() const noexcept;
  9170. /** Returns the name of the month.
  9171. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9172. it'll return the long form, e.g. "January"
  9173. @see getMonth
  9174. */
  9175. String getMonthName (bool threeLetterVersion) const;
  9176. /** Returns the day of the month.
  9177. The value returned is in the range 1 to 31.
  9178. */
  9179. int getDayOfMonth() const noexcept;
  9180. /** Returns the number of the day of the week.
  9181. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  9182. */
  9183. int getDayOfWeek() const noexcept;
  9184. /** Returns the name of the weekday.
  9185. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9186. false, it'll return the full version, e.g. "Tuesday".
  9187. */
  9188. String getWeekdayName (bool threeLetterVersion) const;
  9189. /** Returns the number of hours since midnight.
  9190. This is in 24-hour clock format, in the range 0 to 23.
  9191. @see getHoursInAmPmFormat, isAfternoon
  9192. */
  9193. int getHours() const noexcept;
  9194. /** Returns true if the time is in the afternoon.
  9195. So it returns true for "PM", false for "AM".
  9196. @see getHoursInAmPmFormat, getHours
  9197. */
  9198. bool isAfternoon() const noexcept;
  9199. /** Returns the hours in 12-hour clock format.
  9200. This will return a value 1 to 12 - use isAfternoon() to find out
  9201. whether this is in the afternoon or morning.
  9202. @see getHours, isAfternoon
  9203. */
  9204. int getHoursInAmPmFormat() const noexcept;
  9205. /** Returns the number of minutes, 0 to 59. */
  9206. int getMinutes() const noexcept;
  9207. /** Returns the number of seconds, 0 to 59. */
  9208. int getSeconds() const noexcept;
  9209. /** Returns the number of milliseconds, 0 to 999.
  9210. Unlike toMilliseconds(), this just returns the position within the
  9211. current second rather than the total number since the epoch.
  9212. @see toMilliseconds
  9213. */
  9214. int getMilliseconds() const noexcept;
  9215. /** Returns true if the local timezone uses a daylight saving correction. */
  9216. bool isDaylightSavingTime() const noexcept;
  9217. /** Returns a 3-character string to indicate the local timezone. */
  9218. String getTimeZone() const noexcept;
  9219. /** Quick way of getting a string version of a date and time.
  9220. For a more powerful way of formatting the date and time, see the formatted() method.
  9221. @param includeDate whether to include the date in the string
  9222. @param includeTime whether to include the time in the string
  9223. @param includeSeconds if the time is being included, this provides an option not to include
  9224. the seconds in it
  9225. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  9226. hour notation.
  9227. @see formatted
  9228. */
  9229. String toString (bool includeDate,
  9230. bool includeTime,
  9231. bool includeSeconds = true,
  9232. bool use24HourClock = false) const noexcept;
  9233. /** Converts this date/time to a string with a user-defined format.
  9234. This uses the C strftime() function to format this time as a string. To save you
  9235. looking it up, these are the escape codes that strftime uses (other codes might
  9236. work on some platforms and not others, but these are the common ones):
  9237. %a is replaced by the locale's abbreviated weekday name.
  9238. %A is replaced by the locale's full weekday name.
  9239. %b is replaced by the locale's abbreviated month name.
  9240. %B is replaced by the locale's full month name.
  9241. %c is replaced by the locale's appropriate date and time representation.
  9242. %d is replaced by the day of the month as a decimal number [01,31].
  9243. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  9244. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  9245. %j is replaced by the day of the year as a decimal number [001,366].
  9246. %m is replaced by the month as a decimal number [01,12].
  9247. %M is replaced by the minute as a decimal number [00,59].
  9248. %p is replaced by the locale's equivalent of either a.m. or p.m.
  9249. %S is replaced by the second as a decimal number [00,61].
  9250. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  9251. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  9252. %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.
  9253. %x is replaced by the locale's appropriate date representation.
  9254. %X is replaced by the locale's appropriate time representation.
  9255. %y is replaced by the year without century as a decimal number [00,99].
  9256. %Y is replaced by the year with century as a decimal number.
  9257. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  9258. %% is replaced by %.
  9259. @see toString
  9260. */
  9261. String formatted (const String& format) const;
  9262. /** Adds a RelativeTime to this time. */
  9263. Time& operator+= (const RelativeTime& delta);
  9264. /** Subtracts a RelativeTime from this time. */
  9265. Time& operator-= (const RelativeTime& delta);
  9266. /** Tries to set the computer's clock.
  9267. @returns true if this succeeds, although depending on the system, the
  9268. application might not have sufficient privileges to do this.
  9269. */
  9270. bool setSystemTimeToThisTime() const;
  9271. /** Returns the name of a day of the week.
  9272. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  9273. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9274. false, it'll return the full version, e.g. "Tuesday".
  9275. */
  9276. static String getWeekdayName (int dayNumber,
  9277. bool threeLetterVersion);
  9278. /** Returns the name of one of the months.
  9279. @param monthNumber the month, 0 to 11
  9280. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9281. it'll return the long form, e.g. "January"
  9282. */
  9283. static String getMonthName (int monthNumber,
  9284. bool threeLetterVersion);
  9285. // Static methods for getting system timers directly..
  9286. /** Returns the current system time.
  9287. Returns the number of milliseconds since midnight jan 1st 1970.
  9288. Should be accurate to within a few millisecs, depending on platform,
  9289. hardware, etc.
  9290. */
  9291. static int64 currentTimeMillis() noexcept;
  9292. /** Returns the number of millisecs since a fixed event (usually system startup).
  9293. This returns a monotonically increasing value which it unaffected by changes to the
  9294. system clock. It should be accurate to within a few millisecs, depending on platform,
  9295. hardware, etc.
  9296. Being a 32-bit return value, it will of course wrap back to 0 after 2^32 seconds of
  9297. uptime, so be careful to take that into account. If you need a 64-bit time, you can
  9298. use currentTimeMillis() instead.
  9299. @see getApproximateMillisecondCounter
  9300. */
  9301. static uint32 getMillisecondCounter() noexcept;
  9302. /** Returns the number of millisecs since a fixed event (usually system startup).
  9303. This has the same function as getMillisecondCounter(), but returns a more accurate
  9304. value, using a higher-resolution timer if one is available.
  9305. @see getMillisecondCounter
  9306. */
  9307. static double getMillisecondCounterHiRes() noexcept;
  9308. /** Waits until the getMillisecondCounter() reaches a given value.
  9309. This will make the thread sleep as efficiently as it can while it's waiting.
  9310. */
  9311. static void waitForMillisecondCounter (uint32 targetTime) noexcept;
  9312. /** Less-accurate but faster version of getMillisecondCounter().
  9313. This will return the last value that getMillisecondCounter() returned, so doesn't
  9314. need to make a system call, but is less accurate - it shouldn't be more than
  9315. 100ms away from the correct time, though, so is still accurate enough for a
  9316. lot of purposes.
  9317. @see getMillisecondCounter
  9318. */
  9319. static uint32 getApproximateMillisecondCounter() noexcept;
  9320. // High-resolution timers..
  9321. /** Returns the current high-resolution counter's tick-count.
  9322. This is a similar idea to getMillisecondCounter(), but with a higher
  9323. resolution.
  9324. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  9325. secondsToHighResolutionTicks
  9326. */
  9327. static int64 getHighResolutionTicks() noexcept;
  9328. /** Returns the resolution of the high-resolution counter in ticks per second.
  9329. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  9330. secondsToHighResolutionTicks
  9331. */
  9332. static int64 getHighResolutionTicksPerSecond() noexcept;
  9333. /** Converts a number of high-resolution ticks into seconds.
  9334. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9335. secondsToHighResolutionTicks
  9336. */
  9337. static double highResolutionTicksToSeconds (int64 ticks) noexcept;
  9338. /** Converts a number seconds into high-resolution ticks.
  9339. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9340. highResolutionTicksToSeconds
  9341. */
  9342. static int64 secondsToHighResolutionTicks (double seconds) noexcept;
  9343. private:
  9344. int64 millisSinceEpoch;
  9345. };
  9346. /** Adds a RelativeTime to a Time. */
  9347. JUCE_API Time operator+ (const Time& time, const RelativeTime& delta);
  9348. /** Adds a RelativeTime to a Time. */
  9349. JUCE_API Time operator+ (const RelativeTime& delta, const Time& time);
  9350. /** Subtracts a RelativeTime from a Time. */
  9351. JUCE_API Time operator- (const Time& time, const RelativeTime& delta);
  9352. /** Returns the relative time difference between two times. */
  9353. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  9354. /** Compares two Time objects. */
  9355. JUCE_API bool operator== (const Time& time1, const Time& time2);
  9356. /** Compares two Time objects. */
  9357. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  9358. /** Compares two Time objects. */
  9359. JUCE_API bool operator< (const Time& time1, const Time& time2);
  9360. /** Compares two Time objects. */
  9361. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  9362. /** Compares two Time objects. */
  9363. JUCE_API bool operator> (const Time& time1, const Time& time2);
  9364. /** Compares two Time objects. */
  9365. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  9366. #endif // __JUCE_TIME_JUCEHEADER__
  9367. /*** End of inlined file: juce_Time.h ***/
  9368. /*** Start of inlined file: juce_MemoryBlock.h ***/
  9369. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  9370. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  9371. /**
  9372. A class to hold a resizable block of raw data.
  9373. */
  9374. class JUCE_API MemoryBlock
  9375. {
  9376. public:
  9377. /** Create an uninitialised block with 0 size. */
  9378. MemoryBlock() noexcept;
  9379. /** Creates a memory block with a given initial size.
  9380. @param initialSize the size of block to create
  9381. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  9382. */
  9383. MemoryBlock (const size_t initialSize,
  9384. bool initialiseToZero = false);
  9385. /** Creates a copy of another memory block. */
  9386. MemoryBlock (const MemoryBlock& other);
  9387. /** Creates a memory block using a copy of a block of data.
  9388. @param dataToInitialiseFrom some data to copy into this block
  9389. @param sizeInBytes how much space to use
  9390. */
  9391. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  9392. /** Destructor. */
  9393. ~MemoryBlock() noexcept;
  9394. /** Copies another memory block onto this one.
  9395. This block will be resized and copied to exactly match the other one.
  9396. */
  9397. MemoryBlock& operator= (const MemoryBlock& other);
  9398. /** Compares two memory blocks.
  9399. @returns true only if the two blocks are the same size and have identical contents.
  9400. */
  9401. bool operator== (const MemoryBlock& other) const noexcept;
  9402. /** Compares two memory blocks.
  9403. @returns true if the two blocks are different sizes or have different contents.
  9404. */
  9405. bool operator!= (const MemoryBlock& other) const noexcept;
  9406. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  9407. */
  9408. bool matches (const void* data, size_t dataSize) const noexcept;
  9409. /** Returns a void pointer to the data.
  9410. Note that the pointer returned will probably become invalid when the
  9411. block is resized.
  9412. */
  9413. void* getData() const noexcept { return data; }
  9414. /** Returns a byte from the memory block.
  9415. This returns a reference, so you can also use it to set a byte.
  9416. */
  9417. template <typename Type>
  9418. char& operator[] (const Type offset) const noexcept { return data [offset]; }
  9419. /** Returns the block's current allocated size, in bytes. */
  9420. size_t getSize() const noexcept { return size; }
  9421. /** Resizes the memory block.
  9422. This will try to keep as much of the block's current content as it can,
  9423. and can optionally be made to clear any new space that gets allocated at
  9424. the end of the block.
  9425. @param newSize the new desired size for the block
  9426. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  9427. whether to clear the new section or just leave it
  9428. uninitialised
  9429. @see ensureSize
  9430. */
  9431. void setSize (const size_t newSize,
  9432. bool initialiseNewSpaceToZero = false);
  9433. /** Increases the block's size only if it's smaller than a given size.
  9434. @param minimumSize if the block is already bigger than this size, no action
  9435. will be taken; otherwise it will be increased to this size
  9436. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  9437. whether to clear the new section or just leave it
  9438. uninitialised
  9439. @see setSize
  9440. */
  9441. void ensureSize (const size_t minimumSize,
  9442. bool initialiseNewSpaceToZero = false);
  9443. /** Fills the entire memory block with a repeated byte value.
  9444. This is handy for clearing a block of memory to zero.
  9445. */
  9446. void fillWith (uint8 valueToUse) noexcept;
  9447. /** Adds another block of data to the end of this one.
  9448. This block's size will be increased accordingly.
  9449. */
  9450. void append (const void* data, size_t numBytes);
  9451. /** Exchanges the contents of this and another memory block.
  9452. No actual copying is required for this, so it's very fast.
  9453. */
  9454. void swapWith (MemoryBlock& other) noexcept;
  9455. /** Copies data into this MemoryBlock from a memory address.
  9456. @param srcData the memory location of the data to copy into this block
  9457. @param destinationOffset the offset in this block at which the data being copied should begin
  9458. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  9459. it will be clipped so not to do anything nasty)
  9460. */
  9461. void copyFrom (const void* srcData,
  9462. int destinationOffset,
  9463. size_t numBytes) noexcept;
  9464. /** Copies data from this MemoryBlock to a memory address.
  9465. @param destData the memory location to write to
  9466. @param sourceOffset the offset within this block from which the copied data will be read
  9467. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  9468. zeros will be used for that portion of the data)
  9469. */
  9470. void copyTo (void* destData,
  9471. int sourceOffset,
  9472. size_t numBytes) const noexcept;
  9473. /** Chops out a section of the block.
  9474. This will remove a section of the memory block and close the gap around it,
  9475. shifting any subsequent data downwards and reducing the size of the block.
  9476. If the range specified goes beyond the size of the block, it will be clipped.
  9477. */
  9478. void removeSection (size_t startByte, size_t numBytesToRemove);
  9479. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  9480. characters in the system's default encoding. */
  9481. const String toString() const;
  9482. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  9483. The block will be resized to the number of valid bytes read from the string.
  9484. Non-hex characters in the string will be ignored.
  9485. @see String::toHexString()
  9486. */
  9487. void loadFromHexString (const String& sourceHexString);
  9488. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  9489. void setBitRange (size_t bitRangeStart,
  9490. size_t numBits,
  9491. int binaryNumberToApply) noexcept;
  9492. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  9493. int getBitRange (size_t bitRangeStart,
  9494. size_t numBitsToRead) const noexcept;
  9495. /** Returns a string of characters that represent the binary contents of this block.
  9496. Uses a 64-bit encoding system to allow binary data to be turned into a string
  9497. of simple non-extended characters, e.g. for storage in XML.
  9498. @see fromBase64Encoding
  9499. */
  9500. const String toBase64Encoding() const;
  9501. /** Takes a string of encoded characters and turns it into binary data.
  9502. The string passed in must have been created by to64BitEncoding(), and this
  9503. block will be resized to recreate the original data block.
  9504. @see toBase64Encoding
  9505. */
  9506. bool fromBase64Encoding (const String& encodedString);
  9507. private:
  9508. HeapBlock <char> data;
  9509. size_t size;
  9510. static const char* const encodingTable;
  9511. JUCE_LEAK_DETECTOR (MemoryBlock);
  9512. };
  9513. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  9514. /*** End of inlined file: juce_MemoryBlock.h ***/
  9515. /*** Start of inlined file: juce_Result.h ***/
  9516. #ifndef __JUCE_RESULT_JUCEHEADER__
  9517. #define __JUCE_RESULT_JUCEHEADER__
  9518. /**
  9519. Represents the 'success' or 'failure' of an operation, and holds an associated
  9520. error message to describe the error when there's a failure.
  9521. E.g.
  9522. @code
  9523. Result myOperation()
  9524. {
  9525. if (doSomeKindOfFoobar())
  9526. return Result::ok();
  9527. else
  9528. return Result::fail ("foobar didn't work!");
  9529. }
  9530. const Result result (myOperation());
  9531. if (result.wasOk())
  9532. {
  9533. ...it's all good...
  9534. }
  9535. else
  9536. {
  9537. warnUserAboutFailure ("The foobar operation failed! Error message was: "
  9538. + result.getErrorMessage());
  9539. }
  9540. @endcode
  9541. */
  9542. class Result
  9543. {
  9544. public:
  9545. /** Creates and returns a 'successful' result. */
  9546. static Result ok() noexcept;
  9547. /** Creates a 'failure' result.
  9548. If you pass a blank error message in here, a default "Unknown Error" message
  9549. will be used instead.
  9550. */
  9551. static Result fail (const String& errorMessage) noexcept;
  9552. /** Returns true if this result indicates a success. */
  9553. bool wasOk() const noexcept;
  9554. /** Returns true if this result indicates a failure.
  9555. You can use getErrorMessage() to retrieve the error message associated
  9556. with the failure.
  9557. */
  9558. bool failed() const noexcept;
  9559. /** Returns true if this result indicates a success.
  9560. This is equivalent to calling wasOk().
  9561. */
  9562. operator bool() const noexcept;
  9563. /** Returns true if this result indicates a failure.
  9564. This is equivalent to calling failed().
  9565. */
  9566. bool operator!() const noexcept;
  9567. /** Returns the error message that was set when this result was created.
  9568. For a successful result, this will be an empty string;
  9569. */
  9570. const String& getErrorMessage() const noexcept;
  9571. Result (const Result& other);
  9572. Result& operator= (const Result& other);
  9573. bool operator== (const Result& other) const noexcept;
  9574. bool operator!= (const Result& other) const noexcept;
  9575. private:
  9576. String errorMessage;
  9577. explicit Result (const String& errorMessage) noexcept;
  9578. // These casts are private to prevent people trying to use the Result object in numeric contexts
  9579. operator int() const;
  9580. operator void*() const;
  9581. };
  9582. #endif // __JUCE_RESULT_JUCEHEADER__
  9583. /*** End of inlined file: juce_Result.h ***/
  9584. class FileInputStream;
  9585. class FileOutputStream;
  9586. /**
  9587. Represents a local file or directory.
  9588. This class encapsulates the absolute pathname of a file or directory, and
  9589. has methods for finding out about the file and changing its properties.
  9590. To read or write to the file, there are methods for returning an input or
  9591. output stream.
  9592. @see FileInputStream, FileOutputStream
  9593. */
  9594. class JUCE_API File
  9595. {
  9596. public:
  9597. /** Creates an (invalid) file object.
  9598. The file is initially set to an empty path, so getFullPath() will return
  9599. an empty string, and comparing the file to File::nonexistent will return
  9600. true.
  9601. You can use its operator= method to point it at a proper file.
  9602. */
  9603. File() {}
  9604. /** Creates a file from an absolute path.
  9605. If the path supplied is a relative path, it is taken to be relative
  9606. to the current working directory (see File::getCurrentWorkingDirectory()),
  9607. but this isn't a recommended way of creating a file, because you
  9608. never know what the CWD is going to be.
  9609. On the Mac/Linux, the path can include "~" notation for referring to
  9610. user home directories.
  9611. */
  9612. File (const String& path);
  9613. /** Creates a copy of another file object. */
  9614. File (const File& other);
  9615. /** Destructor. */
  9616. ~File() {}
  9617. /** Sets the file based on an absolute pathname.
  9618. If the path supplied is a relative path, it is taken to be relative
  9619. to the current working directory (see File::getCurrentWorkingDirectory()),
  9620. but this isn't a recommended way of creating a file, because you
  9621. never know what the CWD is going to be.
  9622. On the Mac/Linux, the path can include "~" notation for referring to
  9623. user home directories.
  9624. */
  9625. File& operator= (const String& newFilePath);
  9626. /** Copies from another file object. */
  9627. File& operator= (const File& otherFile);
  9628. /** This static constant is used for referring to an 'invalid' file. */
  9629. static const File nonexistent;
  9630. /** Checks whether the file actually exists.
  9631. @returns true if the file exists, either as a file or a directory.
  9632. @see existsAsFile, isDirectory
  9633. */
  9634. bool exists() const;
  9635. /** Checks whether the file exists and is a file rather than a directory.
  9636. @returns true only if this is a real file, false if it's a directory
  9637. or doesn't exist
  9638. @see exists, isDirectory
  9639. */
  9640. bool existsAsFile() const;
  9641. /** Checks whether the file is a directory that exists.
  9642. @returns true only if the file is a directory which actually exists, so
  9643. false if it's a file or doesn't exist at all
  9644. @see exists, existsAsFile
  9645. */
  9646. bool isDirectory() const;
  9647. /** Returns the size of the file in bytes.
  9648. @returns the number of bytes in the file, or 0 if it doesn't exist.
  9649. */
  9650. int64 getSize() const;
  9651. /** Utility function to convert a file size in bytes to a neat string description.
  9652. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  9653. 2000000 would produce "2 MB", etc.
  9654. */
  9655. static String descriptionOfSizeInBytes (int64 bytes);
  9656. /** Returns the complete, absolute path of this file.
  9657. This includes the filename and all its parent folders. On Windows it'll
  9658. also include the drive letter prefix; on Mac or Linux it'll be a complete
  9659. path starting from the root folder.
  9660. If you just want the file's name, you should use getFileName() or
  9661. getFileNameWithoutExtension().
  9662. @see getFileName, getRelativePathFrom
  9663. */
  9664. const String& getFullPathName() const noexcept { return fullPath; }
  9665. /** Returns the last section of the pathname.
  9666. Returns just the final part of the path - e.g. if the whole path
  9667. is "/moose/fish/foo.txt" this will return "foo.txt".
  9668. For a directory, it returns the final part of the path - e.g. for the
  9669. directory "/moose/fish" it'll return "fish".
  9670. If the filename begins with a dot, it'll return the whole filename, e.g. for
  9671. "/moose/.fish", it'll return ".fish"
  9672. @see getFullPathName, getFileNameWithoutExtension
  9673. */
  9674. String getFileName() const;
  9675. /** Creates a relative path that refers to a file relatively to a given directory.
  9676. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  9677. would return "../../foo.txt".
  9678. If it's not possible to navigate from one file to the other, an absolute
  9679. path is returned. If the paths are invalid, an empty string may also be
  9680. returned.
  9681. @param directoryToBeRelativeTo the directory which the resultant string will
  9682. be relative to. If this is actually a file rather than
  9683. a directory, its parent directory will be used instead.
  9684. If it doesn't exist, it's assumed to be a directory.
  9685. @see getChildFile, isAbsolutePath
  9686. */
  9687. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  9688. /** Returns the file's extension.
  9689. Returns the file extension of this file, also including the dot.
  9690. e.g. "/moose/fish/foo.txt" would return ".txt"
  9691. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  9692. */
  9693. String getFileExtension() const;
  9694. /** Checks whether the file has a given extension.
  9695. @param extensionToTest the extension to look for - it doesn't matter whether or
  9696. not this string has a dot at the start, so ".wav" and "wav"
  9697. will have the same effect. The comparison used is
  9698. case-insensitve. To compare with multiple extensions, this
  9699. parameter can contain multiple strings, separated by semi-colons -
  9700. so, for example: hasFileExtension (".jpeg;png;gif") would return
  9701. true if the file has any of those three extensions.
  9702. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  9703. */
  9704. bool hasFileExtension (const String& extensionToTest) const;
  9705. /** Returns a version of this file with a different file extension.
  9706. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  9707. @param newExtension the new extension, either with or without a dot at the start (this
  9708. doesn't make any difference). To get remove a file's extension altogether,
  9709. pass an empty string into this function.
  9710. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  9711. */
  9712. File withFileExtension (const String& newExtension) const;
  9713. /** Returns the last part of the filename, without its file extension.
  9714. e.g. for "/moose/fish/foo.txt" this will return "foo".
  9715. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  9716. */
  9717. String getFileNameWithoutExtension() const;
  9718. /** Returns a 32-bit hash-code that identifies this file.
  9719. This is based on the filename. Obviously it's possible, although unlikely, that
  9720. two files will have the same hash-code.
  9721. */
  9722. int hashCode() const;
  9723. /** Returns a 64-bit hash-code that identifies this file.
  9724. This is based on the filename. Obviously it's possible, although unlikely, that
  9725. two files will have the same hash-code.
  9726. */
  9727. int64 hashCode64() const;
  9728. /** Returns a file based on a relative path.
  9729. This will find a child file or directory of the current object.
  9730. e.g.
  9731. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9732. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9733. If the string is actually an absolute path, it will be treated as such, e.g.
  9734. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9735. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9736. */
  9737. File getChildFile (String relativePath) const;
  9738. /** Returns a file which is in the same directory as this one.
  9739. This is equivalent to getParentDirectory().getChildFile (name).
  9740. @see getChildFile, getParentDirectory
  9741. */
  9742. File getSiblingFile (const String& siblingFileName) const;
  9743. /** Returns the directory that contains this file or directory.
  9744. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9745. */
  9746. File getParentDirectory() const;
  9747. /** Checks whether a file is somewhere inside a directory.
  9748. Returns true if this file is somewhere inside a subdirectory of the directory
  9749. that is passed in. Neither file actually has to exist, because the function
  9750. just checks the paths for similarities.
  9751. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9752. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9753. */
  9754. bool isAChildOf (const File& potentialParentDirectory) const;
  9755. /** Chooses a filename relative to this one that doesn't already exist.
  9756. If this file is a directory, this will return a child file of this
  9757. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9758. it finds one that isn't already there.
  9759. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9760. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9761. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9762. @param prefix the string to use for the filename before the number
  9763. @param suffix the string to add to the filename after the number
  9764. @param putNumbersInBrackets if true, this will create filenames in the
  9765. format "prefix(number)suffix", if false, it will leave the
  9766. brackets out.
  9767. */
  9768. File getNonexistentChildFile (const String& prefix,
  9769. const String& suffix,
  9770. bool putNumbersInBrackets = true) const;
  9771. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9772. If this file doesn't exist, this will just return itself, otherwise it
  9773. will return an appropriate sibling that doesn't exist, e.g. if a file
  9774. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9775. @param putNumbersInBrackets whether to add brackets around the numbers that
  9776. get appended to the new filename.
  9777. */
  9778. File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9779. /** Compares the pathnames for two files. */
  9780. bool operator== (const File& otherFile) const;
  9781. /** Compares the pathnames for two files. */
  9782. bool operator!= (const File& otherFile) const;
  9783. /** Compares the pathnames for two files. */
  9784. bool operator< (const File& otherFile) const;
  9785. /** Compares the pathnames for two files. */
  9786. bool operator> (const File& otherFile) const;
  9787. /** Checks whether a file can be created or written to.
  9788. @returns true if it's possible to create and write to this file. If the file
  9789. doesn't already exist, this will check its parent directory to
  9790. see if writing is allowed.
  9791. @see setReadOnly
  9792. */
  9793. bool hasWriteAccess() const;
  9794. /** Changes the write-permission of a file or directory.
  9795. @param shouldBeReadOnly whether to add or remove write-permission
  9796. @param applyRecursively if the file is a directory and this is true, it will
  9797. recurse through all the subfolders changing the permissions
  9798. of all files
  9799. @returns true if it manages to change the file's permissions.
  9800. @see hasWriteAccess
  9801. */
  9802. bool setReadOnly (bool shouldBeReadOnly,
  9803. bool applyRecursively = false) const;
  9804. /** Returns true if this file is a hidden or system file.
  9805. The criteria for deciding whether a file is hidden are platform-dependent.
  9806. */
  9807. bool isHidden() const;
  9808. /** If this file is a link, this returns the file that it points to.
  9809. If this file isn't actually link, it'll just return itself.
  9810. */
  9811. File getLinkedTarget() const;
  9812. /** Returns the last modification time of this file.
  9813. @returns the time, or an invalid time if the file doesn't exist.
  9814. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9815. */
  9816. const Time getLastModificationTime() const;
  9817. /** Returns the last time this file was accessed.
  9818. @returns the time, or an invalid time if the file doesn't exist.
  9819. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9820. */
  9821. const Time getLastAccessTime() const;
  9822. /** Returns the time that this file was created.
  9823. @returns the time, or an invalid time if the file doesn't exist.
  9824. @see getLastModificationTime, getLastAccessTime
  9825. */
  9826. const Time getCreationTime() const;
  9827. /** Changes the modification time for this file.
  9828. @param newTime the time to apply to the file
  9829. @returns true if it manages to change the file's time.
  9830. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9831. */
  9832. bool setLastModificationTime (const Time& newTime) const;
  9833. /** Changes the last-access time for this file.
  9834. @param newTime the time to apply to the file
  9835. @returns true if it manages to change the file's time.
  9836. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9837. */
  9838. bool setLastAccessTime (const Time& newTime) const;
  9839. /** Changes the creation date for this file.
  9840. @param newTime the time to apply to the file
  9841. @returns true if it manages to change the file's time.
  9842. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9843. */
  9844. bool setCreationTime (const Time& newTime) const;
  9845. /** If possible, this will try to create a version string for the given file.
  9846. The OS may be able to look at the file and give a version for it - e.g. with
  9847. executables, bundles, dlls, etc. If no version is available, this will
  9848. return an empty string.
  9849. */
  9850. String getVersion() const;
  9851. /** Creates an empty file if it doesn't already exist.
  9852. If the file that this object refers to doesn't exist, this will create a file
  9853. of zero size.
  9854. If it already exists or is a directory, this method will do nothing.
  9855. @returns true if the file has been created (or if it already existed).
  9856. @see createDirectory
  9857. */
  9858. Result create() const;
  9859. /** Creates a new directory for this filename.
  9860. This will try to create the file as a directory, and fill also create
  9861. any parent directories it needs in order to complete the operation.
  9862. @returns a result to indicate whether the directory was created successfully, or
  9863. an error message if it failed.
  9864. @see create
  9865. */
  9866. Result createDirectory() const;
  9867. /** Deletes a file.
  9868. If this file is actually a directory, it may not be deleted correctly if it
  9869. contains files. See deleteRecursively() as a better way of deleting directories.
  9870. @returns true if the file has been successfully deleted (or if it didn't exist to
  9871. begin with).
  9872. @see deleteRecursively
  9873. */
  9874. bool deleteFile() const;
  9875. /** Deletes a file or directory and all its subdirectories.
  9876. If this file is a directory, this will try to delete it and all its subfolders. If
  9877. it's just a file, it will just try to delete the file.
  9878. @returns true if the file and all its subfolders have been successfully deleted
  9879. (or if it didn't exist to begin with).
  9880. @see deleteFile
  9881. */
  9882. bool deleteRecursively() const;
  9883. /** Moves this file or folder to the trash.
  9884. @returns true if the operation succeeded. It could fail if the trash is full, or
  9885. if the file is write-protected, so you should check the return value
  9886. and act appropriately.
  9887. */
  9888. bool moveToTrash() const;
  9889. /** Moves or renames a file.
  9890. Tries to move a file to a different location.
  9891. If the target file already exists, this will attempt to delete it first, and
  9892. will fail if this can't be done.
  9893. Note that the destination file isn't the directory to put it in, it's the actual
  9894. filename that you want the new file to have.
  9895. @returns true if the operation succeeds
  9896. */
  9897. bool moveFileTo (const File& targetLocation) const;
  9898. /** Copies a file.
  9899. Tries to copy a file to a different location.
  9900. If the target file already exists, this will attempt to delete it first, and
  9901. will fail if this can't be done.
  9902. @returns true if the operation succeeds
  9903. */
  9904. bool copyFileTo (const File& targetLocation) const;
  9905. /** Copies a directory.
  9906. Tries to copy an entire directory, recursively.
  9907. If this file isn't a directory or if any target files can't be created, this
  9908. will return false.
  9909. @param newDirectory the directory that this one should be copied to. Note that this
  9910. is the name of the actual directory to create, not the directory
  9911. into which the new one should be placed, so there must be enough
  9912. write privileges to create it if it doesn't exist. Any files inside
  9913. it will be overwritten by similarly named ones that are copied.
  9914. */
  9915. bool copyDirectoryTo (const File& newDirectory) const;
  9916. /** Used in file searching, to specify whether to return files, directories, or both.
  9917. */
  9918. enum TypesOfFileToFind
  9919. {
  9920. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9921. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9922. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9923. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9924. };
  9925. /** Searches inside a directory for files matching a wildcard pattern.
  9926. Assuming that this file is a directory, this method will search it
  9927. for either files or subdirectories whose names match a filename pattern.
  9928. @param results an array to which File objects will be added for the
  9929. files that the search comes up with
  9930. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9931. return files, directories, or both. If the ignoreHiddenFiles flag
  9932. is also added to this value, hidden files won't be returned
  9933. @param searchRecursively if true, all subdirectories will be recursed into to do
  9934. an exhaustive search
  9935. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9936. @returns the number of results that have been found
  9937. @see getNumberOfChildFiles, DirectoryIterator
  9938. */
  9939. int findChildFiles (Array<File>& results,
  9940. int whatToLookFor,
  9941. bool searchRecursively,
  9942. const String& wildCardPattern = "*") const;
  9943. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9944. Assuming that this file is a directory, this method will search it
  9945. for either files or subdirectories whose names match a filename pattern,
  9946. and will return the number of matches found.
  9947. This isn't a recursive call, and will only search this directory, not
  9948. its children.
  9949. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9950. count files, directories, or both. If the ignoreHiddenFiles flag
  9951. is also added to this value, hidden files won't be counted
  9952. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9953. @returns the number of matches found
  9954. @see findChildFiles, DirectoryIterator
  9955. */
  9956. int getNumberOfChildFiles (int whatToLookFor,
  9957. const String& wildCardPattern = "*") const;
  9958. /** Returns true if this file is a directory that contains one or more subdirectories.
  9959. @see isDirectory, findChildFiles
  9960. */
  9961. bool containsSubDirectories() const;
  9962. /** Creates a stream to read from this file.
  9963. @returns a stream that will read from this file (initially positioned at the
  9964. start of the file), or 0 if the file can't be opened for some reason
  9965. @see createOutputStream, loadFileAsData
  9966. */
  9967. FileInputStream* createInputStream() const;
  9968. /** Creates a stream to write to this file.
  9969. If the file exists, the stream that is returned will be positioned ready for
  9970. writing at the end of the file, so you might want to use deleteFile() first
  9971. to write to an empty file.
  9972. @returns a stream that will write to this file (initially positioned at the
  9973. end of the file), or 0 if the file can't be opened for some reason
  9974. @see createInputStream, appendData, appendText
  9975. */
  9976. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9977. /** Loads a file's contents into memory as a block of binary data.
  9978. Of course, trying to load a very large file into memory will blow up, so
  9979. it's better to check first.
  9980. @param result the data block to which the file's contents should be appended - note
  9981. that if the memory block might already contain some data, you
  9982. might want to clear it first
  9983. @returns true if the file could all be read into memory
  9984. */
  9985. bool loadFileAsData (MemoryBlock& result) const;
  9986. /** Reads a file into memory as a string.
  9987. Attempts to load the entire file as a zero-terminated string.
  9988. This makes use of InputStream::readEntireStreamAsString, which should
  9989. automatically cope with unicode/acsii file formats.
  9990. */
  9991. String loadFileAsString() const;
  9992. /** Appends a block of binary data to the end of the file.
  9993. This will try to write the given buffer to the end of the file.
  9994. @returns false if it can't write to the file for some reason
  9995. */
  9996. bool appendData (const void* dataToAppend,
  9997. int numberOfBytes) const;
  9998. /** Replaces this file's contents with a given block of data.
  9999. This will delete the file and replace it with the given data.
  10000. A nice feature of this method is that it's safe - instead of deleting
  10001. the file first and then re-writing it, it creates a new temporary file,
  10002. writes the data to that, and then moves the new file to replace the existing
  10003. file. This means that if the power gets pulled out or something crashes,
  10004. you're a lot less likely to end up with a corrupted or unfinished file..
  10005. Returns true if the operation succeeds, or false if it fails.
  10006. @see appendText
  10007. */
  10008. bool replaceWithData (const void* dataToWrite,
  10009. int numberOfBytes) const;
  10010. /** Appends a string to the end of the file.
  10011. This will try to append a text string to the file, as either 16-bit unicode
  10012. or 8-bit characters in the default system encoding.
  10013. It can also write the 'ff fe' unicode header bytes before the text to indicate
  10014. the endianness of the file.
  10015. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  10016. @see replaceWithText
  10017. */
  10018. bool appendText (const String& textToAppend,
  10019. bool asUnicode = false,
  10020. bool writeUnicodeHeaderBytes = false) const;
  10021. /** Replaces this file's contents with a given text string.
  10022. This will delete the file and replace it with the given text.
  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 text 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 an empty file..
  10028. For an explanation of the parameters here, see the appendText() method.
  10029. Returns true if the operation succeeds, or false if it fails.
  10030. @see appendText
  10031. */
  10032. bool replaceWithText (const String& textToWrite,
  10033. bool asUnicode = false,
  10034. bool writeUnicodeHeaderBytes = false) const;
  10035. /** Attempts to scan the contents of this file and compare it to another file, returning
  10036. true if this is possible and they match byte-for-byte.
  10037. */
  10038. bool hasIdenticalContentTo (const File& other) const;
  10039. /** Creates a set of files to represent each file root.
  10040. e.g. on Windows this will create files for "c:\", "d:\" etc according
  10041. to which ones are available. On the Mac/Linux, this will probably
  10042. just add a single entry for "/".
  10043. */
  10044. static void findFileSystemRoots (Array<File>& results);
  10045. /** Finds the name of the drive on which this file lives.
  10046. @returns the volume label of the drive, or an empty string if this isn't possible
  10047. */
  10048. String getVolumeLabel() const;
  10049. /** Returns the serial number of the volume on which this file lives.
  10050. @returns the serial number, or zero if there's a problem doing this
  10051. */
  10052. int getVolumeSerialNumber() const;
  10053. /** Returns the number of bytes free on the drive that this file lives on.
  10054. @returns the number of bytes free, or 0 if there's a problem finding this out
  10055. @see getVolumeTotalSize
  10056. */
  10057. int64 getBytesFreeOnVolume() const;
  10058. /** Returns the total size of the drive that contains this file.
  10059. @returns the total number of bytes that the volume can hold
  10060. @see getBytesFreeOnVolume
  10061. */
  10062. int64 getVolumeTotalSize() const;
  10063. /** Returns true if this file is on a CD or DVD drive. */
  10064. bool isOnCDRomDrive() const;
  10065. /** Returns true if this file is on a hard disk.
  10066. This will fail if it's a network drive, but will still be true for
  10067. removable hard-disks.
  10068. */
  10069. bool isOnHardDisk() const;
  10070. /** Returns true if this file is on a removable disk drive.
  10071. This might be a usb-drive, a CD-rom, or maybe a network drive.
  10072. */
  10073. bool isOnRemovableDrive() const;
  10074. /** Launches the file as a process.
  10075. - if the file is executable, this will run it.
  10076. - if it's a document of some kind, it will launch the document with its
  10077. default viewer application.
  10078. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  10079. @see revealToUser
  10080. */
  10081. bool startAsProcess (const String& parameters = String::empty) const;
  10082. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  10083. @see startAsProcess
  10084. */
  10085. void revealToUser() const;
  10086. /** A set of types of location that can be passed to the getSpecialLocation() method.
  10087. */
  10088. enum SpecialLocationType
  10089. {
  10090. /** The user's home folder. This is the same as using File ("~"). */
  10091. userHomeDirectory,
  10092. /** The user's default documents folder. On Windows, this might be the user's
  10093. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  10094. doesn't tend to have one of these, so it might just return their home folder.
  10095. */
  10096. userDocumentsDirectory,
  10097. /** The folder that contains the user's desktop objects. */
  10098. userDesktopDirectory,
  10099. /** The folder in which applications store their persistent user-specific settings.
  10100. On Windows, this might be "\Documents and Settings\username\Application Data".
  10101. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  10102. always create your own sub-folder to put them in, to avoid making a mess.
  10103. */
  10104. userApplicationDataDirectory,
  10105. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  10106. of the computer, rather than just the current user.
  10107. On the Mac it'll be "/Library", on Windows, it could be something like
  10108. "\Documents and Settings\All Users\Application Data".
  10109. Depending on the setup, this folder may be read-only.
  10110. */
  10111. commonApplicationDataDirectory,
  10112. /** The folder that should be used for temporary files.
  10113. Always delete them when you're finished, to keep the user's computer tidy!
  10114. */
  10115. tempDirectory,
  10116. /** Returns this application's executable file.
  10117. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10118. host app.
  10119. On the mac this will return the unix binary, not the package folder - see
  10120. currentApplicationFile for that.
  10121. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  10122. file link, invokedExecutableFile will return the name of the link.
  10123. */
  10124. currentExecutableFile,
  10125. /** Returns this application's location.
  10126. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10127. host app.
  10128. On the mac this will return the package folder (if it's in one), not the unix binary
  10129. that's inside it - compare with currentExecutableFile.
  10130. */
  10131. currentApplicationFile,
  10132. /** Returns the file that was invoked to launch this executable.
  10133. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  10134. will return the name of the link that was used, whereas currentExecutableFile will return
  10135. the actual location of the target executable.
  10136. */
  10137. invokedExecutableFile,
  10138. /** In a plugin, this will return the path of the host executable. */
  10139. hostApplicationPath,
  10140. /** The directory in which applications normally get installed.
  10141. So on windows, this would be something like "c:\program files", on the
  10142. Mac "/Applications", or "/usr" on linux.
  10143. */
  10144. globalApplicationsDirectory,
  10145. /** The most likely place where a user might store their music files.
  10146. */
  10147. userMusicDirectory,
  10148. /** The most likely place where a user might store their movie files.
  10149. */
  10150. userMoviesDirectory,
  10151. };
  10152. /** Finds the location of a special type of file or directory, such as a home folder or
  10153. documents folder.
  10154. @see SpecialLocationType
  10155. */
  10156. static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  10157. /** Returns a temporary file in the system's temp directory.
  10158. This will try to return the name of a non-existent temp file.
  10159. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  10160. */
  10161. static File createTempFile (const String& fileNameEnding);
  10162. /** Returns the current working directory.
  10163. @see setAsCurrentWorkingDirectory
  10164. */
  10165. static File getCurrentWorkingDirectory();
  10166. /** Sets the current working directory to be this file.
  10167. For this to work the file must point to a valid directory.
  10168. @returns true if the current directory has been changed.
  10169. @see getCurrentWorkingDirectory
  10170. */
  10171. bool setAsCurrentWorkingDirectory() const;
  10172. /** The system-specific file separator character.
  10173. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10174. */
  10175. static const juce_wchar separator;
  10176. /** The system-specific file separator character, as a string.
  10177. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10178. */
  10179. static const String separatorString;
  10180. /** Removes illegal characters from a filename.
  10181. This will return a copy of the given string after removing characters
  10182. that are not allowed in a legal filename, and possibly shortening the
  10183. string if it's too long.
  10184. Because this will remove slashes, don't use it on an absolute pathname.
  10185. @see createLegalPathName
  10186. */
  10187. static String createLegalFileName (const String& fileNameToFix);
  10188. /** Removes illegal characters from a pathname.
  10189. Similar to createLegalFileName(), but this won't remove slashes, so can
  10190. be used on a complete pathname.
  10191. @see createLegalFileName
  10192. */
  10193. static String createLegalPathName (const String& pathNameToFix);
  10194. /** Indicates whether filenames are case-sensitive on the current operating system.
  10195. */
  10196. static bool areFileNamesCaseSensitive();
  10197. /** Returns true if the string seems to be a fully-specified absolute path.
  10198. */
  10199. static bool isAbsolutePath (const String& path);
  10200. /** Creates a file that simply contains this string, without doing the sanity-checking
  10201. that the normal constructors do.
  10202. Best to avoid this unless you really know what you're doing.
  10203. */
  10204. static File createFileWithoutCheckingPath (const String& path);
  10205. /** Adds a separator character to the end of a path if it doesn't already have one. */
  10206. static String addTrailingSeparator (const String& path);
  10207. private:
  10208. String fullPath;
  10209. // internal way of contructing a file without checking the path
  10210. friend class DirectoryIterator;
  10211. File (const String&, int);
  10212. String getPathUpToLastSlash() const;
  10213. Result createDirectoryInternal (const String& fileName) const;
  10214. bool copyInternal (const File& dest) const;
  10215. bool moveInternal (const File& dest) const;
  10216. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  10217. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  10218. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  10219. static String parseAbsolutePath (const String& path);
  10220. JUCE_LEAK_DETECTOR (File);
  10221. };
  10222. #endif // __JUCE_FILE_JUCEHEADER__
  10223. /*** End of inlined file: juce_File.h ***/
  10224. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  10225. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10226. will be the name of a pointer to each child element.
  10227. E.g. @code
  10228. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10229. forEachXmlChildElement (*myParentXml, child)
  10230. {
  10231. if (child->hasTagName ("FOO"))
  10232. doSomethingWithXmlElement (child);
  10233. }
  10234. @endcode
  10235. @see forEachXmlChildElementWithTagName
  10236. */
  10237. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  10238. \
  10239. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  10240. childElementVariableName != 0; \
  10241. childElementVariableName = childElementVariableName->getNextElement())
  10242. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  10243. which have a specified tag.
  10244. This does the same job as the forEachXmlChildElement macro, but only for those
  10245. elements that have a particular tag name.
  10246. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10247. will be the name of a pointer to each child element. The requiredTagName is the
  10248. tag name to match.
  10249. E.g. @code
  10250. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10251. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  10252. {
  10253. // the child object is now guaranteed to be a <MYTAG> element..
  10254. doSomethingWithMYTAGElement (child);
  10255. }
  10256. @endcode
  10257. @see forEachXmlChildElement
  10258. */
  10259. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  10260. \
  10261. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  10262. childElementVariableName != 0; \
  10263. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  10264. /** Used to build a tree of elements representing an XML document.
  10265. An XML document can be parsed into a tree of XmlElements, each of which
  10266. represents an XML tag structure, and which may itself contain other
  10267. nested elements.
  10268. An XmlElement can also be converted back into a text document, and has
  10269. lots of useful methods for manipulating its attributes and sub-elements,
  10270. so XmlElements can actually be used as a handy general-purpose data
  10271. structure.
  10272. Here's an example of parsing some elements: @code
  10273. // check we're looking at the right kind of document..
  10274. if (myElement->hasTagName ("ANIMALS"))
  10275. {
  10276. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  10277. forEachXmlChildElement (*myElement, e)
  10278. {
  10279. if (e->hasTagName ("GIRAFFE"))
  10280. {
  10281. // found a giraffe, so use some of its attributes..
  10282. String giraffeName = e->getStringAttribute ("name");
  10283. int giraffeAge = e->getIntAttribute ("age");
  10284. bool isFriendly = e->getBoolAttribute ("friendly");
  10285. }
  10286. }
  10287. }
  10288. @endcode
  10289. And here's an example of how to create an XML document from scratch: @code
  10290. // create an outer node called "ANIMALS"
  10291. XmlElement animalsList ("ANIMALS");
  10292. for (int i = 0; i < numAnimals; ++i)
  10293. {
  10294. // create an inner element..
  10295. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  10296. giraffe->setAttribute ("name", "nigel");
  10297. giraffe->setAttribute ("age", 10);
  10298. giraffe->setAttribute ("friendly", true);
  10299. // ..and add our new element to the parent node
  10300. animalsList.addChildElement (giraffe);
  10301. }
  10302. // now we can turn the whole thing into a text document..
  10303. String myXmlDoc = animalsList.createDocument (String::empty);
  10304. @endcode
  10305. @see XmlDocument
  10306. */
  10307. class JUCE_API XmlElement
  10308. {
  10309. public:
  10310. /** Creates an XmlElement with this tag name. */
  10311. explicit XmlElement (const String& tagName) noexcept;
  10312. /** Creates a (deep) copy of another element. */
  10313. XmlElement (const XmlElement& other);
  10314. /** Creates a (deep) copy of another element. */
  10315. XmlElement& operator= (const XmlElement& other);
  10316. /** Deleting an XmlElement will also delete all its child elements. */
  10317. ~XmlElement() noexcept;
  10318. /** Compares two XmlElements to see if they contain the same text and attiributes.
  10319. The elements are only considered equivalent if they contain the same attiributes
  10320. with the same values, and have the same sub-nodes.
  10321. @param other the other element to compare to
  10322. @param ignoreOrderOfAttributes if true, this means that two elements with the
  10323. same attributes in a different order will be
  10324. considered the same; if false, the attributes must
  10325. be in the same order as well
  10326. */
  10327. bool isEquivalentTo (const XmlElement* other,
  10328. bool ignoreOrderOfAttributes) const noexcept;
  10329. /** Returns an XML text document that represents this element.
  10330. The string returned can be parsed to recreate the same XmlElement that
  10331. was used to create it.
  10332. @param dtdToUse the DTD to add to the document
  10333. @param allOnOneLine if true, this means that the document will not contain any
  10334. linefeeds, so it'll be smaller but not very easy to read.
  10335. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10336. document
  10337. @param encodingType the character encoding format string to put into the xml
  10338. header
  10339. @param lineWrapLength the line length that will be used before items get placed on
  10340. a new line. This isn't an absolute maximum length, it just
  10341. determines how lists of attributes get broken up
  10342. @see writeToStream, writeToFile
  10343. */
  10344. String createDocument (const String& dtdToUse,
  10345. bool allOnOneLine = false,
  10346. bool includeXmlHeader = true,
  10347. const String& encodingType = "UTF-8",
  10348. int lineWrapLength = 60) const;
  10349. /** Writes the document to a stream as UTF-8.
  10350. @param output the stream to write to
  10351. @param dtdToUse the DTD to add to the document
  10352. @param allOnOneLine if true, this means that the document will not contain any
  10353. linefeeds, so it'll be smaller but not very easy to read.
  10354. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10355. document
  10356. @param encodingType the character encoding format string to put into the xml
  10357. header
  10358. @param lineWrapLength the line length that will be used before items get placed on
  10359. a new line. This isn't an absolute maximum length, it just
  10360. determines how lists of attributes get broken up
  10361. @see writeToFile, createDocument
  10362. */
  10363. void writeToStream (OutputStream& output,
  10364. const String& dtdToUse,
  10365. bool allOnOneLine = false,
  10366. bool includeXmlHeader = true,
  10367. const String& encodingType = "UTF-8",
  10368. int lineWrapLength = 60) const;
  10369. /** Writes the element to a file as an XML document.
  10370. To improve safety in case something goes wrong while writing the file, this
  10371. will actually write the document to a new temporary file in the same
  10372. directory as the destination file, and if this succeeds, it will rename this
  10373. new file as the destination file (overwriting any existing file that was there).
  10374. @param destinationFile the file to write to. If this already exists, it will be
  10375. overwritten.
  10376. @param dtdToUse the DTD to add to the document
  10377. @param encodingType the character encoding format string to put into the xml
  10378. header
  10379. @param lineWrapLength the line length that will be used before items get placed on
  10380. a new line. This isn't an absolute maximum length, it just
  10381. determines how lists of attributes get broken up
  10382. @returns true if the file is written successfully; false if something goes wrong
  10383. in the process
  10384. @see createDocument
  10385. */
  10386. bool writeToFile (const File& destinationFile,
  10387. const String& dtdToUse,
  10388. const String& encodingType = "UTF-8",
  10389. int lineWrapLength = 60) const;
  10390. /** Returns this element's tag type name.
  10391. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  10392. "MOOSE".
  10393. @see hasTagName
  10394. */
  10395. inline const String& getTagName() const noexcept { return tagName; }
  10396. /** Tests whether this element has a particular tag name.
  10397. @param possibleTagName the tag name you're comparing it with
  10398. @see getTagName
  10399. */
  10400. bool hasTagName (const String& possibleTagName) const noexcept;
  10401. /** Returns the number of XML attributes this element contains.
  10402. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  10403. return 2.
  10404. */
  10405. int getNumAttributes() const noexcept;
  10406. /** Returns the name of one of the elements attributes.
  10407. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10408. getAttributeName(1) would return "antlers".
  10409. @see getAttributeValue, getStringAttribute
  10410. */
  10411. const String& getAttributeName (int attributeIndex) const noexcept;
  10412. /** Returns the value of one of the elements attributes.
  10413. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10414. getAttributeName(1) would return "2".
  10415. @see getAttributeName, getStringAttribute
  10416. */
  10417. const String& getAttributeValue (int attributeIndex) const noexcept;
  10418. // Attribute-handling methods..
  10419. /** Checks whether the element contains an attribute with a certain name. */
  10420. bool hasAttribute (const String& attributeName) const noexcept;
  10421. /** Returns the value of a named attribute.
  10422. @param attributeName the name of the attribute to look up
  10423. */
  10424. const String& getStringAttribute (const String& attributeName) const noexcept;
  10425. /** Returns the value of a named attribute.
  10426. @param attributeName the name of the attribute to look up
  10427. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10428. with this name
  10429. */
  10430. String getStringAttribute (const String& attributeName,
  10431. const String& defaultReturnValue) const;
  10432. /** Compares the value of a named attribute with a value passed-in.
  10433. @param attributeName the name of the attribute to look up
  10434. @param stringToCompareAgainst the value to compare it with
  10435. @param ignoreCase whether the comparison should be case-insensitive
  10436. @returns true if the value of the attribute is the same as the string passed-in;
  10437. false if it's different (or if no such attribute exists)
  10438. */
  10439. bool compareAttribute (const String& attributeName,
  10440. const String& stringToCompareAgainst,
  10441. bool ignoreCase = false) const noexcept;
  10442. /** Returns the value of a named attribute as an integer.
  10443. This will try to find the attribute and convert it to an integer (using
  10444. the String::getIntValue() method).
  10445. @param attributeName the name of the attribute to look up
  10446. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10447. with this name
  10448. @see setAttribute
  10449. */
  10450. int getIntAttribute (const String& attributeName,
  10451. int defaultReturnValue = 0) const;
  10452. /** Returns the value of a named attribute as floating-point.
  10453. This will try to find the attribute and convert it to an integer (using
  10454. the String::getDoubleValue() method).
  10455. @param attributeName the name of the attribute to look up
  10456. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10457. with this name
  10458. @see setAttribute
  10459. */
  10460. double getDoubleAttribute (const String& attributeName,
  10461. double defaultReturnValue = 0.0) const;
  10462. /** Returns the value of a named attribute as a boolean.
  10463. This will try to find the attribute and interpret it as a boolean. To do this,
  10464. it'll return true if the value is "1", "true", "y", etc, or false for other
  10465. values.
  10466. @param attributeName the name of the attribute to look up
  10467. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10468. with this name
  10469. */
  10470. bool getBoolAttribute (const String& attributeName,
  10471. bool defaultReturnValue = false) const;
  10472. /** Adds a named attribute to the element.
  10473. If the element already contains an attribute with this name, it's value will
  10474. be updated to the new value. If there's no such attribute yet, a new one will
  10475. be added.
  10476. Note that there are other setAttribute() methods that take integers,
  10477. doubles, etc. to make it easy to store numbers.
  10478. @param attributeName the name of the attribute to set
  10479. @param newValue the value to set it to
  10480. @see removeAttribute
  10481. */
  10482. void setAttribute (const String& attributeName,
  10483. const String& newValue);
  10484. /** Adds a named attribute to the element, setting it to an integer value.
  10485. If the element already contains an attribute with this name, it's value will
  10486. be updated to the new value. If there's no such attribute yet, a new one will
  10487. be added.
  10488. Note that there are other setAttribute() methods that take integers,
  10489. doubles, etc. to make it easy to store numbers.
  10490. @param attributeName the name of the attribute to set
  10491. @param newValue the value to set it to
  10492. */
  10493. void setAttribute (const String& attributeName,
  10494. int newValue);
  10495. /** Adds a named attribute to the element, setting it to a floating-point value.
  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. */
  10504. void setAttribute (const String& attributeName,
  10505. double newValue);
  10506. /** Removes a named attribute from the element.
  10507. @param attributeName the name of the attribute to remove
  10508. @see removeAllAttributes
  10509. */
  10510. void removeAttribute (const String& attributeName) noexcept;
  10511. /** Removes all attributes from this element.
  10512. */
  10513. void removeAllAttributes() noexcept;
  10514. // Child element methods..
  10515. /** Returns the first of this element's sub-elements.
  10516. see getNextElement() for an example of how to iterate the sub-elements.
  10517. @see forEachXmlChildElement
  10518. */
  10519. XmlElement* getFirstChildElement() const noexcept { return firstChildElement; }
  10520. /** Returns the next of this element's siblings.
  10521. This can be used for iterating an element's sub-elements, e.g.
  10522. @code
  10523. XmlElement* child = myXmlDocument->getFirstChildElement();
  10524. while (child != nullptr)
  10525. {
  10526. ...do stuff with this child..
  10527. child = child->getNextElement();
  10528. }
  10529. @endcode
  10530. Note that when iterating the child elements, some of them might be
  10531. text elements as well as XML tags - use isTextElement() to work this
  10532. out.
  10533. Also, it's much easier and neater to use this method indirectly via the
  10534. forEachXmlChildElement macro.
  10535. @returns the sibling element that follows this one, or zero if this is the last
  10536. element in its parent
  10537. @see getNextElement, isTextElement, forEachXmlChildElement
  10538. */
  10539. inline XmlElement* getNextElement() const noexcept { return nextListItem; }
  10540. /** Returns the next of this element's siblings which has the specified tag
  10541. name.
  10542. This is like getNextElement(), but will scan through the list until it
  10543. finds an element with the given tag name.
  10544. @see getNextElement, forEachXmlChildElementWithTagName
  10545. */
  10546. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  10547. /** Returns the number of sub-elements in this element.
  10548. @see getChildElement
  10549. */
  10550. int getNumChildElements() const noexcept;
  10551. /** Returns the sub-element at a certain index.
  10552. It's not very efficient to iterate the sub-elements by index - see
  10553. getNextElement() for an example of how best to iterate.
  10554. @returns the n'th child of this element, or 0 if the index is out-of-range
  10555. @see getNextElement, isTextElement, getChildByName
  10556. */
  10557. XmlElement* getChildElement (int index) const noexcept;
  10558. /** Returns the first sub-element with a given tag-name.
  10559. @param tagNameToLookFor the tag name of the element you want to find
  10560. @returns the first element with this tag name, or 0 if none is found
  10561. @see getNextElement, isTextElement, getChildElement
  10562. */
  10563. XmlElement* getChildByName (const String& tagNameToLookFor) const noexcept;
  10564. /** Appends an element to this element's list of children.
  10565. Child elements are deleted automatically when their parent is deleted, so
  10566. make sure the object that you pass in will not be deleted by anything else,
  10567. and make sure it's not already the child of another element.
  10568. @see getFirstChildElement, getNextElement, getNumChildElements,
  10569. getChildElement, removeChildElement
  10570. */
  10571. void addChildElement (XmlElement* newChildElement) noexcept;
  10572. /** Inserts an element into this element's list of children.
  10573. Child elements are deleted automatically when their parent is deleted, so
  10574. make sure the object that you pass in will not be deleted by anything else,
  10575. and make sure it's not already the child of another element.
  10576. @param newChildNode the element to add
  10577. @param indexToInsertAt the index at which to insert the new element - if this is
  10578. below zero, it will be added to the end of the list
  10579. @see addChildElement, insertChildElement
  10580. */
  10581. void insertChildElement (XmlElement* newChildNode,
  10582. int indexToInsertAt) noexcept;
  10583. /** Creates a new element with the given name and returns it, after adding it
  10584. as a child element.
  10585. This is a handy method that means that instead of writing this:
  10586. @code
  10587. XmlElement* newElement = new XmlElement ("foobar");
  10588. myParentElement->addChildElement (newElement);
  10589. @endcode
  10590. ..you could just write this:
  10591. @code
  10592. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  10593. @endcode
  10594. */
  10595. XmlElement* createNewChildElement (const String& tagName);
  10596. /** Replaces one of this element's children with another node.
  10597. If the current element passed-in isn't actually a child of this element,
  10598. this will return false and the new one won't be added. Otherwise, the
  10599. existing element will be deleted, replaced with the new one, and it
  10600. will return true.
  10601. */
  10602. bool replaceChildElement (XmlElement* currentChildElement,
  10603. XmlElement* newChildNode) noexcept;
  10604. /** Removes a child element.
  10605. @param childToRemove the child to look for and remove
  10606. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  10607. just remove it
  10608. */
  10609. void removeChildElement (XmlElement* childToRemove,
  10610. bool shouldDeleteTheChild) noexcept;
  10611. /** Deletes all the child elements in the element.
  10612. @see removeChildElement, deleteAllChildElementsWithTagName
  10613. */
  10614. void deleteAllChildElements() noexcept;
  10615. /** Deletes all the child elements with a given tag name.
  10616. @see removeChildElement
  10617. */
  10618. void deleteAllChildElementsWithTagName (const String& tagName) noexcept;
  10619. /** Returns true if the given element is a child of this one. */
  10620. bool containsChildElement (const XmlElement* possibleChild) const noexcept;
  10621. /** Recursively searches all sub-elements to find one that contains the specified
  10622. child element.
  10623. */
  10624. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) noexcept;
  10625. /** Sorts the child elements using a comparator.
  10626. This will use a comparator object to sort the elements into order. The object
  10627. passed must have a method of the form:
  10628. @code
  10629. int compareElements (const XmlElement* first, const XmlElement* second);
  10630. @endcode
  10631. ..and this method must return:
  10632. - a value of < 0 if the first comes before the second
  10633. - a value of 0 if the two objects are equivalent
  10634. - a value of > 0 if the second comes before the first
  10635. To improve performance, the compareElements() method can be declared as static or const.
  10636. @param comparator the comparator to use for comparing elements.
  10637. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  10638. says are equivalent will be kept in the order in which they
  10639. currently appear in the array. This is slower to perform, but
  10640. may be important in some cases. If it's false, a faster algorithm
  10641. is used, but equivalent elements may be rearranged.
  10642. */
  10643. template <class ElementComparator>
  10644. void sortChildElements (ElementComparator& comparator,
  10645. bool retainOrderOfEquivalentItems = false)
  10646. {
  10647. const int num = getNumChildElements();
  10648. if (num > 1)
  10649. {
  10650. HeapBlock <XmlElement*> elems (num);
  10651. getChildElementsAsArray (elems);
  10652. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  10653. reorderChildElements (elems, num);
  10654. }
  10655. }
  10656. /** Returns true if this element is a section of text.
  10657. Elements can either be an XML tag element or a secton of text, so this
  10658. is used to find out what kind of element this one is.
  10659. @see getAllText, addTextElement, deleteAllTextElements
  10660. */
  10661. bool isTextElement() const noexcept;
  10662. /** Returns the text for a text element.
  10663. Note that if you have an element like this:
  10664. @code<xyz>hello</xyz>@endcode
  10665. then calling getText on the "xyz" element won't return "hello", because that is
  10666. actually stored in a special text sub-element inside the xyz element. To get the
  10667. "hello" string, you could either call getText on the (unnamed) sub-element, or
  10668. use getAllSubText() to do this automatically.
  10669. Note that leading and trailing whitespace will be included in the string - to remove
  10670. if, just call String::trim() on the result.
  10671. @see isTextElement, getAllSubText, getChildElementAllSubText
  10672. */
  10673. const String& getText() const noexcept;
  10674. /** Sets the text in a text element.
  10675. Note that this is only a valid call if this element is a text element. If it's
  10676. not, then no action will be performed. If you're trying to add text inside a normal
  10677. element, you probably want to use addTextElement() instead.
  10678. */
  10679. void setText (const String& newText);
  10680. /** Returns all the text from this element's child nodes.
  10681. This iterates all the child elements and when it finds text elements,
  10682. it concatenates their text into a big string which it returns.
  10683. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  10684. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  10685. Note that leading and trailing whitespace will be included in the string - to remove
  10686. if, just call String::trim() on the result.
  10687. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  10688. */
  10689. String getAllSubText() const;
  10690. /** Returns all the sub-text of a named child element.
  10691. If there is a child element with the given tag name, this will return
  10692. all of its sub-text (by calling getAllSubText() on it). If there is
  10693. no such child element, this will return the default string passed-in.
  10694. @see getAllSubText
  10695. */
  10696. String getChildElementAllSubText (const String& childTagName,
  10697. const String& defaultReturnValue) const;
  10698. /** Appends a section of text to this element.
  10699. @see isTextElement, getText, getAllSubText
  10700. */
  10701. void addTextElement (const String& text);
  10702. /** Removes all the text elements from this element.
  10703. @see isTextElement, getText, getAllSubText, addTextElement
  10704. */
  10705. void deleteAllTextElements() noexcept;
  10706. /** Creates a text element that can be added to a parent element.
  10707. */
  10708. static XmlElement* createTextElement (const String& text);
  10709. private:
  10710. struct XmlAttributeNode
  10711. {
  10712. XmlAttributeNode (const XmlAttributeNode& other) noexcept;
  10713. XmlAttributeNode (const String& name, const String& value) noexcept;
  10714. LinkedListPointer<XmlAttributeNode> nextListItem;
  10715. String name, value;
  10716. bool hasName (const String& name) const noexcept;
  10717. private:
  10718. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10719. };
  10720. friend class XmlDocument;
  10721. friend class LinkedListPointer<XmlAttributeNode>;
  10722. friend class LinkedListPointer <XmlElement>;
  10723. friend class LinkedListPointer <XmlElement>::Appender;
  10724. LinkedListPointer <XmlElement> nextListItem;
  10725. LinkedListPointer <XmlElement> firstChildElement;
  10726. LinkedListPointer <XmlAttributeNode> attributes;
  10727. String tagName;
  10728. XmlElement (int) noexcept;
  10729. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10730. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10731. void getChildElementsAsArray (XmlElement**) const noexcept;
  10732. void reorderChildElements (XmlElement**, int) noexcept;
  10733. JUCE_LEAK_DETECTOR (XmlElement);
  10734. };
  10735. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10736. /*** End of inlined file: juce_XmlElement.h ***/
  10737. /**
  10738. A set of named property values, which can be strings, integers, floating point, etc.
  10739. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10740. to load and save types other than strings.
  10741. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10742. messages and saves/loads the list from a file.
  10743. */
  10744. class JUCE_API PropertySet
  10745. {
  10746. public:
  10747. /** Creates an empty PropertySet.
  10748. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10749. case-insensitive way
  10750. */
  10751. PropertySet (bool ignoreCaseOfKeyNames = false);
  10752. /** Creates a copy of another PropertySet.
  10753. */
  10754. PropertySet (const PropertySet& other);
  10755. /** Copies another PropertySet over this one.
  10756. */
  10757. PropertySet& operator= (const PropertySet& other);
  10758. /** Destructor. */
  10759. virtual ~PropertySet();
  10760. /** Returns one of the properties as a string.
  10761. If the value isn't found in this set, then this will look for it in a fallback
  10762. property set (if you've specified one with the setFallbackPropertySet() method),
  10763. and if it can't find one there, it'll return the default value passed-in.
  10764. @param keyName the name of the property to retrieve
  10765. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10766. */
  10767. String getValue (const String& keyName,
  10768. const String& defaultReturnValue = String::empty) const noexcept;
  10769. /** Returns one of the properties as an integer.
  10770. If the value isn't found in this set, then this will look for it in a fallback
  10771. property set (if you've specified one with the setFallbackPropertySet() method),
  10772. and if it can't find one there, it'll return the default value passed-in.
  10773. @param keyName the name of the property to retrieve
  10774. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10775. */
  10776. int getIntValue (const String& keyName,
  10777. const int defaultReturnValue = 0) const noexcept;
  10778. /** Returns one of the properties as an double.
  10779. If the value isn't found in this set, then this will look for it in a fallback
  10780. property set (if you've specified one with the setFallbackPropertySet() method),
  10781. and if it can't find one there, it'll return the default value passed-in.
  10782. @param keyName the name of the property to retrieve
  10783. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10784. */
  10785. double getDoubleValue (const String& keyName,
  10786. const double defaultReturnValue = 0.0) const noexcept;
  10787. /** Returns one of the properties as an boolean.
  10788. The result will be true if the string found for this key name can be parsed as a non-zero
  10789. integer.
  10790. If the value isn't found in this set, then this will look for it in a fallback
  10791. property set (if you've specified one with the setFallbackPropertySet() method),
  10792. and if it can't find one there, it'll return the default value passed-in.
  10793. @param keyName the name of the property to retrieve
  10794. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10795. */
  10796. bool getBoolValue (const String& keyName,
  10797. const bool defaultReturnValue = false) const noexcept;
  10798. /** Returns one of the properties as an XML element.
  10799. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10800. key isn't found, or if the entry contains an string that isn't valid XML.
  10801. If the value isn't found in this set, then this will look for it in a fallback
  10802. property set (if you've specified one with the setFallbackPropertySet() method),
  10803. and if it can't find one there, it'll return the default value passed-in.
  10804. @param keyName the name of the property to retrieve
  10805. */
  10806. XmlElement* getXmlValue (const String& keyName) const;
  10807. /** Sets a named property.
  10808. @param keyName the name of the property to set. (This mustn't be an empty string)
  10809. @param value the new value to set it to
  10810. */
  10811. void setValue (const String& keyName, const var& value);
  10812. /** Sets a named property to an XML element.
  10813. @param keyName the name of the property to set. (This mustn't be an empty string)
  10814. @param xml the new element to set it to. If this is zero, the value will be set to
  10815. an empty string
  10816. @see getXmlValue
  10817. */
  10818. void setValue (const String& keyName, const XmlElement* xml);
  10819. /** Deletes a property.
  10820. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10821. */
  10822. void removeValue (const String& keyName);
  10823. /** Returns true if the properies include the given key. */
  10824. bool containsKey (const String& keyName) const noexcept;
  10825. /** Removes all values. */
  10826. void clear();
  10827. /** Returns the keys/value pair array containing all the properties. */
  10828. StringPairArray& getAllProperties() noexcept { return properties; }
  10829. /** Returns the lock used when reading or writing to this set */
  10830. const CriticalSection& getLock() const noexcept { return lock; }
  10831. /** Returns an XML element which encapsulates all the items in this property set.
  10832. The string parameter is the tag name that should be used for the node.
  10833. @see restoreFromXml
  10834. */
  10835. XmlElement* createXml (const String& nodeName) const;
  10836. /** Reloads a set of properties that were previously stored as XML.
  10837. The node passed in must have been created by the createXml() method.
  10838. @see createXml
  10839. */
  10840. void restoreFromXml (const XmlElement& xml);
  10841. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10842. set in this one.
  10843. If you set this up to be a pointer to a second property set, then whenever one
  10844. of the getValue() methods fails to find an entry in this set, it will look up that
  10845. value in the fallback set, and if it finds it, it will return that.
  10846. Make sure that you don't delete the fallback set while it's still being used by
  10847. another set! To remove the fallback set, just call this method with a null pointer.
  10848. @see getFallbackPropertySet
  10849. */
  10850. void setFallbackPropertySet (PropertySet* fallbackProperties) noexcept;
  10851. /** Returns the fallback property set.
  10852. @see setFallbackPropertySet
  10853. */
  10854. PropertySet* getFallbackPropertySet() const noexcept { return fallbackProperties; }
  10855. protected:
  10856. /** Subclasses can override this to be told when one of the properies has been changed. */
  10857. virtual void propertyChanged();
  10858. private:
  10859. StringPairArray properties;
  10860. PropertySet* fallbackProperties;
  10861. CriticalSection lock;
  10862. bool ignoreCaseOfKeys;
  10863. JUCE_LEAK_DETECTOR (PropertySet);
  10864. };
  10865. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10866. /*** End of inlined file: juce_PropertySet.h ***/
  10867. #endif
  10868. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10869. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10870. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10871. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10872. /**
  10873. Holds a list of objects derived from ReferenceCountedObject.
  10874. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10875. and takes care of incrementing and decrementing their ref counts when they
  10876. are added and removed from the array.
  10877. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10878. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10879. @see Array, OwnedArray, StringArray
  10880. */
  10881. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10882. class ReferenceCountedArray
  10883. {
  10884. public:
  10885. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10886. /** Creates an empty array.
  10887. @see ReferenceCountedObject, Array, OwnedArray
  10888. */
  10889. ReferenceCountedArray() noexcept
  10890. : numUsed (0)
  10891. {
  10892. }
  10893. /** Creates a copy of another array */
  10894. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10895. {
  10896. const ScopedLockType lock (other.getLock());
  10897. numUsed = other.numUsed;
  10898. data.setAllocatedSize (numUsed);
  10899. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10900. for (int i = numUsed; --i >= 0;)
  10901. if (data.elements[i] != nullptr)
  10902. data.elements[i]->incReferenceCount();
  10903. }
  10904. /** Copies another array into this one.
  10905. Any existing objects in this array will first be released.
  10906. */
  10907. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10908. {
  10909. if (this != &other)
  10910. {
  10911. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10912. swapWithArray (otherCopy);
  10913. }
  10914. return *this;
  10915. }
  10916. /** Destructor.
  10917. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10918. */
  10919. ~ReferenceCountedArray()
  10920. {
  10921. clear();
  10922. }
  10923. /** Removes all objects from the array.
  10924. Any objects in the array that are not referenced from elsewhere will be deleted.
  10925. */
  10926. void clear()
  10927. {
  10928. const ScopedLockType lock (getLock());
  10929. while (numUsed > 0)
  10930. if (data.elements [--numUsed] != nullptr)
  10931. data.elements [numUsed]->decReferenceCount();
  10932. jassert (numUsed == 0);
  10933. data.setAllocatedSize (0);
  10934. }
  10935. /** Returns the current number of objects in the array. */
  10936. inline int size() const noexcept
  10937. {
  10938. return numUsed;
  10939. }
  10940. /** Returns a pointer to the object at this index in the array.
  10941. If the index is out-of-range, this will return a null pointer, (and
  10942. it could be null anyway, because it's ok for the array to hold null
  10943. pointers as well as objects).
  10944. @see getUnchecked
  10945. */
  10946. inline const ObjectClassPtr operator[] (const int index) const noexcept
  10947. {
  10948. const ScopedLockType lock (getLock());
  10949. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10950. : static_cast <ObjectClass*> (nullptr);
  10951. }
  10952. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10953. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10954. it can be used when you're sure the index if always going to be legal.
  10955. */
  10956. inline const ObjectClassPtr getUnchecked (const int index) const noexcept
  10957. {
  10958. const ScopedLockType lock (getLock());
  10959. jassert (isPositiveAndBelow (index, numUsed));
  10960. return data.elements [index];
  10961. }
  10962. /** Returns a pointer to the first object in the array.
  10963. This will return a null pointer if the array's empty.
  10964. @see getLast
  10965. */
  10966. inline const ObjectClassPtr getFirst() const noexcept
  10967. {
  10968. const ScopedLockType lock (getLock());
  10969. return numUsed > 0 ? data.elements [0]
  10970. : static_cast <ObjectClass*> (nullptr);
  10971. }
  10972. /** Returns a pointer to the last object in the array.
  10973. This will return a null pointer if the array's empty.
  10974. @see getFirst
  10975. */
  10976. inline const ObjectClassPtr getLast() const noexcept
  10977. {
  10978. const ScopedLockType lock (getLock());
  10979. return numUsed > 0 ? data.elements [numUsed - 1]
  10980. : static_cast <ObjectClass*> (nullptr);
  10981. }
  10982. /** Returns a pointer to the first element in the array.
  10983. This method is provided for compatibility with standard C++ iteration mechanisms.
  10984. */
  10985. inline ObjectClass** begin() const noexcept
  10986. {
  10987. return data.elements;
  10988. }
  10989. /** Returns a pointer to the element which follows the last element in the array.
  10990. This method is provided for compatibility with standard C++ iteration mechanisms.
  10991. */
  10992. inline ObjectClass** end() const noexcept
  10993. {
  10994. return data.elements + numUsed;
  10995. }
  10996. /** Finds the index of the first occurrence of an object in the array.
  10997. @param objectToLookFor the object to look for
  10998. @returns the index at which the object was found, or -1 if it's not found
  10999. */
  11000. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  11001. {
  11002. const ScopedLockType lock (getLock());
  11003. ObjectClass** e = data.elements.getData();
  11004. ObjectClass** const end = e + numUsed;
  11005. while (e != end)
  11006. {
  11007. if (objectToLookFor == *e)
  11008. return static_cast <int> (e - data.elements.getData());
  11009. ++e;
  11010. }
  11011. return -1;
  11012. }
  11013. /** Returns true if the array contains a specified object.
  11014. @param objectToLookFor the object to look for
  11015. @returns true if the object is in the array
  11016. */
  11017. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  11018. {
  11019. const ScopedLockType lock (getLock());
  11020. ObjectClass** e = data.elements.getData();
  11021. ObjectClass** const end = e + numUsed;
  11022. while (e != end)
  11023. {
  11024. if (objectToLookFor == *e)
  11025. return true;
  11026. ++e;
  11027. }
  11028. return false;
  11029. }
  11030. /** Appends a new object to the end of the array.
  11031. This will increase the new object's reference count.
  11032. @param newObject the new object to add to the array
  11033. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  11034. */
  11035. void add (ObjectClass* const newObject) noexcept
  11036. {
  11037. const ScopedLockType lock (getLock());
  11038. data.ensureAllocatedSize (numUsed + 1);
  11039. data.elements [numUsed++] = newObject;
  11040. if (newObject != nullptr)
  11041. newObject->incReferenceCount();
  11042. }
  11043. /** Inserts a new object into the array at the given index.
  11044. If the index is less than 0 or greater than the size of the array, the
  11045. element will be added to the end of the array.
  11046. Otherwise, it will be inserted into the array, moving all the later elements
  11047. along to make room.
  11048. This will increase the new object's reference count.
  11049. @param indexToInsertAt the index at which the new element should be inserted
  11050. @param newObject the new object to add to the array
  11051. @see add, addSorted, addIfNotAlreadyThere, set
  11052. */
  11053. void insert (int indexToInsertAt,
  11054. ObjectClass* const newObject) noexcept
  11055. {
  11056. if (indexToInsertAt >= 0)
  11057. {
  11058. const ScopedLockType lock (getLock());
  11059. if (indexToInsertAt > numUsed)
  11060. indexToInsertAt = numUsed;
  11061. data.ensureAllocatedSize (numUsed + 1);
  11062. ObjectClass** const e = data.elements + indexToInsertAt;
  11063. const int numToMove = numUsed - indexToInsertAt;
  11064. if (numToMove > 0)
  11065. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  11066. *e = newObject;
  11067. if (newObject != nullptr)
  11068. newObject->incReferenceCount();
  11069. ++numUsed;
  11070. }
  11071. else
  11072. {
  11073. add (newObject);
  11074. }
  11075. }
  11076. /** Appends a new object at the end of the array as long as the array doesn't
  11077. already contain it.
  11078. If the array already contains a matching object, nothing will be done.
  11079. @param newObject the new object to add to the array
  11080. */
  11081. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  11082. {
  11083. const ScopedLockType lock (getLock());
  11084. if (! contains (newObject))
  11085. add (newObject);
  11086. }
  11087. /** Replaces an object in the array with a different one.
  11088. If the index is less than zero, this method does nothing.
  11089. If the index is beyond the end of the array, the new object is added to the end of the array.
  11090. The object being added has its reference count increased, and if it's replacing
  11091. another object, then that one has its reference count decreased, and may be deleted.
  11092. @param indexToChange the index whose value you want to change
  11093. @param newObject the new value to set for this index.
  11094. @see add, insert, remove
  11095. */
  11096. void set (const int indexToChange,
  11097. ObjectClass* const newObject)
  11098. {
  11099. if (indexToChange >= 0)
  11100. {
  11101. const ScopedLockType lock (getLock());
  11102. if (newObject != nullptr)
  11103. newObject->incReferenceCount();
  11104. if (indexToChange < numUsed)
  11105. {
  11106. if (data.elements [indexToChange] != nullptr)
  11107. data.elements [indexToChange]->decReferenceCount();
  11108. data.elements [indexToChange] = newObject;
  11109. }
  11110. else
  11111. {
  11112. data.ensureAllocatedSize (numUsed + 1);
  11113. data.elements [numUsed++] = newObject;
  11114. }
  11115. }
  11116. }
  11117. /** Adds elements from another array to the end of this array.
  11118. @param arrayToAddFrom the array from which to copy the elements
  11119. @param startIndex the first element of the other array to start copying from
  11120. @param numElementsToAdd how many elements to add from the other array. If this
  11121. value is negative or greater than the number of available elements,
  11122. all available elements will be copied.
  11123. @see add
  11124. */
  11125. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  11126. int startIndex = 0,
  11127. int numElementsToAdd = -1) noexcept
  11128. {
  11129. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  11130. {
  11131. const ScopedLockType lock2 (getLock());
  11132. if (startIndex < 0)
  11133. {
  11134. jassertfalse;
  11135. startIndex = 0;
  11136. }
  11137. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  11138. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  11139. if (numElementsToAdd > 0)
  11140. {
  11141. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  11142. while (--numElementsToAdd >= 0)
  11143. add (arrayToAddFrom.getUnchecked (startIndex++));
  11144. }
  11145. }
  11146. }
  11147. /** Inserts a new object into the array assuming that the array is sorted.
  11148. This will use a comparator to find the position at which the new object
  11149. should go. If the array isn't sorted, the behaviour of this
  11150. method will be unpredictable.
  11151. @param comparator the comparator object to use to compare the elements - see the
  11152. sort() method for details about this object's form
  11153. @param newObject the new object to insert to the array
  11154. @returns the index at which the new object was added
  11155. @see add, sort
  11156. */
  11157. template <class ElementComparator>
  11158. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  11159. {
  11160. const ScopedLockType lock (getLock());
  11161. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11162. insert (index, newObject);
  11163. return index;
  11164. }
  11165. /** Inserts or replaces an object in the array, assuming it is sorted.
  11166. This is similar to addSorted, but if a matching element already exists, then it will be
  11167. replaced by the new one, rather than the new one being added as well.
  11168. */
  11169. template <class ElementComparator>
  11170. void addOrReplaceSorted (ElementComparator& comparator,
  11171. ObjectClass* newObject) noexcept
  11172. {
  11173. const ScopedLockType lock (getLock());
  11174. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11175. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  11176. set (index - 1, newObject); // replace an existing object that matches
  11177. else
  11178. insert (index, newObject); // no match, so insert the new one
  11179. }
  11180. /** Removes an object from the array.
  11181. This will remove the object at a given index and move back all the
  11182. subsequent objects to close the gap.
  11183. If the index passed in is out-of-range, nothing will happen.
  11184. The object that is removed will have its reference count decreased,
  11185. and may be deleted if not referenced from elsewhere.
  11186. @param indexToRemove the index of the element to remove
  11187. @see removeObject, removeRange
  11188. */
  11189. void remove (const int indexToRemove)
  11190. {
  11191. const ScopedLockType lock (getLock());
  11192. if (isPositiveAndBelow (indexToRemove, numUsed))
  11193. {
  11194. ObjectClass** const e = data.elements + indexToRemove;
  11195. if (*e != nullptr)
  11196. (*e)->decReferenceCount();
  11197. --numUsed;
  11198. const int numberToShift = numUsed - indexToRemove;
  11199. if (numberToShift > 0)
  11200. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11201. if ((numUsed << 1) < data.numAllocated)
  11202. minimiseStorageOverheads();
  11203. }
  11204. }
  11205. /** Removes and returns an object from the array.
  11206. This will remove the object at a given index and return it, moving back all
  11207. the subsequent objects to close the gap. If the index passed in is out-of-range,
  11208. nothing will happen and a null pointer will be returned.
  11209. @param indexToRemove the index of the element to remove
  11210. @see remove, removeObject, removeRange
  11211. */
  11212. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  11213. {
  11214. ObjectClassPtr removedItem;
  11215. const ScopedLockType lock (getLock());
  11216. if (isPositiveAndBelow (indexToRemove, numUsed))
  11217. {
  11218. ObjectClass** const e = data.elements + indexToRemove;
  11219. if (*e != nullptr)
  11220. {
  11221. removedItem = *e;
  11222. (*e)->decReferenceCount();
  11223. }
  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. return removedItem;
  11232. }
  11233. /** Removes the first occurrence of a specified object from the array.
  11234. If the item isn't found, no action is taken. If it is found, it is
  11235. removed and has its reference count decreased.
  11236. @param objectToRemove the object to try to remove
  11237. @see remove, removeRange
  11238. */
  11239. void removeObject (ObjectClass* const objectToRemove)
  11240. {
  11241. const ScopedLockType lock (getLock());
  11242. remove (indexOf (objectToRemove));
  11243. }
  11244. /** Removes a range of objects from the array.
  11245. This will remove a set of objects, starting from the given index,
  11246. and move any subsequent elements down to close the gap.
  11247. If the range extends beyond the bounds of the array, it will
  11248. be safely clipped to the size of the array.
  11249. The objects that are removed will have their reference counts decreased,
  11250. and may be deleted if not referenced from elsewhere.
  11251. @param startIndex the index of the first object to remove
  11252. @param numberToRemove how many objects should be removed
  11253. @see remove, removeObject
  11254. */
  11255. void removeRange (const int startIndex,
  11256. const int numberToRemove)
  11257. {
  11258. const ScopedLockType lock (getLock());
  11259. const int start = jlimit (0, numUsed, startIndex);
  11260. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  11261. if (end > start)
  11262. {
  11263. int i;
  11264. for (i = start; i < end; ++i)
  11265. {
  11266. if (data.elements[i] != nullptr)
  11267. {
  11268. data.elements[i]->decReferenceCount();
  11269. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  11270. }
  11271. }
  11272. const int rangeSize = end - start;
  11273. ObjectClass** e = data.elements + start;
  11274. i = numUsed - end;
  11275. numUsed -= rangeSize;
  11276. while (--i >= 0)
  11277. {
  11278. *e = e [rangeSize];
  11279. ++e;
  11280. }
  11281. if ((numUsed << 1) < data.numAllocated)
  11282. minimiseStorageOverheads();
  11283. }
  11284. }
  11285. /** Removes the last n objects from the array.
  11286. The objects that are removed will have their reference counts decreased,
  11287. and may be deleted if not referenced from elsewhere.
  11288. @param howManyToRemove how many objects to remove from the end of the array
  11289. @see remove, removeObject, removeRange
  11290. */
  11291. void removeLast (int howManyToRemove = 1)
  11292. {
  11293. const ScopedLockType lock (getLock());
  11294. if (howManyToRemove > numUsed)
  11295. howManyToRemove = numUsed;
  11296. while (--howManyToRemove >= 0)
  11297. remove (numUsed - 1);
  11298. }
  11299. /** Swaps a pair of objects in the array.
  11300. If either of the indexes passed in is out-of-range, nothing will happen,
  11301. otherwise the two objects at these positions will be exchanged.
  11302. */
  11303. void swap (const int index1,
  11304. const int index2) noexcept
  11305. {
  11306. const ScopedLockType lock (getLock());
  11307. if (isPositiveAndBelow (index1, numUsed)
  11308. && isPositiveAndBelow (index2, numUsed))
  11309. {
  11310. std::swap (data.elements [index1],
  11311. data.elements [index2]);
  11312. }
  11313. }
  11314. /** Moves one of the objects to a different position.
  11315. This will move the object to a specified index, shuffling along
  11316. any intervening elements as required.
  11317. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  11318. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  11319. @param currentIndex the index of the object to be moved. If this isn't a
  11320. valid index, then nothing will be done
  11321. @param newIndex the index at which you'd like this object to end up. If this
  11322. is less than zero, it will be moved to the end of the array
  11323. */
  11324. void move (const int currentIndex,
  11325. int newIndex) noexcept
  11326. {
  11327. if (currentIndex != newIndex)
  11328. {
  11329. const ScopedLockType lock (getLock());
  11330. if (isPositiveAndBelow (currentIndex, numUsed))
  11331. {
  11332. if (! isPositiveAndBelow (newIndex, numUsed))
  11333. newIndex = numUsed - 1;
  11334. ObjectClass* const value = data.elements [currentIndex];
  11335. if (newIndex > currentIndex)
  11336. {
  11337. memmove (data.elements + currentIndex,
  11338. data.elements + currentIndex + 1,
  11339. (newIndex - currentIndex) * sizeof (ObjectClass*));
  11340. }
  11341. else
  11342. {
  11343. memmove (data.elements + newIndex + 1,
  11344. data.elements + newIndex,
  11345. (currentIndex - newIndex) * sizeof (ObjectClass*));
  11346. }
  11347. data.elements [newIndex] = value;
  11348. }
  11349. }
  11350. }
  11351. /** This swaps the contents of this array with those of another array.
  11352. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  11353. because it just swaps their internal pointers.
  11354. */
  11355. void swapWithArray (ReferenceCountedArray& otherArray) noexcept
  11356. {
  11357. const ScopedLockType lock1 (getLock());
  11358. const ScopedLockType lock2 (otherArray.getLock());
  11359. data.swapWith (otherArray.data);
  11360. std::swap (numUsed, otherArray.numUsed);
  11361. }
  11362. /** Compares this array to another one.
  11363. @returns true only if the other array contains the same objects in the same order
  11364. */
  11365. bool operator== (const ReferenceCountedArray& other) const noexcept
  11366. {
  11367. const ScopedLockType lock2 (other.getLock());
  11368. const ScopedLockType lock1 (getLock());
  11369. if (numUsed != other.numUsed)
  11370. return false;
  11371. for (int i = numUsed; --i >= 0;)
  11372. if (data.elements [i] != other.data.elements [i])
  11373. return false;
  11374. return true;
  11375. }
  11376. /** Compares this array to another one.
  11377. @see operator==
  11378. */
  11379. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  11380. {
  11381. return ! operator== (other);
  11382. }
  11383. /** Sorts the elements in the array.
  11384. This will use a comparator object to sort the elements into order. The object
  11385. passed must have a method of the form:
  11386. @code
  11387. int compareElements (ElementType first, ElementType second);
  11388. @endcode
  11389. ..and this method must return:
  11390. - a value of < 0 if the first comes before the second
  11391. - a value of 0 if the two objects are equivalent
  11392. - a value of > 0 if the second comes before the first
  11393. To improve performance, the compareElements() method can be declared as static or const.
  11394. @param comparator the comparator to use for comparing elements.
  11395. @param retainOrderOfEquivalentItems if this is true, then items
  11396. which the comparator says are equivalent will be
  11397. kept in the order in which they currently appear
  11398. in the array. This is slower to perform, but may
  11399. be important in some cases. If it's false, a faster
  11400. algorithm is used, but equivalent elements may be
  11401. rearranged.
  11402. @see sortArray
  11403. */
  11404. template <class ElementComparator>
  11405. void sort (ElementComparator& comparator,
  11406. const bool retainOrderOfEquivalentItems = false) const noexcept
  11407. {
  11408. (void) comparator; // if you pass in an object with a static compareElements() method, this
  11409. // avoids getting warning messages about the parameter being unused
  11410. const ScopedLockType lock (getLock());
  11411. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  11412. }
  11413. /** Reduces the amount of storage being used by the array.
  11414. Arrays typically allocate slightly more storage than they need, and after
  11415. removing elements, they may have quite a lot of unused space allocated.
  11416. This method will reduce the amount of allocated storage to a minimum.
  11417. */
  11418. void minimiseStorageOverheads() noexcept
  11419. {
  11420. const ScopedLockType lock (getLock());
  11421. data.shrinkToNoMoreThan (numUsed);
  11422. }
  11423. /** Returns the CriticalSection that locks this array.
  11424. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11425. an object of ScopedLockType as an RAII lock for it.
  11426. */
  11427. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11428. /** Returns the type of scoped lock to use for locking this array */
  11429. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11430. private:
  11431. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  11432. int numUsed;
  11433. };
  11434. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  11435. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  11436. #endif
  11437. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11438. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  11439. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11440. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11441. /**
  11442. Helper class providing an RAII-based mechanism for temporarily setting and
  11443. then re-setting a value.
  11444. E.g. @code
  11445. int x = 1;
  11446. {
  11447. ScopedValueSetter setter (x, 2);
  11448. // x is now 2
  11449. }
  11450. // x is now 1 again
  11451. {
  11452. ScopedValueSetter setter (x, 3, 4);
  11453. // x is now 3
  11454. }
  11455. // x is now 4
  11456. @endcode
  11457. */
  11458. template <typename ValueType>
  11459. class ScopedValueSetter
  11460. {
  11461. public:
  11462. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11463. given new value, and will then reset it to its original value when this object is deleted.
  11464. */
  11465. ScopedValueSetter (ValueType& valueToSet,
  11466. const ValueType& newValue)
  11467. : value (valueToSet),
  11468. originalValue (valueToSet)
  11469. {
  11470. valueToSet = newValue;
  11471. }
  11472. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11473. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  11474. */
  11475. ScopedValueSetter (ValueType& valueToSet,
  11476. const ValueType& newValue,
  11477. const ValueType& valueWhenDeleted)
  11478. : value (valueToSet),
  11479. originalValue (valueWhenDeleted)
  11480. {
  11481. valueToSet = newValue;
  11482. }
  11483. ~ScopedValueSetter()
  11484. {
  11485. value = originalValue;
  11486. }
  11487. private:
  11488. ValueType& value;
  11489. const ValueType originalValue;
  11490. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  11491. };
  11492. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11493. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  11494. #endif
  11495. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11496. /*** Start of inlined file: juce_SortedSet.h ***/
  11497. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11498. #define __JUCE_SORTEDSET_JUCEHEADER__
  11499. #if JUCE_MSVC
  11500. #pragma warning (push)
  11501. #pragma warning (disable: 4512)
  11502. #endif
  11503. /**
  11504. Holds a set of unique primitive objects, such as ints or doubles.
  11505. A set can only hold one item with a given value, so if for example it's a
  11506. set of integers, attempting to add the same integer twice will do nothing
  11507. the second time.
  11508. Internally, the list of items is kept sorted (which means that whatever
  11509. kind of primitive type is used must support the ==, <, >, <= and >= operators
  11510. to determine the order), and searching the set for known values is very fast
  11511. because it uses a binary-chop method.
  11512. Note that if you're using a class or struct as the element type, it must be
  11513. capable of being copied or moved with a straightforward memcpy, rather than
  11514. needing construction and destruction code.
  11515. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  11516. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  11517. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  11518. */
  11519. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  11520. class SortedSet
  11521. {
  11522. public:
  11523. /** Creates an empty set. */
  11524. SortedSet() noexcept
  11525. : numUsed (0)
  11526. {
  11527. }
  11528. /** Creates a copy of another set.
  11529. @param other the set to copy
  11530. */
  11531. SortedSet (const SortedSet& other) noexcept
  11532. {
  11533. const ScopedLockType lock (other.getLock());
  11534. numUsed = other.numUsed;
  11535. data.setAllocatedSize (other.numUsed);
  11536. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11537. }
  11538. /** Destructor. */
  11539. ~SortedSet() noexcept
  11540. {
  11541. }
  11542. /** Copies another set over this one.
  11543. @param other the set to copy
  11544. */
  11545. SortedSet& operator= (const SortedSet& other) noexcept
  11546. {
  11547. if (this != &other)
  11548. {
  11549. const ScopedLockType lock1 (other.getLock());
  11550. const ScopedLockType lock2 (getLock());
  11551. data.ensureAllocatedSize (other.size());
  11552. numUsed = other.numUsed;
  11553. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11554. minimiseStorageOverheads();
  11555. }
  11556. return *this;
  11557. }
  11558. /** Compares this set to another one.
  11559. Two sets are considered equal if they both contain the same set of
  11560. elements.
  11561. @param other the other set to compare with
  11562. */
  11563. bool operator== (const SortedSet<ElementType>& other) const noexcept
  11564. {
  11565. const ScopedLockType lock (getLock());
  11566. if (numUsed != other.numUsed)
  11567. return false;
  11568. for (int i = numUsed; --i >= 0;)
  11569. if (! (data.elements[i] == other.data.elements[i]))
  11570. return false;
  11571. return true;
  11572. }
  11573. /** Compares this set to another one.
  11574. Two sets are considered equal if they both contain the same set of
  11575. elements.
  11576. @param other the other set to compare with
  11577. */
  11578. bool operator!= (const SortedSet<ElementType>& other) const noexcept
  11579. {
  11580. return ! operator== (other);
  11581. }
  11582. /** Removes all elements from the set.
  11583. This will remove all the elements, and free any storage that the set is
  11584. using. To clear it without freeing the storage, use the clearQuick()
  11585. method instead.
  11586. @see clearQuick
  11587. */
  11588. void clear() noexcept
  11589. {
  11590. const ScopedLockType lock (getLock());
  11591. data.setAllocatedSize (0);
  11592. numUsed = 0;
  11593. }
  11594. /** Removes all elements from the set without freeing the array's allocated storage.
  11595. @see clear
  11596. */
  11597. void clearQuick() noexcept
  11598. {
  11599. const ScopedLockType lock (getLock());
  11600. numUsed = 0;
  11601. }
  11602. /** Returns the current number of elements in the set.
  11603. */
  11604. inline int size() const noexcept
  11605. {
  11606. return numUsed;
  11607. }
  11608. /** Returns one of the elements in the set.
  11609. If the index passed in is beyond the range of valid elements, this
  11610. will return zero.
  11611. If you're certain that the index will always be a valid element, you
  11612. can call getUnchecked() instead, which is faster.
  11613. @param index the index of the element being requested (0 is the first element in the set)
  11614. @see getUnchecked, getFirst, getLast
  11615. */
  11616. inline ElementType operator[] (const int index) const noexcept
  11617. {
  11618. const ScopedLockType lock (getLock());
  11619. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11620. : ElementType();
  11621. }
  11622. /** Returns one of the elements in the set, without checking the index passed in.
  11623. Unlike the operator[] method, this will try to return an element without
  11624. checking that the index is within the bounds of the set, so should only
  11625. be used when you're confident that it will always be a valid index.
  11626. @param index the index of the element being requested (0 is the first element in the set)
  11627. @see operator[], getFirst, getLast
  11628. */
  11629. inline ElementType getUnchecked (const int index) const noexcept
  11630. {
  11631. const ScopedLockType lock (getLock());
  11632. jassert (isPositiveAndBelow (index, numUsed));
  11633. return data.elements [index];
  11634. }
  11635. /** Returns a direct reference to one of the elements in the set, without checking the index passed in.
  11636. This is like getUnchecked, but returns a direct reference to the element, so that
  11637. you can alter it directly. Obviously this can be dangerous, so only use it when
  11638. absolutely necessary.
  11639. @param index the index of the element being requested (0 is the first element in the array)
  11640. */
  11641. inline ElementType& getReference (const int index) const noexcept
  11642. {
  11643. const ScopedLockType lock (getLock());
  11644. jassert (isPositiveAndBelow (index, numUsed));
  11645. return data.elements [index];
  11646. }
  11647. /** Returns the first element in the set, or 0 if the set is empty.
  11648. @see operator[], getUnchecked, getLast
  11649. */
  11650. inline ElementType getFirst() const noexcept
  11651. {
  11652. const ScopedLockType lock (getLock());
  11653. return numUsed > 0 ? data.elements [0] : ElementType();
  11654. }
  11655. /** Returns the last element in the set, or 0 if the set is empty.
  11656. @see operator[], getUnchecked, getFirst
  11657. */
  11658. inline ElementType getLast() const noexcept
  11659. {
  11660. const ScopedLockType lock (getLock());
  11661. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  11662. }
  11663. /** Returns a pointer to the first element in the set.
  11664. This method is provided for compatibility with standard C++ iteration mechanisms.
  11665. */
  11666. inline ElementType* begin() const noexcept
  11667. {
  11668. return data.elements;
  11669. }
  11670. /** Returns a pointer to the element which follows the last element in the set.
  11671. This method is provided for compatibility with standard C++ iteration mechanisms.
  11672. */
  11673. inline ElementType* end() const noexcept
  11674. {
  11675. return data.elements + numUsed;
  11676. }
  11677. /** Finds the index of the first element which matches the value passed in.
  11678. This will search the set for the given object, and return the index
  11679. of its first occurrence. If the object isn't found, the method will return -1.
  11680. @param elementToLookFor the value or object to look for
  11681. @returns the index of the object, or -1 if it's not found
  11682. */
  11683. int indexOf (const ElementType elementToLookFor) const noexcept
  11684. {
  11685. const ScopedLockType lock (getLock());
  11686. int start = 0;
  11687. int end = numUsed;
  11688. for (;;)
  11689. {
  11690. if (start >= end)
  11691. {
  11692. return -1;
  11693. }
  11694. else if (elementToLookFor == data.elements [start])
  11695. {
  11696. return start;
  11697. }
  11698. else
  11699. {
  11700. const int halfway = (start + end) >> 1;
  11701. if (halfway == start)
  11702. return -1;
  11703. else if (elementToLookFor < data.elements [halfway])
  11704. end = halfway;
  11705. else
  11706. start = halfway;
  11707. }
  11708. }
  11709. }
  11710. /** Returns true if the set contains at least one occurrence of an object.
  11711. @param elementToLookFor the value or object to look for
  11712. @returns true if the item is found
  11713. */
  11714. bool contains (const ElementType elementToLookFor) const noexcept
  11715. {
  11716. const ScopedLockType lock (getLock());
  11717. int start = 0;
  11718. int end = numUsed;
  11719. for (;;)
  11720. {
  11721. if (start >= end)
  11722. {
  11723. return false;
  11724. }
  11725. else if (elementToLookFor == data.elements [start])
  11726. {
  11727. return true;
  11728. }
  11729. else
  11730. {
  11731. const int halfway = (start + end) >> 1;
  11732. if (halfway == start)
  11733. return false;
  11734. else if (elementToLookFor < data.elements [halfway])
  11735. end = halfway;
  11736. else
  11737. start = halfway;
  11738. }
  11739. }
  11740. }
  11741. /** Adds a new element to the set, (as long as it's not already in there).
  11742. @param newElement the new object to add to the set
  11743. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  11744. */
  11745. void add (const ElementType newElement) noexcept
  11746. {
  11747. const ScopedLockType lock (getLock());
  11748. int start = 0;
  11749. int end = numUsed;
  11750. for (;;)
  11751. {
  11752. if (start >= end)
  11753. {
  11754. jassert (start <= end);
  11755. insertInternal (start, newElement);
  11756. break;
  11757. }
  11758. else if (newElement == data.elements [start])
  11759. {
  11760. break;
  11761. }
  11762. else
  11763. {
  11764. const int halfway = (start + end) >> 1;
  11765. if (halfway == start)
  11766. {
  11767. if (newElement < data.elements [halfway])
  11768. insertInternal (start, newElement);
  11769. else
  11770. insertInternal (start + 1, newElement);
  11771. break;
  11772. }
  11773. else if (newElement < data.elements [halfway])
  11774. end = halfway;
  11775. else
  11776. start = halfway;
  11777. }
  11778. }
  11779. }
  11780. /** Adds elements from an array to this set.
  11781. @param elementsToAdd the array of elements to add
  11782. @param numElementsToAdd how many elements are in this other array
  11783. @see add
  11784. */
  11785. void addArray (const ElementType* elementsToAdd,
  11786. int numElementsToAdd) noexcept
  11787. {
  11788. const ScopedLockType lock (getLock());
  11789. while (--numElementsToAdd >= 0)
  11790. add (*elementsToAdd++);
  11791. }
  11792. /** Adds elements from another set to this one.
  11793. @param setToAddFrom the set from which to copy the elements
  11794. @param startIndex the first element of the other set to start copying from
  11795. @param numElementsToAdd how many elements to add from the other set. If this
  11796. value is negative or greater than the number of available elements,
  11797. all available elements will be copied.
  11798. @see add
  11799. */
  11800. template <class OtherSetType>
  11801. void addSet (const OtherSetType& setToAddFrom,
  11802. int startIndex = 0,
  11803. int numElementsToAdd = -1) noexcept
  11804. {
  11805. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11806. {
  11807. const ScopedLockType lock2 (getLock());
  11808. jassert (this != &setToAddFrom);
  11809. if (this != &setToAddFrom)
  11810. {
  11811. if (startIndex < 0)
  11812. {
  11813. jassertfalse;
  11814. startIndex = 0;
  11815. }
  11816. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11817. numElementsToAdd = setToAddFrom.size() - startIndex;
  11818. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11819. }
  11820. }
  11821. }
  11822. /** Removes an element from the set.
  11823. This will remove the element at a given index.
  11824. If the index passed in is out-of-range, nothing will happen.
  11825. @param indexToRemove the index of the element to remove
  11826. @returns the element that has been removed
  11827. @see removeValue, removeRange
  11828. */
  11829. ElementType remove (const int indexToRemove) noexcept
  11830. {
  11831. const ScopedLockType lock (getLock());
  11832. if (isPositiveAndBelow (indexToRemove, numUsed))
  11833. {
  11834. --numUsed;
  11835. ElementType* const e = data.elements + indexToRemove;
  11836. ElementType const removed = *e;
  11837. const int numberToShift = numUsed - indexToRemove;
  11838. if (numberToShift > 0)
  11839. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11840. if ((numUsed << 1) < data.numAllocated)
  11841. minimiseStorageOverheads();
  11842. return removed;
  11843. }
  11844. return ElementType();
  11845. }
  11846. /** Removes an item from the set.
  11847. This will remove the given element from the set, if it's there.
  11848. @param valueToRemove the object to try to remove
  11849. @see remove, removeRange
  11850. */
  11851. void removeValue (const ElementType valueToRemove) noexcept
  11852. {
  11853. const ScopedLockType lock (getLock());
  11854. remove (indexOf (valueToRemove));
  11855. }
  11856. /** Removes any elements which are also in another set.
  11857. @param otherSet the other set in which to look for elements to remove
  11858. @see removeValuesNotIn, remove, removeValue, removeRange
  11859. */
  11860. template <class OtherSetType>
  11861. void removeValuesIn (const OtherSetType& otherSet) noexcept
  11862. {
  11863. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11864. const ScopedLockType lock2 (getLock());
  11865. if (this == &otherSet)
  11866. {
  11867. clear();
  11868. }
  11869. else
  11870. {
  11871. if (otherSet.size() > 0)
  11872. {
  11873. for (int i = numUsed; --i >= 0;)
  11874. if (otherSet.contains (data.elements [i]))
  11875. remove (i);
  11876. }
  11877. }
  11878. }
  11879. /** Removes any elements which are not found in another set.
  11880. Only elements which occur in this other set will be retained.
  11881. @param otherSet the set in which to look for elements NOT to remove
  11882. @see removeValuesIn, remove, removeValue, removeRange
  11883. */
  11884. template <class OtherSetType>
  11885. void removeValuesNotIn (const OtherSetType& otherSet) noexcept
  11886. {
  11887. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11888. const ScopedLockType lock2 (getLock());
  11889. if (this != &otherSet)
  11890. {
  11891. if (otherSet.size() <= 0)
  11892. {
  11893. clear();
  11894. }
  11895. else
  11896. {
  11897. for (int i = numUsed; --i >= 0;)
  11898. if (! otherSet.contains (data.elements [i]))
  11899. remove (i);
  11900. }
  11901. }
  11902. }
  11903. /** Reduces the amount of storage being used by the set.
  11904. Sets typically allocate slightly more storage than they need, and after
  11905. removing elements, they may have quite a lot of unused space allocated.
  11906. This method will reduce the amount of allocated storage to a minimum.
  11907. */
  11908. void minimiseStorageOverheads() noexcept
  11909. {
  11910. const ScopedLockType lock (getLock());
  11911. data.shrinkToNoMoreThan (numUsed);
  11912. }
  11913. /** Increases the set's internal storage to hold a minimum number of elements.
  11914. Calling this before adding a large known number of elements means that
  11915. the set won't have to keep dynamically resizing itself as the elements
  11916. are added, and it'll therefore be more efficient.
  11917. */
  11918. void ensureStorageAllocated (const int minNumElements)
  11919. {
  11920. const ScopedLockType lock (getLock());
  11921. data.ensureAllocatedSize (minNumElements);
  11922. }
  11923. /** Returns the CriticalSection that locks this array.
  11924. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11925. an object of ScopedLockType as an RAII lock for it.
  11926. */
  11927. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11928. /** Returns the type of scoped lock to use for locking this array */
  11929. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11930. private:
  11931. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11932. int numUsed;
  11933. void insertInternal (const int indexToInsertAt, const ElementType newElement) noexcept
  11934. {
  11935. data.ensureAllocatedSize (numUsed + 1);
  11936. ElementType* const insertPos = data.elements + indexToInsertAt;
  11937. const int numberToMove = numUsed - indexToInsertAt;
  11938. if (numberToMove > 0)
  11939. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11940. *insertPos = newElement;
  11941. ++numUsed;
  11942. }
  11943. };
  11944. #if JUCE_MSVC
  11945. #pragma warning (pop)
  11946. #endif
  11947. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11948. /*** End of inlined file: juce_SortedSet.h ***/
  11949. #endif
  11950. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11951. /*** Start of inlined file: juce_SparseSet.h ***/
  11952. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11953. #define __JUCE_SPARSESET_JUCEHEADER__
  11954. /*** Start of inlined file: juce_Range.h ***/
  11955. #ifndef __JUCE_RANGE_JUCEHEADER__
  11956. #define __JUCE_RANGE_JUCEHEADER__
  11957. /** A general-purpose range object, that simply represents any linear range with
  11958. a start and end point.
  11959. The templated parameter is expected to be a primitive integer or floating point
  11960. type, though class types could also be used if they behave in a number-like way.
  11961. */
  11962. template <typename ValueType>
  11963. class Range
  11964. {
  11965. public:
  11966. /** Constructs an empty range. */
  11967. Range() noexcept
  11968. : start (ValueType()), end (ValueType())
  11969. {
  11970. }
  11971. /** Constructs a range with given start and end values. */
  11972. Range (const ValueType start_, const ValueType end_) noexcept
  11973. : start (start_), end (jmax (start_, end_))
  11974. {
  11975. }
  11976. /** Constructs a copy of another range. */
  11977. Range (const Range& other) noexcept
  11978. : start (other.start), end (other.end)
  11979. {
  11980. }
  11981. /** Copies another range object. */
  11982. Range& operator= (const Range& other) noexcept
  11983. {
  11984. start = other.start;
  11985. end = other.end;
  11986. return *this;
  11987. }
  11988. /** Destructor. */
  11989. ~Range() noexcept
  11990. {
  11991. }
  11992. /** Returns the range that lies between two positions (in either order). */
  11993. static Range between (const ValueType position1, const ValueType position2) noexcept
  11994. {
  11995. return (position1 < position2) ? Range (position1, position2)
  11996. : Range (position2, position1);
  11997. }
  11998. /** Returns a range with the specified start position and a length of zero. */
  11999. static Range emptyRange (const ValueType start) noexcept
  12000. {
  12001. return Range (start, start);
  12002. }
  12003. /** Returns the start of the range. */
  12004. inline ValueType getStart() const noexcept { return start; }
  12005. /** Returns the length of the range. */
  12006. inline ValueType getLength() const noexcept { return end - start; }
  12007. /** Returns the end of the range. */
  12008. inline ValueType getEnd() const noexcept { return end; }
  12009. /** Returns true if the range has a length of zero. */
  12010. inline bool isEmpty() const noexcept { return start == end; }
  12011. /** Changes the start position of the range, leaving the end position unchanged.
  12012. If the new start position is higher than the current end of the range, the end point
  12013. will be pushed along to equal it, leaving an empty range at the new position.
  12014. */
  12015. void setStart (const ValueType newStart) noexcept
  12016. {
  12017. start = newStart;
  12018. if (end < newStart)
  12019. end = newStart;
  12020. }
  12021. /** Returns a range with the same end as this one, but a different start.
  12022. If the new start position is higher than the current end of the range, the end point
  12023. will be pushed along to equal it, returning an empty range at the new position.
  12024. */
  12025. Range withStart (const ValueType newStart) const noexcept
  12026. {
  12027. return Range (newStart, jmax (newStart, end));
  12028. }
  12029. /** Returns a range with the same length as this one, but moved to have the given start position. */
  12030. Range movedToStartAt (const ValueType newStart) const noexcept
  12031. {
  12032. return Range (newStart, end + (newStart - start));
  12033. }
  12034. /** Changes the end position of the range, leaving the start unchanged.
  12035. If the new end position is below the current start of the range, the start point
  12036. will be pushed back to equal the new end point.
  12037. */
  12038. void setEnd (const ValueType newEnd) noexcept
  12039. {
  12040. end = newEnd;
  12041. if (newEnd < start)
  12042. start = newEnd;
  12043. }
  12044. /** Returns a range with the same start position as this one, but a different end.
  12045. If the new end position is below the current start of the range, the start point
  12046. will be pushed back to equal the new end point.
  12047. */
  12048. Range withEnd (const ValueType newEnd) const noexcept
  12049. {
  12050. return Range (jmin (start, newEnd), newEnd);
  12051. }
  12052. /** Returns a range with the same length as this one, but moved to have the given start position. */
  12053. Range movedToEndAt (const ValueType newEnd) const noexcept
  12054. {
  12055. return Range (start + (newEnd - end), newEnd);
  12056. }
  12057. /** Changes the length of the range.
  12058. Lengths less than zero are treated as zero.
  12059. */
  12060. void setLength (const ValueType newLength) noexcept
  12061. {
  12062. end = start + jmax (ValueType(), newLength);
  12063. }
  12064. /** Returns a range with the same start as this one, but a different length.
  12065. Lengths less than zero are treated as zero.
  12066. */
  12067. Range withLength (const ValueType newLength) const noexcept
  12068. {
  12069. return Range (start, start + newLength);
  12070. }
  12071. /** Adds an amount to the start and end of the range. */
  12072. inline const Range& operator+= (const ValueType amountToAdd) noexcept
  12073. {
  12074. start += amountToAdd;
  12075. end += amountToAdd;
  12076. return *this;
  12077. }
  12078. /** Subtracts an amount from the start and end of the range. */
  12079. inline const Range& operator-= (const ValueType amountToSubtract) noexcept
  12080. {
  12081. start -= amountToSubtract;
  12082. end -= amountToSubtract;
  12083. return *this;
  12084. }
  12085. /** Returns a range that is equal to this one with an amount added to its
  12086. start and end.
  12087. */
  12088. Range operator+ (const ValueType amountToAdd) const noexcept
  12089. {
  12090. return Range (start + amountToAdd, end + amountToAdd);
  12091. }
  12092. /** Returns a range that is equal to this one with the specified amount
  12093. subtracted from its start and end. */
  12094. Range operator- (const ValueType amountToSubtract) const noexcept
  12095. {
  12096. return Range (start - amountToSubtract, end - amountToSubtract);
  12097. }
  12098. bool operator== (const Range& other) const noexcept { return start == other.start && end == other.end; }
  12099. bool operator!= (const Range& other) const noexcept { return start != other.start || end != other.end; }
  12100. /** Returns true if the given position lies inside this range. */
  12101. bool contains (const ValueType position) const noexcept
  12102. {
  12103. return start <= position && position < end;
  12104. }
  12105. /** Returns the nearest value to the one supplied, which lies within the range. */
  12106. ValueType clipValue (const ValueType value) const noexcept
  12107. {
  12108. return jlimit (start, end, value);
  12109. }
  12110. /** Returns true if the given range lies entirely inside this range. */
  12111. bool contains (const Range& other) const noexcept
  12112. {
  12113. return start <= other.start && end >= other.end;
  12114. }
  12115. /** Returns true if the given range intersects this one. */
  12116. bool intersects (const Range& other) const noexcept
  12117. {
  12118. return other.start < end && start < other.end;
  12119. }
  12120. /** Returns the range that is the intersection of the two ranges, or an empty range
  12121. with an undefined start position if they don't overlap. */
  12122. Range getIntersectionWith (const Range& other) const noexcept
  12123. {
  12124. return Range (jmax (start, other.start),
  12125. jmin (end, other.end));
  12126. }
  12127. /** Returns the smallest range that contains both this one and the other one. */
  12128. Range getUnionWith (const Range& other) const noexcept
  12129. {
  12130. return Range (jmin (start, other.start),
  12131. jmax (end, other.end));
  12132. }
  12133. /** Returns a given range, after moving it forwards or backwards to fit it
  12134. within this range.
  12135. If the supplied range has a greater length than this one, the return value
  12136. will be this range.
  12137. Otherwise, if the supplied range is smaller than this one, the return value
  12138. will be the new range, shifted forwards or backwards so that it doesn't extend
  12139. beyond this one, but keeping its original length.
  12140. */
  12141. Range constrainRange (const Range& rangeToConstrain) const noexcept
  12142. {
  12143. const ValueType otherLen = rangeToConstrain.getLength();
  12144. return getLength() <= otherLen
  12145. ? *this
  12146. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  12147. }
  12148. private:
  12149. ValueType start, end;
  12150. };
  12151. #endif // __JUCE_RANGE_JUCEHEADER__
  12152. /*** End of inlined file: juce_Range.h ***/
  12153. /**
  12154. Holds a set of primitive values, storing them as a set of ranges.
  12155. This container acts like an array, but can efficiently hold large continguous
  12156. ranges of values. It's quite a specialised class, mostly useful for things
  12157. like keeping the set of selected rows in a listbox.
  12158. The type used as a template paramter must be an integer type, such as int, short,
  12159. int64, etc.
  12160. */
  12161. template <class Type>
  12162. class SparseSet
  12163. {
  12164. public:
  12165. /** Creates a new empty set. */
  12166. SparseSet()
  12167. {
  12168. }
  12169. /** Creates a copy of another SparseSet. */
  12170. SparseSet (const SparseSet<Type>& other)
  12171. : values (other.values)
  12172. {
  12173. }
  12174. /** Clears the set. */
  12175. void clear()
  12176. {
  12177. values.clear();
  12178. }
  12179. /** Checks whether the set is empty.
  12180. This is much quicker than using (size() == 0).
  12181. */
  12182. bool isEmpty() const noexcept
  12183. {
  12184. return values.size() == 0;
  12185. }
  12186. /** Returns the number of values in the set.
  12187. Because of the way the data is stored, this method can take longer if there
  12188. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  12189. are any items.
  12190. */
  12191. Type size() const
  12192. {
  12193. Type total (0);
  12194. for (int i = 0; i < values.size(); i += 2)
  12195. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  12196. return total;
  12197. }
  12198. /** Returns one of the values in the set.
  12199. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  12200. @returns the value at this index, or 0 if it's out-of-range
  12201. */
  12202. Type operator[] (Type index) const
  12203. {
  12204. for (int i = 0; i < values.size(); i += 2)
  12205. {
  12206. const Type start (values.getUnchecked (i));
  12207. const Type len (values.getUnchecked (i + 1) - start);
  12208. if (index < len)
  12209. return start + index;
  12210. index -= len;
  12211. }
  12212. return Type();
  12213. }
  12214. /** Checks whether a particular value is in the set. */
  12215. bool contains (const Type valueToLookFor) const
  12216. {
  12217. for (int i = 0; i < values.size(); ++i)
  12218. if (valueToLookFor < values.getUnchecked(i))
  12219. return (i & 1) != 0;
  12220. return false;
  12221. }
  12222. /** Returns the number of contiguous blocks of values.
  12223. @see getRange
  12224. */
  12225. int getNumRanges() const noexcept
  12226. {
  12227. return values.size() >> 1;
  12228. }
  12229. /** Returns one of the contiguous ranges of values stored.
  12230. @param rangeIndex the index of the range to look up, between 0
  12231. and (getNumRanges() - 1)
  12232. @see getTotalRange
  12233. */
  12234. const Range<Type> getRange (const int rangeIndex) const
  12235. {
  12236. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  12237. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  12238. values.getUnchecked ((rangeIndex << 1) + 1));
  12239. else
  12240. return Range<Type>();
  12241. }
  12242. /** Returns the range between the lowest and highest values in the set.
  12243. @see getRange
  12244. */
  12245. const Range<Type> getTotalRange() const
  12246. {
  12247. if (values.size() > 0)
  12248. {
  12249. jassert ((values.size() & 1) == 0);
  12250. return Range<Type> (values.getUnchecked (0),
  12251. values.getUnchecked (values.size() - 1));
  12252. }
  12253. return Range<Type>();
  12254. }
  12255. /** Adds a range of contiguous values to the set.
  12256. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  12257. */
  12258. void addRange (const Range<Type>& range)
  12259. {
  12260. jassert (range.getLength() >= 0);
  12261. if (range.getLength() > 0)
  12262. {
  12263. removeRange (range);
  12264. values.addUsingDefaultSort (range.getStart());
  12265. values.addUsingDefaultSort (range.getEnd());
  12266. simplify();
  12267. }
  12268. }
  12269. /** Removes a range of values from the set.
  12270. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  12271. */
  12272. void removeRange (const Range<Type>& rangeToRemove)
  12273. {
  12274. jassert (rangeToRemove.getLength() >= 0);
  12275. if (rangeToRemove.getLength() > 0
  12276. && values.size() > 0
  12277. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  12278. && values.getUnchecked(0) < rangeToRemove.getEnd())
  12279. {
  12280. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  12281. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  12282. const bool onAtEnd = contains (lastValue);
  12283. for (int i = values.size(); --i >= 0;)
  12284. {
  12285. if (values.getUnchecked(i) <= lastValue)
  12286. {
  12287. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  12288. {
  12289. values.remove (i);
  12290. if (--i < 0)
  12291. break;
  12292. }
  12293. break;
  12294. }
  12295. }
  12296. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  12297. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  12298. simplify();
  12299. }
  12300. }
  12301. /** Does an XOR of the values in a given range. */
  12302. void invertRange (const Range<Type>& range)
  12303. {
  12304. SparseSet newItems;
  12305. newItems.addRange (range);
  12306. int i;
  12307. for (i = getNumRanges(); --i >= 0;)
  12308. newItems.removeRange (getRange (i));
  12309. removeRange (range);
  12310. for (i = newItems.getNumRanges(); --i >= 0;)
  12311. addRange (newItems.getRange(i));
  12312. }
  12313. /** Checks whether any part of a given range overlaps any part of this set. */
  12314. bool overlapsRange (const Range<Type>& range)
  12315. {
  12316. if (range.getLength() > 0)
  12317. {
  12318. for (int i = getNumRanges(); --i >= 0;)
  12319. {
  12320. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12321. return false;
  12322. if (values.getUnchecked (i << 1) < range.getEnd())
  12323. return true;
  12324. }
  12325. }
  12326. return false;
  12327. }
  12328. /** Checks whether the whole of a given range is contained within this one. */
  12329. bool containsRange (const Range<Type>& range)
  12330. {
  12331. if (range.getLength() > 0)
  12332. {
  12333. for (int i = getNumRanges(); --i >= 0;)
  12334. {
  12335. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12336. return false;
  12337. if (values.getUnchecked (i << 1) <= range.getStart()
  12338. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  12339. return true;
  12340. }
  12341. }
  12342. return false;
  12343. }
  12344. bool operator== (const SparseSet<Type>& other) noexcept
  12345. {
  12346. return values == other.values;
  12347. }
  12348. bool operator!= (const SparseSet<Type>& other) noexcept
  12349. {
  12350. return values != other.values;
  12351. }
  12352. private:
  12353. // alternating start/end values of ranges of values that are present.
  12354. Array<Type, DummyCriticalSection> values;
  12355. void simplify()
  12356. {
  12357. jassert ((values.size() & 1) == 0);
  12358. for (int i = values.size(); --i > 0;)
  12359. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  12360. values.removeRange (--i, 2);
  12361. }
  12362. };
  12363. #endif // __JUCE_SPARSESET_JUCEHEADER__
  12364. /*** End of inlined file: juce_SparseSet.h ***/
  12365. #endif
  12366. #ifndef __JUCE_VALUE_JUCEHEADER__
  12367. /*** Start of inlined file: juce_Value.h ***/
  12368. #ifndef __JUCE_VALUE_JUCEHEADER__
  12369. #define __JUCE_VALUE_JUCEHEADER__
  12370. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  12371. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  12372. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  12373. /*** Start of inlined file: juce_CallbackMessage.h ***/
  12374. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12375. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12376. /*** Start of inlined file: juce_Message.h ***/
  12377. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  12378. #define __JUCE_MESSAGE_JUCEHEADER__
  12379. class MessageListener;
  12380. class MessageManager;
  12381. /** The base class for objects that can be delivered to a MessageListener.
  12382. The simplest Message object contains a few integer and pointer parameters
  12383. that the user can set, and this is enough for a lot of purposes. For passing more
  12384. complex data, subclasses of Message can also be used.
  12385. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12386. */
  12387. class JUCE_API Message : public ReferenceCountedObject
  12388. {
  12389. public:
  12390. /** Creates an uninitialised message.
  12391. The class's variables will also be left uninitialised.
  12392. */
  12393. Message() noexcept;
  12394. /** Creates a message object, filling in the member variables.
  12395. The corresponding public member variables will be set from the parameters
  12396. passed in.
  12397. */
  12398. Message (int intParameter1,
  12399. int intParameter2,
  12400. int intParameter3,
  12401. void* pointerParameter) noexcept;
  12402. /** Destructor. */
  12403. virtual ~Message();
  12404. // These values can be used for carrying simple data that the application needs to
  12405. // pass around. For more complex messages, just create a subclass.
  12406. int intParameter1; /**< user-defined integer value. */
  12407. int intParameter2; /**< user-defined integer value. */
  12408. int intParameter3; /**< user-defined integer value. */
  12409. void* pointerParameter; /**< user-defined pointer value. */
  12410. /** A typedef for pointers to messages. */
  12411. typedef ReferenceCountedObjectPtr <Message> Ptr;
  12412. private:
  12413. friend class MessageListener;
  12414. friend class MessageManager;
  12415. MessageListener* messageRecipient;
  12416. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12417. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12418. JUCE_DECLARE_NON_COPYABLE (Message);
  12419. };
  12420. #endif // __JUCE_MESSAGE_JUCEHEADER__
  12421. /*** End of inlined file: juce_Message.h ***/
  12422. /**
  12423. A message that calls a custom function when it gets delivered.
  12424. You can use this class to fire off actions that you want to be performed later
  12425. on the message thread.
  12426. Unlike other Message objects, these don't get sent to a MessageListener, you
  12427. just call the post() method to send them, and when they arrive, your
  12428. messageCallback() method will automatically be invoked.
  12429. Always create an instance of a CallbackMessage on the heap, as it will be
  12430. deleted automatically after the message has been delivered.
  12431. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12432. */
  12433. class JUCE_API CallbackMessage : public Message
  12434. {
  12435. public:
  12436. CallbackMessage() noexcept;
  12437. /** Destructor. */
  12438. ~CallbackMessage();
  12439. /** Called when the message is delivered.
  12440. You should implement this method and make it do whatever action you want
  12441. to perform.
  12442. Note that like all other messages, this object will be deleted immediately
  12443. after this method has been invoked.
  12444. */
  12445. virtual void messageCallback() = 0;
  12446. /** Instead of sending this message to a MessageListener, just call this method
  12447. to post it to the event queue.
  12448. After you've called this, this object will belong to the MessageManager,
  12449. which will delete it later. So make sure you don't delete the object yourself,
  12450. call post() more than once, or call post() on a stack-based obect!
  12451. */
  12452. void post();
  12453. private:
  12454. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12455. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12456. JUCE_DECLARE_NON_COPYABLE (CallbackMessage);
  12457. };
  12458. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12459. /*** End of inlined file: juce_CallbackMessage.h ***/
  12460. /**
  12461. Has a callback method that is triggered asynchronously.
  12462. This object allows an asynchronous callback function to be triggered, for
  12463. tasks such as coalescing multiple updates into a single callback later on.
  12464. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  12465. message thread calling handleAsyncUpdate() as soon as it can.
  12466. */
  12467. class JUCE_API AsyncUpdater
  12468. {
  12469. public:
  12470. /** Creates an AsyncUpdater object. */
  12471. AsyncUpdater();
  12472. /** Destructor.
  12473. If there are any pending callbacks when the object is deleted, these are lost.
  12474. */
  12475. virtual ~AsyncUpdater();
  12476. /** Causes the callback to be triggered at a later time.
  12477. This method returns immediately, having made sure that a callback
  12478. to the handleAsyncUpdate() method will occur as soon as possible.
  12479. If an update callback is already pending but hasn't happened yet, calls
  12480. to this method will be ignored.
  12481. It's thread-safe to call this method from any number of threads without
  12482. needing to worry about locking.
  12483. */
  12484. void triggerAsyncUpdate();
  12485. /** This will stop any pending updates from happening.
  12486. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  12487. callback happens, this will cancel the handleAsyncUpdate() callback.
  12488. Note that this method simply cancels the next callback - if a callback is already
  12489. in progress on a different thread, this won't block until it finishes, so there's
  12490. no guarantee that the callback isn't still running when you return from
  12491. */
  12492. void cancelPendingUpdate() noexcept;
  12493. /** If an update has been triggered and is pending, this will invoke it
  12494. synchronously.
  12495. Use this as a kind of "flush" operation - if an update is pending, the
  12496. handleAsyncUpdate() method will be called immediately; if no update is
  12497. pending, then nothing will be done.
  12498. Because this may invoke the callback, this method must only be called on
  12499. the main event thread.
  12500. */
  12501. void handleUpdateNowIfNeeded();
  12502. /** Returns true if there's an update callback in the pipeline. */
  12503. bool isUpdatePending() const noexcept;
  12504. /** Called back to do whatever your class needs to do.
  12505. This method is called by the message thread at the next convenient time
  12506. after the triggerAsyncUpdate() method has been called.
  12507. */
  12508. virtual void handleAsyncUpdate() = 0;
  12509. private:
  12510. ReferenceCountedObjectPtr<CallbackMessage> message;
  12511. Atomic<int>& getDeliveryFlag() const noexcept;
  12512. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  12513. };
  12514. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  12515. /*** End of inlined file: juce_AsyncUpdater.h ***/
  12516. /*** Start of inlined file: juce_ListenerList.h ***/
  12517. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  12518. #define __JUCE_LISTENERLIST_JUCEHEADER__
  12519. /**
  12520. Holds a set of objects and can invoke a member function callback on each object
  12521. in the set with a single call.
  12522. Use a ListenerList to manage a set of objects which need a callback, and you
  12523. can invoke a member function by simply calling call() or callChecked().
  12524. E.g.
  12525. @code
  12526. class MyListenerType
  12527. {
  12528. public:
  12529. void myCallbackMethod (int foo, bool bar);
  12530. };
  12531. ListenerList <MyListenerType> listeners;
  12532. listeners.add (someCallbackObjects...);
  12533. // This will invoke myCallbackMethod (1234, true) on each of the objects
  12534. // in the list...
  12535. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  12536. @endcode
  12537. If you add or remove listeners from the list during one of the callbacks - i.e. while
  12538. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  12539. will be mistakenly called after they've been removed, but it may mean that some of the
  12540. listeners could be called more than once, or not at all, depending on the list's order.
  12541. Sometimes, there's a chance that invoking one of the callbacks might result in the
  12542. list itself being deleted while it's still iterating - to survive this situation, you can
  12543. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  12544. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  12545. the list will check this after each callback to determine whether it should abort the
  12546. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  12547. which can be used to check when a Component has been deleted. See also
  12548. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  12549. */
  12550. template <class ListenerClass,
  12551. class ArrayType = Array <ListenerClass*> >
  12552. class ListenerList
  12553. {
  12554. // Horrible macros required to support VC6/7..
  12555. #ifndef DOXYGEN
  12556. #if JUCE_VC8_OR_EARLIER
  12557. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  12558. #define LL_PARAM(a) Q##a& param##a
  12559. #else
  12560. #define LL_TEMPLATE(a) typename P##a
  12561. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  12562. #endif
  12563. #endif
  12564. public:
  12565. /** Creates an empty list. */
  12566. ListenerList()
  12567. {
  12568. }
  12569. /** Destructor. */
  12570. ~ListenerList()
  12571. {
  12572. }
  12573. /** Adds a listener to the list.
  12574. A listener can only be added once, so if the listener is already in the list,
  12575. this method has no effect.
  12576. @see remove
  12577. */
  12578. void add (ListenerClass* const listenerToAdd)
  12579. {
  12580. // Listeners can't be null pointers!
  12581. jassert (listenerToAdd != nullptr);
  12582. if (listenerToAdd != nullptr)
  12583. listeners.addIfNotAlreadyThere (listenerToAdd);
  12584. }
  12585. /** Removes a listener from the list.
  12586. If the listener wasn't in the list, this has no effect.
  12587. */
  12588. void remove (ListenerClass* const listenerToRemove)
  12589. {
  12590. // Listeners can't be null pointers!
  12591. jassert (listenerToRemove != nullptr);
  12592. listeners.removeValue (listenerToRemove);
  12593. }
  12594. /** Returns the number of registered listeners. */
  12595. int size() const noexcept
  12596. {
  12597. return listeners.size();
  12598. }
  12599. /** Returns true if any listeners are registered. */
  12600. bool isEmpty() const noexcept
  12601. {
  12602. return listeners.size() == 0;
  12603. }
  12604. /** Clears the list. */
  12605. void clear()
  12606. {
  12607. listeners.clear();
  12608. }
  12609. /** Returns true if the specified listener has been added to the list. */
  12610. bool contains (ListenerClass* const listener) const noexcept
  12611. {
  12612. return listeners.contains (listener);
  12613. }
  12614. /** Calls a member function on each listener in the list, with no parameters. */
  12615. void call (void (ListenerClass::*callbackFunction) ())
  12616. {
  12617. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  12618. }
  12619. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  12620. See the class description for info about writing a bail-out checker. */
  12621. template <class BailOutCheckerType>
  12622. void callChecked (const BailOutCheckerType& bailOutChecker,
  12623. void (ListenerClass::*callbackFunction) ())
  12624. {
  12625. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12626. (iter.getListener()->*callbackFunction) ();
  12627. }
  12628. /** Calls a member function on each listener in the list, with 1 parameter. */
  12629. template <LL_TEMPLATE(1)>
  12630. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  12631. {
  12632. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12633. (iter.getListener()->*callbackFunction) (param1);
  12634. }
  12635. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  12636. See the class description for info about writing a bail-out checker. */
  12637. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  12638. void callChecked (const BailOutCheckerType& bailOutChecker,
  12639. void (ListenerClass::*callbackFunction) (P1),
  12640. LL_PARAM(1))
  12641. {
  12642. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12643. (iter.getListener()->*callbackFunction) (param1);
  12644. }
  12645. /** Calls a member function on each listener in the list, with 2 parameters. */
  12646. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12647. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  12648. LL_PARAM(1), LL_PARAM(2))
  12649. {
  12650. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12651. (iter.getListener()->*callbackFunction) (param1, param2);
  12652. }
  12653. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  12654. See the class description for info about writing a bail-out checker. */
  12655. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12656. void callChecked (const BailOutCheckerType& bailOutChecker,
  12657. void (ListenerClass::*callbackFunction) (P1, P2),
  12658. LL_PARAM(1), LL_PARAM(2))
  12659. {
  12660. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12661. (iter.getListener()->*callbackFunction) (param1, param2);
  12662. }
  12663. /** Calls a member function on each listener in the list, with 3 parameters. */
  12664. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12665. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12666. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12667. {
  12668. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12669. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12670. }
  12671. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  12672. See the class description for info about writing a bail-out checker. */
  12673. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12674. void callChecked (const BailOutCheckerType& bailOutChecker,
  12675. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12676. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12677. {
  12678. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12679. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12680. }
  12681. /** Calls a member function on each listener in the list, with 4 parameters. */
  12682. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12683. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12684. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12685. {
  12686. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12687. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12688. }
  12689. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  12690. See the class description for info about writing a bail-out checker. */
  12691. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12692. void callChecked (const BailOutCheckerType& bailOutChecker,
  12693. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12694. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12695. {
  12696. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12697. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12698. }
  12699. /** Calls a member function on each listener in the list, with 5 parameters. */
  12700. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12701. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12702. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12703. {
  12704. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12705. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12706. }
  12707. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  12708. See the class description for info about writing a bail-out checker. */
  12709. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12710. void callChecked (const BailOutCheckerType& bailOutChecker,
  12711. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12712. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12713. {
  12714. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12715. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12716. }
  12717. /** A dummy bail-out checker that always returns false.
  12718. See the ListenerList notes for more info about bail-out checkers.
  12719. */
  12720. class DummyBailOutChecker
  12721. {
  12722. public:
  12723. inline bool shouldBailOut() const noexcept { return false; }
  12724. };
  12725. /** Iterates the listeners in a ListenerList. */
  12726. template <class BailOutCheckerType, class ListType>
  12727. class Iterator
  12728. {
  12729. public:
  12730. Iterator (const ListType& list_)
  12731. : list (list_), index (list_.size())
  12732. {}
  12733. ~Iterator() {}
  12734. bool next()
  12735. {
  12736. if (index <= 0)
  12737. return false;
  12738. const int listSize = list.size();
  12739. if (--index < listSize)
  12740. return true;
  12741. index = listSize - 1;
  12742. return index >= 0;
  12743. }
  12744. bool next (const BailOutCheckerType& bailOutChecker)
  12745. {
  12746. return (! bailOutChecker.shouldBailOut()) && next();
  12747. }
  12748. typename ListType::ListenerType* getListener() const noexcept
  12749. {
  12750. return list.getListeners().getUnchecked (index);
  12751. }
  12752. private:
  12753. const ListType& list;
  12754. int index;
  12755. JUCE_DECLARE_NON_COPYABLE (Iterator);
  12756. };
  12757. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  12758. typedef ListenerClass ListenerType;
  12759. const ArrayType& getListeners() const noexcept { return listeners; }
  12760. private:
  12761. ArrayType listeners;
  12762. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  12763. #undef LL_TEMPLATE
  12764. #undef LL_PARAM
  12765. };
  12766. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  12767. /*** End of inlined file: juce_ListenerList.h ***/
  12768. /**
  12769. Represents a shared variant value.
  12770. A Value object contains a reference to a var object, and can get and set its value.
  12771. Listeners can be attached to be told when the value is changed.
  12772. The Value class is a wrapper around a shared, reference-counted underlying data
  12773. object - this means that multiple Value objects can all refer to the same piece of
  12774. data, allowing all of them to be notified when any of them changes it.
  12775. When you create a Value with its default constructor, it acts as a wrapper around a
  12776. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12777. you can map the Value onto any kind of underlying data.
  12778. */
  12779. class JUCE_API Value
  12780. {
  12781. public:
  12782. /** Creates an empty Value, containing a void var. */
  12783. Value();
  12784. /** Creates a Value that refers to the same value as another one.
  12785. Note that this doesn't make a copy of the other value - both this and the other
  12786. Value will share the same underlying value, so that when either one alters it, both
  12787. will see it change.
  12788. */
  12789. Value (const Value& other);
  12790. /** Creates a Value that is set to the specified value. */
  12791. explicit Value (const var& initialValue);
  12792. /** Destructor. */
  12793. ~Value();
  12794. /** Returns the current value. */
  12795. var getValue() const;
  12796. /** Returns the current value. */
  12797. operator var() const;
  12798. /** Returns the value as a string.
  12799. This is alternative to writing things like "myValue.getValue().toString()".
  12800. */
  12801. String toString() const;
  12802. /** Sets the current value.
  12803. You can also use operator= to set the value.
  12804. If there are any listeners registered, they will be notified of the
  12805. change asynchronously.
  12806. */
  12807. void setValue (const var& newValue);
  12808. /** Sets the current value.
  12809. This is the same as calling setValue().
  12810. If there are any listeners registered, they will be notified of the
  12811. change asynchronously.
  12812. */
  12813. Value& operator= (const var& newValue);
  12814. /** Makes this object refer to the same underlying ValueSource as another one.
  12815. Once this object has been connected to another one, changing either one
  12816. will update the other.
  12817. Existing listeners will still be registered after you call this method, and
  12818. they'll continue to receive messages when the new value changes.
  12819. */
  12820. void referTo (const Value& valueToReferTo);
  12821. /** Returns true if this value and the other one are references to the same value.
  12822. */
  12823. bool refersToSameSourceAs (const Value& other) const;
  12824. /** Compares two values.
  12825. This is a compare-by-value comparison, so is effectively the same as
  12826. saying (this->getValue() == other.getValue()).
  12827. */
  12828. bool operator== (const Value& other) const;
  12829. /** Compares two values.
  12830. This is a compare-by-value comparison, so is effectively the same as
  12831. saying (this->getValue() != other.getValue()).
  12832. */
  12833. bool operator!= (const Value& other) const;
  12834. /** Receives callbacks when a Value object changes.
  12835. @see Value::addListener
  12836. */
  12837. class JUCE_API Listener
  12838. {
  12839. public:
  12840. Listener() {}
  12841. virtual ~Listener() {}
  12842. /** Called when a Value object is changed.
  12843. Note that the Value object passed as a parameter may not be exactly the same
  12844. object that you registered the listener with - it might be a copy that refers
  12845. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12846. */
  12847. virtual void valueChanged (Value& value) = 0;
  12848. };
  12849. /** Adds a listener to receive callbacks when the value changes.
  12850. The listener is added to this specific Value object, and not to the shared
  12851. object that it refers to. When this object is deleted, all the listeners will
  12852. be lost, even if other references to the same Value still exist. So when you're
  12853. adding a listener, make sure that you add it to a ValueTree instance that will last
  12854. for as long as you need the listener. In general, you'd never want to add a listener
  12855. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12856. @see removeListener
  12857. */
  12858. void addListener (Listener* listener);
  12859. /** Removes a listener that was previously added with addListener(). */
  12860. void removeListener (Listener* listener);
  12861. /**
  12862. Used internally by the Value class as the base class for its shared value objects.
  12863. The Value class is essentially a reference-counted pointer to a shared instance
  12864. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12865. ValueSource classes to allow Value objects to represent your own custom data items.
  12866. */
  12867. class JUCE_API ValueSource : public SingleThreadedReferenceCountedObject,
  12868. public AsyncUpdater
  12869. {
  12870. public:
  12871. ValueSource();
  12872. virtual ~ValueSource();
  12873. /** Returns the current value of this object. */
  12874. virtual const var getValue() const = 0;
  12875. /** Changes the current value.
  12876. This must also trigger a change message if the value actually changes.
  12877. */
  12878. virtual void setValue (const var& newValue) = 0;
  12879. /** Delivers a change message to all the listeners that are registered with
  12880. this value.
  12881. If dispatchSynchronously is true, the method will call all the listeners
  12882. before returning; otherwise it'll dispatch a message and make the call later.
  12883. */
  12884. void sendChangeMessage (bool dispatchSynchronously);
  12885. protected:
  12886. friend class Value;
  12887. SortedSet <Value*> valuesWithListeners;
  12888. void handleAsyncUpdate();
  12889. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12890. };
  12891. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12892. explicit Value (ValueSource* valueSource);
  12893. /** Returns the ValueSource that this value is referring to. */
  12894. ValueSource& getValueSource() noexcept { return *value; }
  12895. private:
  12896. friend class ValueSource;
  12897. ReferenceCountedObjectPtr <ValueSource> value;
  12898. ListenerList <Listener> listeners;
  12899. void callListeners();
  12900. // This is disallowed to avoid confusion about whether it should
  12901. // do a by-value or by-reference copy.
  12902. Value& operator= (const Value& other);
  12903. };
  12904. /** Writes a Value to an OutputStream as a UTF8 string. */
  12905. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12906. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12907. typedef Value::Listener ValueListener;
  12908. #endif // __JUCE_VALUE_JUCEHEADER__
  12909. /*** End of inlined file: juce_Value.h ***/
  12910. #endif
  12911. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12912. /*** Start of inlined file: juce_ValueTree.h ***/
  12913. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12914. #define __JUCE_VALUETREE_JUCEHEADER__
  12915. /*** Start of inlined file: juce_UndoManager.h ***/
  12916. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12917. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12918. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12919. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12920. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12921. /*** Start of inlined file: juce_ChangeListener.h ***/
  12922. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12923. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12924. class ChangeBroadcaster;
  12925. /**
  12926. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12927. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12928. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12929. ChangeListener is used to receive these callbacks.
  12930. Note that the major difference between an ActionListener and a ChangeListener
  12931. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12932. callbacks, but ActionListeners perform one callback for every event posted.
  12933. @see ChangeBroadcaster, ActionListener
  12934. */
  12935. class JUCE_API ChangeListener
  12936. {
  12937. public:
  12938. /** Destructor. */
  12939. virtual ~ChangeListener() {}
  12940. /** Your subclass should implement this method to receive the callback.
  12941. @param source the ChangeBroadcaster that triggered the callback.
  12942. */
  12943. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12944. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12945. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12946. private: virtual int changeListenerCallback (void*) { return 0; }
  12947. #endif
  12948. };
  12949. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12950. /*** End of inlined file: juce_ChangeListener.h ***/
  12951. /**
  12952. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12953. @see ChangeListener
  12954. */
  12955. class JUCE_API ChangeBroadcaster
  12956. {
  12957. public:
  12958. /** Creates an ChangeBroadcaster. */
  12959. ChangeBroadcaster() noexcept;
  12960. /** Destructor. */
  12961. virtual ~ChangeBroadcaster();
  12962. /** Registers a listener to receive change callbacks from this broadcaster.
  12963. Trying to add a listener that's already on the list will have no effect.
  12964. */
  12965. void addChangeListener (ChangeListener* listener);
  12966. /** Unregisters a listener from the list.
  12967. If the listener isn't on the list, this won't have any effect.
  12968. */
  12969. void removeChangeListener (ChangeListener* listener);
  12970. /** Removes all listeners from the list. */
  12971. void removeAllChangeListeners();
  12972. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12973. The message will be delivered asynchronously by the main message thread, so this
  12974. method will return immediately. To call the listeners synchronously use
  12975. sendSynchronousChangeMessage().
  12976. */
  12977. void sendChangeMessage();
  12978. /** Sends a synchronous change message to all the registered listeners.
  12979. This will immediately call all the listeners that are registered. For thread-safety
  12980. reasons, you must only call this method on the main message thread.
  12981. @see dispatchPendingMessages
  12982. */
  12983. void sendSynchronousChangeMessage();
  12984. /** If a change message has been sent but not yet dispatched, this will call
  12985. sendSynchronousChangeMessage() to make the callback immediately.
  12986. For thread-safety reasons, you must only call this method on the main message thread.
  12987. */
  12988. void dispatchPendingMessages();
  12989. private:
  12990. class ChangeBroadcasterCallback : public AsyncUpdater
  12991. {
  12992. public:
  12993. ChangeBroadcasterCallback();
  12994. void handleAsyncUpdate();
  12995. ChangeBroadcaster* owner;
  12996. };
  12997. friend class ChangeBroadcasterCallback;
  12998. ChangeBroadcasterCallback callback;
  12999. ListenerList <ChangeListener> changeListeners;
  13000. void callListeners();
  13001. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  13002. };
  13003. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  13004. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  13005. /*** Start of inlined file: juce_UndoableAction.h ***/
  13006. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  13007. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  13008. /**
  13009. Used by the UndoManager class to store an action which can be done
  13010. and undone.
  13011. @see UndoManager
  13012. */
  13013. class JUCE_API UndoableAction
  13014. {
  13015. protected:
  13016. /** Creates an action. */
  13017. UndoableAction() noexcept {}
  13018. public:
  13019. /** Destructor. */
  13020. virtual ~UndoableAction() {}
  13021. /** Overridden by a subclass to perform the action.
  13022. This method is called by the UndoManager, and shouldn't be used directly by
  13023. applications.
  13024. Be careful not to make any calls in a perform() method that could call
  13025. recursively back into the UndoManager::perform() method
  13026. @returns true if the action could be performed.
  13027. @see UndoManager::perform
  13028. */
  13029. virtual bool perform() = 0;
  13030. /** Overridden by a subclass to undo the action.
  13031. This method is called by the UndoManager, and shouldn't be used directly by
  13032. applications.
  13033. Be careful not to make any calls in an undo() method that could call
  13034. recursively back into the UndoManager::perform() method
  13035. @returns true if the action could be undone without any errors.
  13036. @see UndoManager::perform
  13037. */
  13038. virtual bool undo() = 0;
  13039. /** Returns a value to indicate how much memory this object takes up.
  13040. Because the UndoManager keeps a list of UndoableActions, this is used
  13041. to work out how much space each one will take up, so that the UndoManager
  13042. can work out how many to keep.
  13043. The default value returned here is 10 - units are arbitrary and
  13044. don't have to be accurate.
  13045. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  13046. UndoManager::setMaxNumberOfStoredUnits
  13047. */
  13048. virtual int getSizeInUnits() { return 10; }
  13049. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  13050. If possible, this method should create and return a single action that does the same job as
  13051. this one followed by the supplied action.
  13052. If it's not possible to merge the two actions, the method should return zero.
  13053. */
  13054. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return nullptr; }
  13055. };
  13056. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  13057. /*** End of inlined file: juce_UndoableAction.h ***/
  13058. /**
  13059. Manages a list of undo/redo commands.
  13060. An UndoManager object keeps a list of past actions and can use these actions
  13061. to move backwards and forwards through an undo history.
  13062. To use it, create subclasses of UndoableAction which perform all the
  13063. actions you need, then when you need to actually perform an action, create one
  13064. and pass it to the UndoManager's perform() method.
  13065. The manager also uses the concept of 'transactions' to group the actions
  13066. together - all actions performed between calls to beginNewTransaction() are
  13067. grouped together and are all undone/redone as a group.
  13068. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  13069. when actions are performed or undone.
  13070. @see UndoableAction
  13071. */
  13072. class JUCE_API UndoManager : public ChangeBroadcaster
  13073. {
  13074. public:
  13075. /** Creates an UndoManager.
  13076. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13077. to indicate how much storage it takes up
  13078. (UndoableAction::getSizeInUnits()), so this
  13079. lets you specify the maximum total number of
  13080. units that the undomanager is allowed to
  13081. keep in memory before letting the older actions
  13082. drop off the end of the list.
  13083. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13084. that will be kept, even if this involves exceeding
  13085. the amount of space specified in maxNumberOfUnitsToKeep
  13086. */
  13087. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  13088. int minimumTransactionsToKeep = 30);
  13089. /** Destructor. */
  13090. ~UndoManager();
  13091. /** Deletes all stored actions in the list. */
  13092. void clearUndoHistory();
  13093. /** Returns the current amount of space to use for storing UndoableAction objects.
  13094. @see setMaxNumberOfStoredUnits
  13095. */
  13096. int getNumberOfUnitsTakenUpByStoredCommands() const;
  13097. /** Sets the amount of space that can be used for storing UndoableAction objects.
  13098. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13099. to indicate how much storage it takes up
  13100. (UndoableAction::getSizeInUnits()), so this
  13101. lets you specify the maximum total number of
  13102. units that the undomanager is allowed to
  13103. keep in memory before letting the older actions
  13104. drop off the end of the list.
  13105. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13106. that will be kept, even if this involves exceeding
  13107. the amount of space specified in maxNumberOfUnitsToKeep
  13108. @see getNumberOfUnitsTakenUpByStoredCommands
  13109. */
  13110. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  13111. int minimumTransactionsToKeep);
  13112. /** Performs an action and adds it to the undo history list.
  13113. @param action the action to perform - this will be deleted by the UndoManager
  13114. when no longer needed
  13115. @param actionName if this string is non-empty, the current transaction will be
  13116. given this name; if it's empty, the current transaction name will
  13117. be left unchanged. See setCurrentTransactionName()
  13118. @returns true if the command succeeds - see UndoableAction::perform
  13119. @see beginNewTransaction
  13120. */
  13121. bool perform (UndoableAction* action,
  13122. const String& actionName = String::empty);
  13123. /** Starts a new group of actions that together will be treated as a single transaction.
  13124. All actions that are passed to the perform() method between calls to this
  13125. method are grouped together and undone/redone together by a single call to
  13126. undo() or redo().
  13127. @param actionName a description of the transaction that is about to be
  13128. performed
  13129. */
  13130. void beginNewTransaction (const String& actionName = String::empty);
  13131. /** Changes the name stored for the current transaction.
  13132. Each transaction is given a name when the beginNewTransaction() method is
  13133. called, but this can be used to change that name without starting a new
  13134. transaction.
  13135. */
  13136. void setCurrentTransactionName (const String& newName);
  13137. /** Returns true if there's at least one action in the list to undo.
  13138. @see getUndoDescription, undo, canRedo
  13139. */
  13140. bool canUndo() const;
  13141. /** Returns the description of the transaction that would be next to get undone.
  13142. The description returned is the one that was passed into beginNewTransaction
  13143. before the set of actions was performed.
  13144. @see undo
  13145. */
  13146. String getUndoDescription() const;
  13147. /** Tries to roll-back the last transaction.
  13148. @returns true if the transaction can be undone, and false if it fails, or
  13149. if there aren't any transactions to undo
  13150. */
  13151. bool undo();
  13152. /** Tries to roll-back any actions that were added to the current transaction.
  13153. This will perform an undo() only if there are some actions in the undo list
  13154. that were added after the last call to beginNewTransaction().
  13155. This is useful because it lets you call beginNewTransaction(), then
  13156. perform an operation which may or may not actually perform some actions, and
  13157. then call this method to get rid of any actions that might have been done
  13158. without it rolling back the previous transaction if nothing was actually
  13159. done.
  13160. @returns true if any actions were undone.
  13161. */
  13162. bool undoCurrentTransactionOnly();
  13163. /** Returns a list of the UndoableAction objects that have been performed during the
  13164. transaction that is currently open.
  13165. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  13166. were to be called now.
  13167. The first item in the list is the earliest action performed.
  13168. */
  13169. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  13170. /** Returns the number of UndoableAction objects that have been performed during the
  13171. transaction that is currently open.
  13172. @see getActionsInCurrentTransaction
  13173. */
  13174. int getNumActionsInCurrentTransaction() const;
  13175. /** Returns true if there's at least one action in the list to redo.
  13176. @see getRedoDescription, redo, canUndo
  13177. */
  13178. bool canRedo() const;
  13179. /** Returns the description of the transaction that would be next to get redone.
  13180. The description returned is the one that was passed into beginNewTransaction
  13181. before the set of actions was performed.
  13182. @see redo
  13183. */
  13184. String getRedoDescription() const;
  13185. /** Tries to redo the last transaction that was undone.
  13186. @returns true if the transaction can be redone, and false if it fails, or
  13187. if there aren't any transactions to redo
  13188. */
  13189. bool redo();
  13190. private:
  13191. OwnedArray <OwnedArray <UndoableAction> > transactions;
  13192. StringArray transactionNames;
  13193. String currentTransactionName;
  13194. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  13195. bool newTransaction, reentrancyCheck;
  13196. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  13197. };
  13198. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  13199. /*** End of inlined file: juce_UndoManager.h ***/
  13200. /**
  13201. A powerful tree structure that can be used to hold free-form data, and which can
  13202. handle its own undo and redo behaviour.
  13203. A ValueTree contains a list of named properties as var objects, and also holds
  13204. any number of sub-trees.
  13205. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  13206. they're simply a lightweight reference to a shared data container. Creating a copy
  13207. of another ValueTree simply creates a new reference to the same underlying object - to
  13208. make a separate, deep copy of a tree you should explicitly call createCopy().
  13209. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  13210. and much of the structure of a ValueTree is similar to an XmlElement tree.
  13211. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  13212. contain text elements, the conversion works well and makes a good serialisation
  13213. format. They can also be serialised to a binary format, which is very fast and compact.
  13214. All the methods that change data take an optional UndoManager, which will be used
  13215. to track any changes to the object. For this to work, you have to be careful to
  13216. consistently always use the same UndoManager for all operations to any node inside
  13217. the tree.
  13218. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  13219. one tree to another, be careful to always remove it first, before adding it. This
  13220. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  13221. assertions if you try to do anything dangerous, but there are still plenty of ways it
  13222. could go wrong.
  13223. Listeners can be added to a ValueTree to be told when properies change and when
  13224. nodes are added or removed.
  13225. @see var, XmlElement
  13226. */
  13227. class JUCE_API ValueTree
  13228. {
  13229. public:
  13230. /** Creates an empty, invalid ValueTree.
  13231. A ValueTree that is created with this constructor can't actually be used for anything,
  13232. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  13233. To create a real one, use the constructor that takes a string.
  13234. @see ValueTree::invalid
  13235. */
  13236. ValueTree() noexcept;
  13237. /** Creates an empty ValueTree with the given type name.
  13238. Like an XmlElement, each ValueTree node has a type, which you can access with
  13239. getType() and hasType().
  13240. */
  13241. explicit ValueTree (const Identifier& type);
  13242. /** Creates a reference to another ValueTree. */
  13243. ValueTree (const ValueTree& other);
  13244. /** Makes this object reference another node. */
  13245. ValueTree& operator= (const ValueTree& other);
  13246. /** Destructor. */
  13247. ~ValueTree();
  13248. /** Returns true if both this and the other tree node refer to the same underlying structure.
  13249. Note that this isn't a value comparison - two independently-created trees which
  13250. contain identical data are not considered equal.
  13251. */
  13252. bool operator== (const ValueTree& other) const noexcept;
  13253. /** Returns true if this and the other node refer to different underlying structures.
  13254. Note that this isn't a value comparison - two independently-created trees which
  13255. contain identical data are not considered equal.
  13256. */
  13257. bool operator!= (const ValueTree& other) const noexcept;
  13258. /** Performs a deep comparison between the properties and children of two trees.
  13259. If all the properties and children of the two trees are the same (recursively), this
  13260. returns true.
  13261. The normal operator==() only checks whether two trees refer to the same shared data
  13262. structure, so use this method if you need to do a proper value comparison.
  13263. */
  13264. bool isEquivalentTo (const ValueTree& other) const;
  13265. /** Returns true if this node refers to some valid data.
  13266. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  13267. call to getChild().
  13268. */
  13269. bool isValid() const { return object != nullptr; }
  13270. /** Returns a deep copy of this tree and all its sub-nodes. */
  13271. ValueTree createCopy() const;
  13272. /** Returns the type of this node.
  13273. The type is specified when the ValueTree is created.
  13274. @see hasType
  13275. */
  13276. Identifier getType() const;
  13277. /** Returns true if the node has this type.
  13278. The comparison is case-sensitive.
  13279. */
  13280. bool hasType (const Identifier& typeName) const;
  13281. /** Returns the value of a named property.
  13282. If no such property has been set, this will return a void variant.
  13283. You can also use operator[] to get a property.
  13284. @see var, setProperty, hasProperty
  13285. */
  13286. const var& getProperty (const Identifier& name) const;
  13287. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  13288. If no such property has been set, this will return the value of defaultReturnValue.
  13289. You can also use operator[] and getProperty to get a property.
  13290. @see var, getProperty, setProperty, hasProperty
  13291. */
  13292. var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13293. /** Returns the value of a named property.
  13294. If no such property has been set, this will return a void variant. This is the same as
  13295. calling getProperty().
  13296. @see getProperty
  13297. */
  13298. const var& operator[] (const Identifier& name) const;
  13299. /** Changes a named property of the node.
  13300. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13301. so that this change can be undone.
  13302. @see var, getProperty, removeProperty
  13303. */
  13304. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  13305. /** Returns true if the node contains a named property. */
  13306. bool hasProperty (const Identifier& name) const;
  13307. /** Removes a property from the node.
  13308. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13309. so that this change can be undone.
  13310. */
  13311. void removeProperty (const Identifier& name, UndoManager* undoManager);
  13312. /** Removes all properties from the node.
  13313. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13314. so that this change can be undone.
  13315. */
  13316. void removeAllProperties (UndoManager* undoManager);
  13317. /** Returns the total number of properties that the node contains.
  13318. @see getProperty.
  13319. */
  13320. int getNumProperties() const;
  13321. /** Returns the identifier of the property with a given index.
  13322. @see getNumProperties
  13323. */
  13324. Identifier getPropertyName (int index) const;
  13325. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  13326. The Value object will maintain a reference to this tree, and will use the undo manager when
  13327. it needs to change the value. Attaching a Value::Listener to the value object will provide
  13328. callbacks whenever the property changes.
  13329. */
  13330. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  13331. /** Returns the number of child nodes belonging to this one.
  13332. @see getChild
  13333. */
  13334. int getNumChildren() const;
  13335. /** Returns one of this node's child nodes.
  13336. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  13337. whether a node is valid).
  13338. */
  13339. ValueTree getChild (int index) const;
  13340. /** Returns the first child node with the speficied type name.
  13341. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13342. whether a node is valid).
  13343. @see getOrCreateChildWithName
  13344. */
  13345. ValueTree getChildWithName (const Identifier& type) const;
  13346. /** Returns the first child node with the speficied type name, creating and adding
  13347. a child with this name if there wasn't already one there.
  13348. The only time this will return an invalid object is when the object that you're calling
  13349. the method on is itself invalid.
  13350. @see getChildWithName
  13351. */
  13352. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13353. /** Looks for the first child node that has the speficied property value.
  13354. This will scan the child nodes in order, until it finds one that has property that matches
  13355. the specified value.
  13356. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13357. whether a node is valid).
  13358. */
  13359. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13360. /** Adds a child to this node.
  13361. Make sure that the child is removed from any former parent node before calling this, or
  13362. you'll hit an assertion.
  13363. If the index is < 0 or greater than the current number of child nodes, the new node will
  13364. be added at the end of the list.
  13365. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13366. so that this change can be undone.
  13367. */
  13368. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  13369. /** Removes the specified child from this node's child-list.
  13370. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13371. so that this change can be undone.
  13372. */
  13373. void removeChild (const ValueTree& child, UndoManager* undoManager);
  13374. /** Removes a child from this node's child-list.
  13375. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13376. so that this change can be undone.
  13377. */
  13378. void removeChild (int childIndex, UndoManager* undoManager);
  13379. /** Removes all child-nodes from this node.
  13380. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13381. so that this change can be undone.
  13382. */
  13383. void removeAllChildren (UndoManager* undoManager);
  13384. /** Moves one of the children to a different index.
  13385. This will move the child to a specified index, shuffling along any intervening
  13386. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  13387. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  13388. @param currentIndex the index of the item to be moved. If this isn't a
  13389. valid index, then nothing will be done
  13390. @param newIndex the index at which you'd like this item to end up. If this
  13391. is less than zero, the value will be moved to the end
  13392. of the list
  13393. @param undoManager the optional UndoManager to use to store this transaction
  13394. */
  13395. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  13396. /** Returns true if this node is anywhere below the specified parent node.
  13397. This returns true if the node is a child-of-a-child, as well as a direct child.
  13398. */
  13399. bool isAChildOf (const ValueTree& possibleParent) const;
  13400. /** Returns the index of a child item in this parent.
  13401. If the child isn't found, this returns -1.
  13402. */
  13403. int indexOf (const ValueTree& child) const;
  13404. /** Returns the parent node that contains this one.
  13405. If the node has no parent, this will return an invalid node. (See isValid() to find out
  13406. whether a node is valid).
  13407. */
  13408. ValueTree getParent() const;
  13409. /** Returns one of this node's siblings in its parent's child list.
  13410. The delta specifies how far to move through the list, so a value of 1 would return the node
  13411. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  13412. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  13413. */
  13414. ValueTree getSibling (int delta) const;
  13415. /** Creates an XmlElement that holds a complete image of this node and all its children.
  13416. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  13417. be used to recreate a similar node by calling fromXml()
  13418. @see fromXml
  13419. */
  13420. XmlElement* createXml() const;
  13421. /** Tries to recreate a node from its XML representation.
  13422. This isn't designed to cope with random XML data - for a sensible result, it should only
  13423. be fed XML that was created by the createXml() method.
  13424. */
  13425. static ValueTree fromXml (const XmlElement& xml);
  13426. /** Stores this tree (and all its children) in a binary format.
  13427. Once written, the data can be read back with readFromStream().
  13428. It's much faster to load/save your tree in binary form than as XML, but
  13429. obviously isn't human-readable.
  13430. */
  13431. void writeToStream (OutputStream& output);
  13432. /** Reloads a tree from a stream that was written with writeToStream(). */
  13433. static ValueTree readFromStream (InputStream& input);
  13434. /** Reloads a tree from a data block that was written with writeToStream(). */
  13435. static ValueTree readFromData (const void* data, size_t numBytes);
  13436. /** Listener class for events that happen to a ValueTree.
  13437. To get events from a ValueTree, make your class implement this interface, and use
  13438. ValueTree::addListener() and ValueTree::removeListener() to register it.
  13439. */
  13440. class JUCE_API Listener
  13441. {
  13442. public:
  13443. /** Destructor. */
  13444. virtual ~Listener() {}
  13445. /** This method is called when a property of this node (or of one of its sub-nodes) has
  13446. changed.
  13447. The tree parameter indicates which tree has had its property changed, and the property
  13448. parameter indicates the property.
  13449. Note that when you register a listener to a tree, it will receive this callback for
  13450. property changes in that tree, and also for any of its children, (recursively, at any depth).
  13451. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13452. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  13453. */
  13454. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  13455. const Identifier& property) = 0;
  13456. /** This method is called when a child sub-tree is added.
  13457. Note that when you register a listener to a tree, it will receive this callback for
  13458. child changes in both that tree and any of its children, (recursively, at any depth).
  13459. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13460. just check the parentTree parameter to make sure it's the one that you're interested in.
  13461. */
  13462. virtual void valueTreeChildAdded (ValueTree& parentTree,
  13463. ValueTree& childWhichHasBeenAdded) = 0;
  13464. /** This method is called when a child sub-tree is removed.
  13465. Note that when you register a listener to a tree, it will receive this callback for
  13466. child changes in both that tree and any of its children, (recursively, at any depth).
  13467. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13468. just check the parentTree parameter to make sure it's the one that you're interested in.
  13469. */
  13470. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  13471. ValueTree& childWhichHasBeenRemoved) = 0;
  13472. /** This method is called when a tree's children have been re-shuffled.
  13473. Note that when you register a listener to a tree, it will receive this callback for
  13474. child changes in both that tree and any of its children, (recursively, at any depth).
  13475. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13476. just check the parameter to make sure it's the tree that you're interested in.
  13477. */
  13478. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  13479. /** This method is called when a tree has been added or removed from a parent node.
  13480. This callback happens when the tree to which the listener was registered is added or
  13481. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  13482. the listener is registered, and not to any of its children.
  13483. */
  13484. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  13485. };
  13486. /** Adds a listener to receive callbacks when this node is changed.
  13487. The listener is added to this specific ValueTree object, and not to the shared
  13488. object that it refers to. When this object is deleted, all the listeners will
  13489. be lost, even if other references to the same ValueTree still exist. And if you
  13490. use the operator= to make this refer to a different ValueTree, any listeners will
  13491. begin listening to changes to the new tree instead of the old one.
  13492. When you're adding a listener, make sure that you add it to a ValueTree instance that
  13493. will last for as long as you need the listener. In general, you'd never want to add a
  13494. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  13495. @see removeListener
  13496. */
  13497. void addListener (Listener* listener);
  13498. /** Removes a listener that was previously added with addListener(). */
  13499. void removeListener (Listener* listener);
  13500. /** This method uses a comparator object to sort the tree's children into order.
  13501. The object provided must have a method of the form:
  13502. @code
  13503. int compareElements (const ValueTree& first, const ValueTree& second);
  13504. @endcode
  13505. ..and this method must return:
  13506. - a value of < 0 if the first comes before the second
  13507. - a value of 0 if the two objects are equivalent
  13508. - a value of > 0 if the second comes before the first
  13509. To improve performance, the compareElements() method can be declared as static or const.
  13510. @param comparator the comparator to use for comparing elements.
  13511. @param undoManager optional UndoManager for storing the changes
  13512. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  13513. equivalent will be kept in the order in which they currently appear in the array.
  13514. This is slower to perform, but may be important in some cases. If it's false, a
  13515. faster algorithm is used, but equivalent elements may be rearranged.
  13516. */
  13517. template <typename ElementComparator>
  13518. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  13519. {
  13520. if (object != nullptr)
  13521. {
  13522. ReferenceCountedArray <SharedObject> sortedList (object->children);
  13523. ComparatorAdapter <ElementComparator> adapter (comparator);
  13524. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  13525. object->reorderChildren (sortedList, undoManager);
  13526. }
  13527. }
  13528. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  13529. This invalid object is equivalent to ValueTree created with its default constructor.
  13530. */
  13531. static const ValueTree invalid;
  13532. private:
  13533. class SetPropertyAction; friend class SetPropertyAction;
  13534. class AddOrRemoveChildAction; friend class AddOrRemoveChildAction;
  13535. class MoveChildAction; friend class MoveChildAction;
  13536. class JUCE_API SharedObject : public SingleThreadedReferenceCountedObject
  13537. {
  13538. public:
  13539. explicit SharedObject (const Identifier& type);
  13540. SharedObject (const SharedObject& other);
  13541. ~SharedObject();
  13542. const Identifier type;
  13543. NamedValueSet properties;
  13544. ReferenceCountedArray <SharedObject> children;
  13545. SortedSet <ValueTree*> valueTreesWithListeners;
  13546. SharedObject* parent;
  13547. void sendPropertyChangeMessage (const Identifier& property);
  13548. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  13549. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  13550. void sendChildAddedMessage (ValueTree child);
  13551. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  13552. void sendChildRemovedMessage (ValueTree child);
  13553. void sendChildOrderChangedMessage (ValueTree& parent);
  13554. void sendChildOrderChangedMessage();
  13555. void sendParentChangeMessage();
  13556. const var& getProperty (const Identifier& name) const;
  13557. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13558. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  13559. bool hasProperty (const Identifier& name) const;
  13560. void removeProperty (const Identifier& name, UndoManager*);
  13561. void removeAllProperties (UndoManager*);
  13562. bool isAChildOf (const SharedObject* possibleParent) const;
  13563. int indexOf (const ValueTree& child) const;
  13564. ValueTree getChildWithName (const Identifier& type) const;
  13565. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13566. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13567. void addChild (SharedObject* child, int index, UndoManager*);
  13568. void removeChild (int childIndex, UndoManager*);
  13569. void removeAllChildren (UndoManager*);
  13570. void moveChild (int currentIndex, int newIndex, UndoManager*);
  13571. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  13572. bool isEquivalentTo (const SharedObject& other) const;
  13573. XmlElement* createXml() const;
  13574. private:
  13575. SharedObject& operator= (const SharedObject&);
  13576. JUCE_LEAK_DETECTOR (SharedObject);
  13577. };
  13578. template <typename ElementComparator>
  13579. class ComparatorAdapter
  13580. {
  13581. public:
  13582. ComparatorAdapter (ElementComparator& comparator_) noexcept : comparator (comparator_) {}
  13583. int compareElements (SharedObject* const first, SharedObject* const second)
  13584. {
  13585. return comparator.compareElements (ValueTree (first), ValueTree (second));
  13586. }
  13587. private:
  13588. ElementComparator& comparator;
  13589. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  13590. };
  13591. friend class SharedObject;
  13592. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  13593. SharedObjectPtr object;
  13594. ListenerList <Listener> listeners;
  13595. #if JUCE_MSVC && ! DOXYGEN
  13596. public: // (workaround for VC6)
  13597. #endif
  13598. explicit ValueTree (SharedObject*);
  13599. };
  13600. #endif // __JUCE_VALUETREE_JUCEHEADER__
  13601. /*** End of inlined file: juce_ValueTree.h ***/
  13602. #endif
  13603. #ifndef __JUCE_VARIANT_JUCEHEADER__
  13604. #endif
  13605. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13606. /*** Start of inlined file: juce_FileLogger.h ***/
  13607. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13608. #define __JUCE_FILELOGGER_JUCEHEADER__
  13609. /**
  13610. A simple implemenation of a Logger that writes to a file.
  13611. @see Logger
  13612. */
  13613. class JUCE_API FileLogger : public Logger
  13614. {
  13615. public:
  13616. /** Creates a FileLogger for a given file.
  13617. @param fileToWriteTo the file that to use - new messages will be appended
  13618. to the file. If the file doesn't exist, it will be created,
  13619. along with any parent directories that are needed.
  13620. @param welcomeMessage when opened, the logger will write a header to the log, along
  13621. with the current date and time, and this welcome message
  13622. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  13623. but is larger than this number of bytes, then the start of the
  13624. file will be truncated to keep the size down. This prevents a log
  13625. file getting ridiculously large over time. The file will be truncated
  13626. at a new-line boundary. If this value is less than zero, no size limit
  13627. will be imposed; if it's zero, the file will always be deleted. Note that
  13628. the size is only checked once when this object is created - any logging
  13629. that is done later will be appended without any checking
  13630. */
  13631. FileLogger (const File& fileToWriteTo,
  13632. const String& welcomeMessage,
  13633. const int maxInitialFileSizeBytes = 128 * 1024);
  13634. /** Destructor. */
  13635. ~FileLogger();
  13636. void logMessage (const String& message);
  13637. File getLogFile() const { return logFile; }
  13638. /** Helper function to create a log file in the correct place for this platform.
  13639. On Windows this will return a logger with a path such as:
  13640. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  13641. On the Mac it'll create something like:
  13642. ~/Library/Logs/[logFileName]
  13643. The method might return 0 if the file can't be created for some reason.
  13644. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  13645. it's best to use the something like the name of your application here.
  13646. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  13647. call it "log.txt" because if it goes in a directory with logs
  13648. from other applications (as it will do on the Mac) then no-one
  13649. will know which one is yours!
  13650. @param welcomeMessage a message that will be written to the log when it's opened.
  13651. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  13652. */
  13653. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  13654. const String& logFileName,
  13655. const String& welcomeMessage,
  13656. const int maxInitialFileSizeBytes = 128 * 1024);
  13657. private:
  13658. File logFile;
  13659. CriticalSection logLock;
  13660. void trimFileSize (int maxFileSizeBytes) const;
  13661. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  13662. };
  13663. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  13664. /*** End of inlined file: juce_FileLogger.h ***/
  13665. #endif
  13666. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13667. /*** Start of inlined file: juce_Initialisation.h ***/
  13668. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13669. #define __JUCE_INITIALISATION_JUCEHEADER__
  13670. /** Initialises Juce's GUI classes.
  13671. If you're embedding Juce into an application that uses its own event-loop rather
  13672. than using the START_JUCE_APPLICATION macro, call this function before making any
  13673. Juce calls, to make sure things are initialised correctly.
  13674. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13675. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13676. @see shutdownJuce_GUI()
  13677. */
  13678. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  13679. /** Clears up any static data being used by Juce's GUI classes.
  13680. If you're embedding Juce into an application that uses its own event-loop rather
  13681. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  13682. code to clean up any juce objects that might be lying around.
  13683. @see initialiseJuce_GUI()
  13684. */
  13685. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  13686. /** A utility object that helps you initialise and shutdown Juce correctly
  13687. using an RAII pattern.
  13688. When an instance of this class is created, it calls initialiseJuce_GUI(),
  13689. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  13690. make sure that these functions are matched correctly.
  13691. This class is particularly handy to use at the beginning of a console app's
  13692. main() function, because it'll take care of shutting down whenever you return
  13693. from the main() call.
  13694. @see ScopedJuceInitialiser_NonGUI
  13695. */
  13696. class ScopedJuceInitialiser_GUI
  13697. {
  13698. public:
  13699. /** The constructor simply calls initialiseJuce_GUI(). */
  13700. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  13701. /** The destructor simply calls shutdownJuce_GUI(). */
  13702. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  13703. };
  13704. /*
  13705. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  13706. AppSubClass is the name of a class derived from JUCEApplication.
  13707. See the JUCEApplication class documentation (juce_Application.h) for more details.
  13708. */
  13709. #if JUCE_ANDROID
  13710. #define START_JUCE_APPLICATION(AppClass) \
  13711. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  13712. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  13713. #define START_JUCE_APPLICATION(AppClass) \
  13714. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13715. int main (int argc, char* argv[]) \
  13716. { \
  13717. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13718. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  13719. }
  13720. #elif JUCE_WINDOWS
  13721. #ifdef _CONSOLE
  13722. #define START_JUCE_APPLICATION(AppClass) \
  13723. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13724. int main (int, char* argv[]) \
  13725. { \
  13726. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13727. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13728. }
  13729. #elif ! defined (_AFXDLL)
  13730. #ifdef _WINDOWS_
  13731. #define START_JUCE_APPLICATION(AppClass) \
  13732. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13733. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  13734. { \
  13735. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13736. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13737. }
  13738. #else
  13739. #define START_JUCE_APPLICATION(AppClass) \
  13740. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13741. int __stdcall WinMain (int, int, const char*, int) \
  13742. { \
  13743. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13744. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13745. }
  13746. #endif
  13747. #endif
  13748. #endif
  13749. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13750. /*** End of inlined file: juce_Initialisation.h ***/
  13751. #endif
  13752. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13753. #endif
  13754. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13755. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13756. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13757. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13758. /** A timer for measuring performance of code and dumping the results to a file.
  13759. e.g. @code
  13760. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13761. for (;;)
  13762. {
  13763. pc.start();
  13764. doSomethingFishy();
  13765. pc.stop();
  13766. }
  13767. @endcode
  13768. In this example, the time of each period between calling start/stop will be
  13769. measured and averaged over 50 runs, and the results printed to a file
  13770. every 50 times round the loop.
  13771. */
  13772. class JUCE_API PerformanceCounter
  13773. {
  13774. public:
  13775. /** Creates a PerformanceCounter object.
  13776. @param counterName the name used when printing out the statistics
  13777. @param runsPerPrintout the number of start/stop iterations before calling
  13778. printStatistics()
  13779. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13780. the results are just written to the debugger output
  13781. */
  13782. PerformanceCounter (const String& counterName,
  13783. int runsPerPrintout = 100,
  13784. const File& loggingFile = File::nonexistent);
  13785. /** Destructor. */
  13786. ~PerformanceCounter();
  13787. /** Starts timing.
  13788. @see stop
  13789. */
  13790. void start();
  13791. /** Stops timing and prints out the results.
  13792. The number of iterations before doing a printout of the
  13793. results is set in the constructor.
  13794. @see start
  13795. */
  13796. void stop();
  13797. /** Dumps the current metrics to the debugger output and to a file.
  13798. As well as using Logger::outputDebugString to print the results,
  13799. this will write then to the file specified in the constructor (if
  13800. this was valid).
  13801. */
  13802. void printStatistics();
  13803. private:
  13804. String name;
  13805. int numRuns, runsPerPrint;
  13806. double totalTime;
  13807. int64 started;
  13808. File outputFile;
  13809. };
  13810. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13811. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13812. #endif
  13813. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13814. #endif
  13815. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13816. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13817. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13818. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13819. /**
  13820. A collection of miscellaneous platform-specific utilities.
  13821. */
  13822. class JUCE_API PlatformUtilities
  13823. {
  13824. public:
  13825. /** Plays the operating system's default alert 'beep' sound. */
  13826. static void beep();
  13827. /** Tries to launch the system's default reader for a given file or URL. */
  13828. static bool openDocument (const String& documentURL, const String& parameters);
  13829. /** Tries to launch the system's default email app to let the user create an email.
  13830. */
  13831. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13832. const String& emailSubject,
  13833. const String& bodyText,
  13834. const StringArray& filesToAttach);
  13835. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13836. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13837. static const String cfStringToJuceString (CFStringRef cfString);
  13838. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13839. static CFStringRef juceStringToCFString (const String& s);
  13840. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13841. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13842. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13843. static const String makePathFromFSRef (FSRef* file);
  13844. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13845. their precomposed equivalents.
  13846. */
  13847. static const String convertToPrecomposedUnicode (const String& s);
  13848. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13849. static OSType getTypeOfFile (const String& filename);
  13850. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13851. static bool isBundle (const String& filename);
  13852. /** MAC ONLY - Adds an item to the dock */
  13853. static void addItemToDock (const File& file);
  13854. /** MAC ONLY - Returns the current OS version number.
  13855. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13856. */
  13857. static int getOSXMinorVersionNumber();
  13858. #endif
  13859. #if JUCE_WINDOWS || DOXYGEN
  13860. // Some registry helper functions:
  13861. /** WIN32 ONLY - Returns a string from the registry.
  13862. The path is a string for the entire path of a value in the registry,
  13863. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13864. */
  13865. static const String getRegistryValue (const String& regValuePath,
  13866. const String& defaultValue = String::empty);
  13867. /** WIN32 ONLY - Sets a registry value as a string.
  13868. This will take care of creating any groups needed to get to the given
  13869. registry value.
  13870. */
  13871. static void setRegistryValue (const String& regValuePath,
  13872. const String& value);
  13873. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13874. static bool registryValueExists (const String& regValuePath);
  13875. /** WIN32 ONLY - Deletes a registry value. */
  13876. static void deleteRegistryValue (const String& regValuePath);
  13877. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13878. static void deleteRegistryKey (const String& regKeyPath);
  13879. /** WIN32 ONLY - Creates a file association in the registry.
  13880. This lets you set the exe that should be launched by a given file extension.
  13881. @param fileExtension the file extension to associate, including the
  13882. initial dot, e.g. ".txt"
  13883. @param symbolicDescription a space-free short token to identify the file type
  13884. @param fullDescription a human-readable description of the file type
  13885. @param targetExecutable the executable that should be launched
  13886. @param iconResourceNumber the icon that gets displayed for the file type will be
  13887. found by looking up this resource number in the
  13888. executable. Pass 0 here to not use an icon
  13889. */
  13890. static void registerFileAssociation (const String& fileExtension,
  13891. const String& symbolicDescription,
  13892. const String& fullDescription,
  13893. const File& targetExecutable,
  13894. int iconResourceNumber);
  13895. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13896. In a normal Juce application this will be set to the module handle
  13897. of the application executable.
  13898. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13899. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13900. to set the correct module handle in your DllMain() function, because
  13901. the win32 system relies on the correct instance handle when opening windows.
  13902. */
  13903. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() noexcept;
  13904. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13905. @see getCurrentModuleInstanceHandle()
  13906. */
  13907. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) noexcept;
  13908. /** WIN32 ONLY - Gets the command-line params as a string.
  13909. This is needed to avoid unicode problems with the argc type params.
  13910. */
  13911. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13912. #endif
  13913. /** Clears the floating point unit's flags.
  13914. Only has an effect under win32, currently.
  13915. */
  13916. static void fpuReset();
  13917. #if JUCE_LINUX || JUCE_WINDOWS
  13918. /** Loads a dynamically-linked library into the process's address space.
  13919. @param pathOrFilename the platform-dependent name and search path
  13920. @returns a handle which can be used by getProcedureEntryPoint(), or
  13921. zero if it fails.
  13922. @see freeDynamicLibrary, getProcedureEntryPoint
  13923. */
  13924. static void* loadDynamicLibrary (const String& pathOrFilename);
  13925. /** Frees a dynamically-linked library.
  13926. @param libraryHandle a handle created by loadDynamicLibrary
  13927. @see loadDynamicLibrary, getProcedureEntryPoint
  13928. */
  13929. static void freeDynamicLibrary (void* libraryHandle);
  13930. /** Finds a procedure call in a dynamically-linked library.
  13931. @param libraryHandle a library handle returned by loadDynamicLibrary
  13932. @param procedureName the name of the procedure call to try to load
  13933. @returns a pointer to the function if found, or 0 if it fails
  13934. @see loadDynamicLibrary
  13935. */
  13936. static void* getProcedureEntryPoint (void* libraryHandle,
  13937. const String& procedureName);
  13938. #endif
  13939. private:
  13940. PlatformUtilities();
  13941. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13942. };
  13943. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13944. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII. */
  13945. class JUCE_API ScopedAutoReleasePool
  13946. {
  13947. public:
  13948. ScopedAutoReleasePool();
  13949. ~ScopedAutoReleasePool();
  13950. private:
  13951. void* pool;
  13952. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13953. };
  13954. /** A macro that can be used to easily declare a local ScopedAutoReleasePool object for RAII-based obj-C autoreleasing. */
  13955. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool JUCE_JOIN_MACRO (autoReleasePool_, __LINE__);
  13956. #else
  13957. #define JUCE_AUTORELEASEPOOL
  13958. #endif
  13959. #if JUCE_LINUX
  13960. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13961. using an RAII approach.
  13962. */
  13963. class ScopedXLock
  13964. {
  13965. public:
  13966. /** Creating a ScopedXLock object locks the X display.
  13967. This uses XLockDisplay() to grab the display that Juce is using.
  13968. */
  13969. ScopedXLock();
  13970. /** Deleting a ScopedXLock object unlocks the X display.
  13971. This calls XUnlockDisplay() to release the lock.
  13972. */
  13973. ~ScopedXLock();
  13974. };
  13975. #endif
  13976. #if JUCE_MAC
  13977. /**
  13978. A wrapper class for picking up events from an Apple IR remote control device.
  13979. To use it, just create a subclass of this class, implementing the buttonPressed()
  13980. callback, then call start() and stop() to start or stop receiving events.
  13981. */
  13982. class JUCE_API AppleRemoteDevice
  13983. {
  13984. public:
  13985. AppleRemoteDevice();
  13986. virtual ~AppleRemoteDevice();
  13987. /** The set of buttons that may be pressed.
  13988. @see buttonPressed
  13989. */
  13990. enum ButtonType
  13991. {
  13992. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13993. playButton, /**< The play button. */
  13994. plusButton, /**< The plus or volume-up button. */
  13995. minusButton, /**< The minus or volume-down button. */
  13996. rightButton, /**< The right button (if it's held for a short time). */
  13997. leftButton, /**< The left button (if it's held for a short time). */
  13998. rightButton_Long, /**< The right button (if it's held for a long time). */
  13999. leftButton_Long, /**< The menu button (if it's held for a long time). */
  14000. menuButton_Long, /**< The menu button (if it's held for a long time). */
  14001. playButtonSleepMode,
  14002. switched
  14003. };
  14004. /** Override this method to receive the callback about a button press.
  14005. The callback will happen on the application's message thread.
  14006. Some buttons trigger matching up and down events, in which the isDown parameter
  14007. will be true and then false. Others only send a single event when the
  14008. button is pressed.
  14009. */
  14010. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  14011. /** Starts the device running and responding to events.
  14012. Returns true if it managed to open the device.
  14013. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  14014. and will not be available to any other part of the system. If
  14015. false, it will be shared with other apps.
  14016. @see stop
  14017. */
  14018. bool start (bool inExclusiveMode);
  14019. /** Stops the device running.
  14020. @see start
  14021. */
  14022. void stop();
  14023. /** Returns true if the device has been started successfully.
  14024. */
  14025. bool isActive() const;
  14026. /** Returns the ID number of the remote, if it has sent one.
  14027. */
  14028. int getRemoteId() const { return remoteId; }
  14029. /** @internal */
  14030. void handleCallbackInternal();
  14031. private:
  14032. void* device;
  14033. void* queue;
  14034. int remoteId;
  14035. bool open (bool openInExclusiveMode);
  14036. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  14037. };
  14038. #endif
  14039. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  14040. /*** End of inlined file: juce_PlatformUtilities.h ***/
  14041. #endif
  14042. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  14043. #endif
  14044. #ifndef __JUCE_RESULT_JUCEHEADER__
  14045. #endif
  14046. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  14047. /*** Start of inlined file: juce_Singleton.h ***/
  14048. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  14049. #define __JUCE_SINGLETON_JUCEHEADER__
  14050. /**
  14051. Macro to declare member variables and methods for a singleton class.
  14052. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  14053. to the class's definition.
  14054. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  14055. implementation code.
  14056. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  14057. destructor, in case it is deleted by other means than deleteInstance()
  14058. Clients can then call the static method MyClass::getInstance() to get a pointer
  14059. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  14060. no instance currently exists.
  14061. e.g. @code
  14062. class MySingleton
  14063. {
  14064. public:
  14065. MySingleton()
  14066. {
  14067. }
  14068. ~MySingleton()
  14069. {
  14070. // this ensures that no dangling pointers are left when the
  14071. // singleton is deleted.
  14072. clearSingletonInstance();
  14073. }
  14074. juce_DeclareSingleton (MySingleton, false)
  14075. };
  14076. juce_ImplementSingleton (MySingleton)
  14077. // example of usage:
  14078. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  14079. ...
  14080. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  14081. @endcode
  14082. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14083. than once during the process's lifetime - i.e. after you've created and deleted the
  14084. object, getInstance() will refuse to create another one. This can be useful to stop
  14085. objects being accidentally re-created during your app's shutdown code.
  14086. If you know that your object will only be created and deleted by a single thread, you
  14087. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  14088. of this one.
  14089. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  14090. */
  14091. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  14092. \
  14093. static classname* _singletonInstance; \
  14094. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  14095. \
  14096. static classname* JUCE_CALLTYPE getInstance() \
  14097. { \
  14098. if (_singletonInstance == nullptr) \
  14099. {\
  14100. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14101. \
  14102. if (_singletonInstance == nullptr) \
  14103. { \
  14104. static bool alreadyInside = false; \
  14105. static bool createdOnceAlready = false; \
  14106. \
  14107. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14108. jassert (! problem); \
  14109. if (! problem) \
  14110. { \
  14111. createdOnceAlready = true; \
  14112. alreadyInside = true; \
  14113. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14114. alreadyInside = false; \
  14115. \
  14116. _singletonInstance = newObject; \
  14117. } \
  14118. } \
  14119. } \
  14120. \
  14121. return _singletonInstance; \
  14122. } \
  14123. \
  14124. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() noexcept\
  14125. { \
  14126. return _singletonInstance; \
  14127. } \
  14128. \
  14129. static void JUCE_CALLTYPE deleteInstance() \
  14130. { \
  14131. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14132. if (_singletonInstance != nullptr) \
  14133. { \
  14134. classname* const old = _singletonInstance; \
  14135. _singletonInstance = nullptr; \
  14136. delete old; \
  14137. } \
  14138. } \
  14139. \
  14140. void clearSingletonInstance() noexcept\
  14141. { \
  14142. if (_singletonInstance == this) \
  14143. _singletonInstance = nullptr; \
  14144. }
  14145. /** This is a counterpart to the juce_DeclareSingleton macro.
  14146. After adding the juce_DeclareSingleton to the class definition, this macro has
  14147. to be used in the cpp file.
  14148. */
  14149. #define juce_ImplementSingleton(classname) \
  14150. \
  14151. classname* classname::_singletonInstance = nullptr; \
  14152. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  14153. /**
  14154. Macro to declare member variables and methods for a singleton class.
  14155. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  14156. section to make access to it thread-safe. If you know that your object will
  14157. only ever be created or deleted by a single thread, then this is a
  14158. more efficient version to use.
  14159. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14160. than once during the process's lifetime - i.e. after you've created and deleted the
  14161. object, getInstance() will refuse to create another one. This can be useful to stop
  14162. objects being accidentally re-created during your app's shutdown code.
  14163. See the documentation for juce_DeclareSingleton for more information about
  14164. how to use it, the only difference being that you have to use
  14165. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14166. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  14167. */
  14168. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  14169. \
  14170. static classname* _singletonInstance; \
  14171. \
  14172. static classname* getInstance() \
  14173. { \
  14174. if (_singletonInstance == nullptr) \
  14175. { \
  14176. static bool alreadyInside = false; \
  14177. static bool createdOnceAlready = false; \
  14178. \
  14179. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14180. jassert (! problem); \
  14181. if (! problem) \
  14182. { \
  14183. createdOnceAlready = true; \
  14184. alreadyInside = true; \
  14185. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14186. alreadyInside = false; \
  14187. \
  14188. _singletonInstance = newObject; \
  14189. } \
  14190. } \
  14191. \
  14192. return _singletonInstance; \
  14193. } \
  14194. \
  14195. static inline classname* getInstanceWithoutCreating() noexcept\
  14196. { \
  14197. return _singletonInstance; \
  14198. } \
  14199. \
  14200. static void deleteInstance() \
  14201. { \
  14202. if (_singletonInstance != nullptr) \
  14203. { \
  14204. classname* const old = _singletonInstance; \
  14205. _singletonInstance = nullptr; \
  14206. delete old; \
  14207. } \
  14208. } \
  14209. \
  14210. void clearSingletonInstance() noexcept\
  14211. { \
  14212. if (_singletonInstance == this) \
  14213. _singletonInstance = nullptr; \
  14214. }
  14215. /**
  14216. Macro to declare member variables and methods for a singleton class.
  14217. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  14218. for recursion or repeated instantiation. It's intended for use as a lightweight
  14219. version of a singleton, where you're using it in very straightforward
  14220. circumstances and don't need the extra checking.
  14221. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  14222. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  14223. See the documentation for juce_DeclareSingleton for more information about
  14224. how to use it, the only difference being that you have to use
  14225. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14226. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  14227. */
  14228. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  14229. \
  14230. static classname* _singletonInstance; \
  14231. \
  14232. static classname* getInstance() \
  14233. { \
  14234. if (_singletonInstance == nullptr) \
  14235. _singletonInstance = new classname(); \
  14236. \
  14237. return _singletonInstance; \
  14238. } \
  14239. \
  14240. static inline classname* getInstanceWithoutCreating() noexcept\
  14241. { \
  14242. return _singletonInstance; \
  14243. } \
  14244. \
  14245. static void deleteInstance() \
  14246. { \
  14247. if (_singletonInstance != nullptr) \
  14248. { \
  14249. classname* const old = _singletonInstance; \
  14250. _singletonInstance = nullptr; \
  14251. delete old; \
  14252. } \
  14253. } \
  14254. \
  14255. void clearSingletonInstance() noexcept\
  14256. { \
  14257. if (_singletonInstance == this) \
  14258. _singletonInstance = nullptr; \
  14259. }
  14260. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  14261. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  14262. to the class definition, this macro has to be used somewhere in the cpp file.
  14263. */
  14264. #define juce_ImplementSingleton_SingleThreaded(classname) \
  14265. \
  14266. classname* classname::_singletonInstance = nullptr;
  14267. #endif // __JUCE_SINGLETON_JUCEHEADER__
  14268. /*** End of inlined file: juce_Singleton.h ***/
  14269. #endif
  14270. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  14271. #endif
  14272. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14273. /*** Start of inlined file: juce_SystemStats.h ***/
  14274. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14275. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  14276. /**
  14277. Contains methods for finding out about the current hardware and OS configuration.
  14278. */
  14279. class JUCE_API SystemStats
  14280. {
  14281. public:
  14282. /** Returns the current version of JUCE,
  14283. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  14284. */
  14285. static const String getJUCEVersion();
  14286. /** The set of possible results of the getOperatingSystemType() method.
  14287. */
  14288. enum OperatingSystemType
  14289. {
  14290. UnknownOS = 0,
  14291. MacOSX = 0x1000,
  14292. Linux = 0x2000,
  14293. Android = 0x3000,
  14294. Win95 = 0x4001,
  14295. Win98 = 0x4002,
  14296. WinNT351 = 0x4103,
  14297. WinNT40 = 0x4104,
  14298. Win2000 = 0x4105,
  14299. WinXP = 0x4106,
  14300. WinVista = 0x4107,
  14301. Windows7 = 0x4108,
  14302. Windows = 0x4000, /**< To test whether any version of Windows is running,
  14303. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  14304. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  14305. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  14306. };
  14307. /** Returns the type of operating system we're running on.
  14308. @returns one of the values from the OperatingSystemType enum.
  14309. @see getOperatingSystemName
  14310. */
  14311. static OperatingSystemType getOperatingSystemType();
  14312. /** Returns the name of the type of operating system we're running on.
  14313. @returns a string describing the OS type.
  14314. @see getOperatingSystemType
  14315. */
  14316. static const String getOperatingSystemName();
  14317. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  14318. */
  14319. static bool isOperatingSystem64Bit();
  14320. /** Returns the current user's name, if available.
  14321. @see getFullUserName()
  14322. */
  14323. static const String getLogonName();
  14324. /** Returns the current user's full name, if available.
  14325. On some OSes, this may just return the same value as getLogonName().
  14326. @see getLogonName()
  14327. */
  14328. static const String getFullUserName();
  14329. /** Returns the host-name of the computer. */
  14330. static const String getComputerName();
  14331. // CPU and memory information..
  14332. /** Returns the approximate CPU speed.
  14333. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  14334. what year you're reading this...)
  14335. */
  14336. static int getCpuSpeedInMegaherz();
  14337. /** Returns a string to indicate the CPU vendor.
  14338. Might not be known on some systems.
  14339. */
  14340. static const String getCpuVendor();
  14341. /** Checks whether Intel MMX instructions are available. */
  14342. static bool hasMMX() noexcept { return getCPUFlags().hasMMX; }
  14343. /** Checks whether Intel SSE instructions are available. */
  14344. static bool hasSSE() noexcept { return getCPUFlags().hasSSE; }
  14345. /** Checks whether Intel SSE2 instructions are available. */
  14346. static bool hasSSE2() noexcept { return getCPUFlags().hasSSE2; }
  14347. /** Checks whether AMD 3DNOW instructions are available. */
  14348. static bool has3DNow() noexcept { return getCPUFlags().has3DNow; }
  14349. /** Returns the number of CPUs. */
  14350. static int getNumCpus() noexcept { return getCPUFlags().numCpus; }
  14351. /** Finds out how much RAM is in the machine.
  14352. @returns the approximate number of megabytes of memory, or zero if
  14353. something goes wrong when finding out.
  14354. */
  14355. static int getMemorySizeInMegabytes();
  14356. /** Returns the system page-size.
  14357. This is only used by programmers with beards.
  14358. */
  14359. static int getPageSize();
  14360. private:
  14361. struct CPUFlags
  14362. {
  14363. CPUFlags();
  14364. int numCpus;
  14365. bool hasMMX : 1;
  14366. bool hasSSE : 1;
  14367. bool hasSSE2 : 1;
  14368. bool has3DNow : 1;
  14369. };
  14370. SystemStats();
  14371. static const CPUFlags& getCPUFlags();
  14372. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  14373. };
  14374. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  14375. /*** End of inlined file: juce_SystemStats.h ***/
  14376. #endif
  14377. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  14378. #endif
  14379. #ifndef __JUCE_TIME_JUCEHEADER__
  14380. #endif
  14381. #ifndef __JUCE_UUID_JUCEHEADER__
  14382. /*** Start of inlined file: juce_Uuid.h ***/
  14383. #ifndef __JUCE_UUID_JUCEHEADER__
  14384. #define __JUCE_UUID_JUCEHEADER__
  14385. /**
  14386. A universally unique 128-bit identifier.
  14387. This class generates very random unique numbers based on the system time
  14388. and MAC addresses if any are available. It's extremely unlikely that two identical
  14389. UUIDs would ever be created by chance.
  14390. The class includes methods for saving the ID as a string or as raw binary data.
  14391. */
  14392. class JUCE_API Uuid
  14393. {
  14394. public:
  14395. /** Creates a new unique ID. */
  14396. Uuid();
  14397. /** Destructor. */
  14398. ~Uuid() noexcept;
  14399. /** Creates a copy of another UUID. */
  14400. Uuid (const Uuid& other);
  14401. /** Copies another UUID. */
  14402. Uuid& operator= (const Uuid& other);
  14403. /** Returns true if the ID is zero. */
  14404. bool isNull() const noexcept;
  14405. /** Compares two UUIDs. */
  14406. bool operator== (const Uuid& other) const;
  14407. /** Compares two UUIDs. */
  14408. bool operator!= (const Uuid& other) const;
  14409. /** Returns a stringified version of this UUID.
  14410. A Uuid object can later be reconstructed from this string using operator= or
  14411. the constructor that takes a string parameter.
  14412. @returns a 32 character hex string.
  14413. */
  14414. String toString() const;
  14415. /** Creates an ID from an encoded string version.
  14416. @see toString
  14417. */
  14418. Uuid (const String& uuidString);
  14419. /** Copies from a stringified UUID.
  14420. The string passed in should be one that was created with the toString() method.
  14421. */
  14422. Uuid& operator= (const String& uuidString);
  14423. /** Returns a pointer to the internal binary representation of the ID.
  14424. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  14425. the constructor or operator= method that takes an array of uint8s.
  14426. */
  14427. const uint8* getRawData() const noexcept { return value.asBytes; }
  14428. /** Creates a UUID from a 16-byte array.
  14429. @see getRawData
  14430. */
  14431. Uuid (const uint8* rawData);
  14432. /** Sets this UUID from 16-bytes of raw data. */
  14433. Uuid& operator= (const uint8* rawData);
  14434. private:
  14435. #ifndef DOXYGEN
  14436. union
  14437. {
  14438. uint8 asBytes [16];
  14439. int asInt[4];
  14440. int64 asInt64[2];
  14441. } value;
  14442. #endif
  14443. JUCE_LEAK_DETECTOR (Uuid);
  14444. };
  14445. #endif // __JUCE_UUID_JUCEHEADER__
  14446. /*** End of inlined file: juce_Uuid.h ***/
  14447. #endif
  14448. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14449. /*** Start of inlined file: juce_BlowFish.h ***/
  14450. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14451. #define __JUCE_BLOWFISH_JUCEHEADER__
  14452. /**
  14453. BlowFish encryption class.
  14454. */
  14455. class JUCE_API BlowFish
  14456. {
  14457. public:
  14458. /** Creates an object that can encode/decode based on the specified key.
  14459. The key data can be up to 72 bytes long.
  14460. */
  14461. BlowFish (const void* keyData, int keyBytes);
  14462. /** Creates a copy of another blowfish object. */
  14463. BlowFish (const BlowFish& other);
  14464. /** Copies another blowfish object. */
  14465. BlowFish& operator= (const BlowFish& other);
  14466. /** Destructor. */
  14467. ~BlowFish();
  14468. /** Encrypts a pair of 32-bit integers. */
  14469. void encrypt (uint32& data1, uint32& data2) const noexcept;
  14470. /** Decrypts a pair of 32-bit integers. */
  14471. void decrypt (uint32& data1, uint32& data2) const noexcept;
  14472. private:
  14473. uint32 p[18];
  14474. HeapBlock <uint32> s[4];
  14475. uint32 F (uint32 x) const noexcept;
  14476. JUCE_LEAK_DETECTOR (BlowFish);
  14477. };
  14478. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  14479. /*** End of inlined file: juce_BlowFish.h ***/
  14480. #endif
  14481. #ifndef __JUCE_MD5_JUCEHEADER__
  14482. /*** Start of inlined file: juce_MD5.h ***/
  14483. #ifndef __JUCE_MD5_JUCEHEADER__
  14484. #define __JUCE_MD5_JUCEHEADER__
  14485. /**
  14486. MD5 checksum class.
  14487. Create one of these with a block of source data or a string, and it calculates the
  14488. MD5 checksum of that data.
  14489. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  14490. */
  14491. class JUCE_API MD5
  14492. {
  14493. public:
  14494. /** Creates a null MD5 object. */
  14495. MD5();
  14496. /** Creates a copy of another MD5. */
  14497. MD5 (const MD5& other);
  14498. /** Copies another MD5. */
  14499. MD5& operator= (const MD5& other);
  14500. /** Creates a checksum for a block of binary data. */
  14501. explicit MD5 (const MemoryBlock& data);
  14502. /** Creates a checksum for a block of binary data. */
  14503. MD5 (const void* data, size_t numBytes);
  14504. /** Creates a checksum for a string.
  14505. Note that this operates on the string as a block of unicode characters, so the
  14506. result you get will differ from the value you'd get if the string was treated
  14507. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  14508. of this method with a checksum created by a different framework, which may have
  14509. used a different encoding.
  14510. */
  14511. explicit MD5 (const String& text);
  14512. /** Creates a checksum for the input from a stream.
  14513. This will read up to the given number of bytes from the stream, and produce the
  14514. checksum of that. If the number of bytes to read is negative, it'll read
  14515. until the stream is exhausted.
  14516. */
  14517. MD5 (InputStream& input, int64 numBytesToRead = -1);
  14518. /** Creates a checksum for a file. */
  14519. explicit MD5 (const File& file);
  14520. /** Destructor. */
  14521. ~MD5();
  14522. /** Returns the checksum as a 16-byte block of data. */
  14523. MemoryBlock getRawChecksumData() const;
  14524. /** Returns the checksum as a 32-digit hex string. */
  14525. String toHexString() const;
  14526. /** Compares this to another MD5. */
  14527. bool operator== (const MD5& other) const;
  14528. /** Compares this to another MD5. */
  14529. bool operator!= (const MD5& other) const;
  14530. private:
  14531. uint8 result [16];
  14532. struct ProcessContext
  14533. {
  14534. uint8 buffer [64];
  14535. uint32 state [4];
  14536. uint32 count [2];
  14537. ProcessContext();
  14538. void processBlock (const void* data, size_t dataSize);
  14539. void transform (const void* buffer);
  14540. void finish (void* result);
  14541. };
  14542. void processStream (InputStream&, int64 numBytesToRead);
  14543. JUCE_LEAK_DETECTOR (MD5);
  14544. };
  14545. #endif // __JUCE_MD5_JUCEHEADER__
  14546. /*** End of inlined file: juce_MD5.h ***/
  14547. #endif
  14548. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14549. /*** Start of inlined file: juce_Primes.h ***/
  14550. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14551. #define __JUCE_PRIMES_JUCEHEADER__
  14552. /*** Start of inlined file: juce_BigInteger.h ***/
  14553. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  14554. #define __JUCE_BIGINTEGER_JUCEHEADER__
  14555. class MemoryBlock;
  14556. /**
  14557. An arbitrarily large integer class.
  14558. A BigInteger can be used in a similar way to a normal integer, but has no size
  14559. limit (except for memory and performance constraints).
  14560. Negative values are possible, but the value isn't stored as 2s-complement, so
  14561. be careful if you use negative values and look at the values of individual bits.
  14562. */
  14563. class JUCE_API BigInteger
  14564. {
  14565. public:
  14566. /** Creates an empty BigInteger */
  14567. BigInteger();
  14568. /** Creates a BigInteger containing an integer value in its low bits.
  14569. The low 32 bits of the number are initialised with this value.
  14570. */
  14571. BigInteger (uint32 value);
  14572. /** Creates a BigInteger containing an integer value in its low bits.
  14573. The low 32 bits of the number are initialised with the absolute value
  14574. passed in, and its sign is set to reflect the sign of the number.
  14575. */
  14576. BigInteger (int32 value);
  14577. /** Creates a BigInteger containing an integer value in its low bits.
  14578. The low 64 bits of the number are initialised with the absolute value
  14579. passed in, and its sign is set to reflect the sign of the number.
  14580. */
  14581. BigInteger (int64 value);
  14582. /** Creates a copy of another BigInteger. */
  14583. BigInteger (const BigInteger& other);
  14584. /** Destructor. */
  14585. ~BigInteger();
  14586. /** Copies another BigInteger onto this one. */
  14587. BigInteger& operator= (const BigInteger& other);
  14588. /** Swaps the internal contents of this with another object. */
  14589. void swapWith (BigInteger& other) noexcept;
  14590. /** Returns the value of a specified bit in the number.
  14591. If the index is out-of-range, the result will be false.
  14592. */
  14593. bool operator[] (int bit) const noexcept;
  14594. /** Returns true if no bits are set. */
  14595. bool isZero() const noexcept;
  14596. /** Returns true if the value is 1. */
  14597. bool isOne() const noexcept;
  14598. /** Attempts to get the lowest bits of the value as an integer.
  14599. If the value is bigger than the integer limits, this will return only the lower bits.
  14600. */
  14601. int toInteger() const noexcept;
  14602. /** Resets the value to 0. */
  14603. void clear();
  14604. /** Clears a particular bit in the number. */
  14605. void clearBit (int bitNumber) noexcept;
  14606. /** Sets a specified bit to 1. */
  14607. void setBit (int bitNumber);
  14608. /** Sets or clears a specified bit. */
  14609. void setBit (int bitNumber, bool shouldBeSet);
  14610. /** Sets a range of bits to be either on or off.
  14611. @param startBit the first bit to change
  14612. @param numBits the number of bits to change
  14613. @param shouldBeSet whether to turn these bits on or off
  14614. */
  14615. void setRange (int startBit, int numBits, bool shouldBeSet);
  14616. /** Inserts a bit an a given position, shifting up any bits above it. */
  14617. void insertBit (int bitNumber, bool shouldBeSet);
  14618. /** Returns a range of bits as a new BigInteger.
  14619. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  14620. @see getBitRangeAsInt
  14621. */
  14622. BigInteger getBitRange (int startBit, int numBits) const;
  14623. /** Returns a range of bits as an integer value.
  14624. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  14625. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  14626. getBitRange().
  14627. */
  14628. int getBitRangeAsInt (int startBit, int numBits) const noexcept;
  14629. /** Sets a range of bits to an integer value.
  14630. Copies the given integer onto a range of bits, starting at startBit,
  14631. and using up to numBits of the available bits.
  14632. */
  14633. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  14634. /** Shifts a section of bits left or right.
  14635. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  14636. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  14637. */
  14638. void shiftBits (int howManyBitsLeft, int startBit);
  14639. /** Returns the total number of set bits in the value. */
  14640. int countNumberOfSetBits() const noexcept;
  14641. /** Looks for the index of the next set bit after a given starting point.
  14642. This searches from startIndex (inclusive) upwards for the first set bit,
  14643. and returns its index. If no set bits are found, it returns -1.
  14644. */
  14645. int findNextSetBit (int startIndex = 0) const noexcept;
  14646. /** Looks for the index of the next clear bit after a given starting point.
  14647. This searches from startIndex (inclusive) upwards for the first clear bit,
  14648. and returns its index.
  14649. */
  14650. int findNextClearBit (int startIndex = 0) const noexcept;
  14651. /** Returns the index of the highest set bit in the number.
  14652. If the value is zero, this will return -1.
  14653. */
  14654. int getHighestBit() const noexcept;
  14655. // All the standard arithmetic ops...
  14656. BigInteger& operator+= (const BigInteger& other);
  14657. BigInteger& operator-= (const BigInteger& other);
  14658. BigInteger& operator*= (const BigInteger& other);
  14659. BigInteger& operator/= (const BigInteger& other);
  14660. BigInteger& operator|= (const BigInteger& other);
  14661. BigInteger& operator&= (const BigInteger& other);
  14662. BigInteger& operator^= (const BigInteger& other);
  14663. BigInteger& operator%= (const BigInteger& other);
  14664. BigInteger& operator<<= (int numBitsToShift);
  14665. BigInteger& operator>>= (int numBitsToShift);
  14666. BigInteger& operator++();
  14667. BigInteger& operator--();
  14668. BigInteger operator++ (int);
  14669. BigInteger operator-- (int);
  14670. BigInteger operator-() const;
  14671. BigInteger operator+ (const BigInteger& other) const;
  14672. BigInteger operator- (const BigInteger& other) const;
  14673. BigInteger operator* (const BigInteger& other) const;
  14674. BigInteger operator/ (const BigInteger& other) const;
  14675. BigInteger operator| (const BigInteger& other) const;
  14676. BigInteger operator& (const BigInteger& other) const;
  14677. BigInteger operator^ (const BigInteger& other) const;
  14678. BigInteger operator% (const BigInteger& other) const;
  14679. BigInteger operator<< (int numBitsToShift) const;
  14680. BigInteger operator>> (int numBitsToShift) const;
  14681. bool operator== (const BigInteger& other) const noexcept;
  14682. bool operator!= (const BigInteger& other) const noexcept;
  14683. bool operator< (const BigInteger& other) const noexcept;
  14684. bool operator<= (const BigInteger& other) const noexcept;
  14685. bool operator> (const BigInteger& other) const noexcept;
  14686. bool operator>= (const BigInteger& other) const noexcept;
  14687. /** Does a signed comparison of two BigIntegers.
  14688. Return values are:
  14689. - 0 if the numbers are the same
  14690. - < 0 if this number is smaller than the other
  14691. - > 0 if this number is bigger than the other
  14692. */
  14693. int compare (const BigInteger& other) const noexcept;
  14694. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14695. Return values are:
  14696. - 0 if the numbers are the same
  14697. - < 0 if this number is smaller than the other
  14698. - > 0 if this number is bigger than the other
  14699. */
  14700. int compareAbsolute (const BigInteger& other) const noexcept;
  14701. /** Divides this value by another one and returns the remainder.
  14702. This number is divided by other, leaving the quotient in this number,
  14703. with the remainder being copied to the other BigInteger passed in.
  14704. */
  14705. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14706. /** Returns the largest value that will divide both this value and the one passed-in.
  14707. */
  14708. BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14709. /** Performs a combined exponent and modulo operation.
  14710. This BigInteger's value becomes (this ^ exponent) % modulus.
  14711. */
  14712. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14713. /** Performs an inverse modulo on the value.
  14714. i.e. the result is (this ^ -1) mod (modulus).
  14715. */
  14716. void inverseModulo (const BigInteger& modulus);
  14717. /** Returns true if the value is less than zero.
  14718. @see setNegative, negate
  14719. */
  14720. bool isNegative() const noexcept;
  14721. /** Changes the sign of the number to be positive or negative.
  14722. @see isNegative, negate
  14723. */
  14724. void setNegative (bool shouldBeNegative) noexcept;
  14725. /** Inverts the sign of the number.
  14726. @see isNegative, setNegative
  14727. */
  14728. void negate() noexcept;
  14729. /** Converts the number to a string.
  14730. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14731. If minimumNumCharacters is greater than 0, the returned string will be
  14732. padded with leading zeros to reach at least that length.
  14733. */
  14734. String toString (int base, int minimumNumCharacters = 1) const;
  14735. /** Reads the numeric value from a string.
  14736. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14737. Any invalid characters will be ignored.
  14738. */
  14739. void parseString (const String& text, int base);
  14740. /** Turns the number into a block of binary data.
  14741. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14742. of the number, and so on.
  14743. @see loadFromMemoryBlock
  14744. */
  14745. MemoryBlock toMemoryBlock() const;
  14746. /** Converts a block of raw data into a number.
  14747. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14748. of the number, and so on.
  14749. @see toMemoryBlock
  14750. */
  14751. void loadFromMemoryBlock (const MemoryBlock& data);
  14752. private:
  14753. HeapBlock <uint32> values;
  14754. int numValues, highestBit;
  14755. bool negative;
  14756. void ensureSize (int numVals);
  14757. void shiftLeft (int bits, int startBit);
  14758. void shiftRight (int bits, int startBit);
  14759. static BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14760. static inline int bitToIndex (const int bit) noexcept { return bit >> 5; }
  14761. static inline uint32 bitToMask (const int bit) noexcept { return 1 << (bit & 31); }
  14762. JUCE_LEAK_DETECTOR (BigInteger);
  14763. };
  14764. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14765. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14766. #ifndef DOXYGEN
  14767. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14768. typedef BigInteger BitArray;
  14769. #endif
  14770. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14771. /*** End of inlined file: juce_BigInteger.h ***/
  14772. /**
  14773. Prime number creation class.
  14774. This class contains static methods for generating and testing prime numbers.
  14775. @see BigInteger
  14776. */
  14777. class JUCE_API Primes
  14778. {
  14779. public:
  14780. /** Creates a random prime number with a given bit-length.
  14781. The certainty parameter specifies how many iterations to use when testing
  14782. for primality. A safe value might be anything over about 20-30.
  14783. The randomSeeds parameter lets you optionally pass it a set of values with
  14784. which to seed the random number generation, improving the security of the
  14785. keys generated.
  14786. */
  14787. static BigInteger createProbablePrime (int bitLength,
  14788. int certainty,
  14789. const int* randomSeeds = 0,
  14790. int numRandomSeeds = 0);
  14791. /** Tests a number to see if it's prime.
  14792. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14793. whether the number is prime.
  14794. The certainty parameter specifies how many iterations to use when testing - a
  14795. safe value might be anything over about 20-30.
  14796. */
  14797. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14798. private:
  14799. Primes();
  14800. JUCE_DECLARE_NON_COPYABLE (Primes);
  14801. };
  14802. #endif // __JUCE_PRIMES_JUCEHEADER__
  14803. /*** End of inlined file: juce_Primes.h ***/
  14804. #endif
  14805. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14806. /*** Start of inlined file: juce_RSAKey.h ***/
  14807. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14808. #define __JUCE_RSAKEY_JUCEHEADER__
  14809. /**
  14810. RSA public/private key-pair encryption class.
  14811. An object of this type makes up one half of a public/private RSA key pair. Use the
  14812. createKeyPair() method to create a matching pair for encoding/decoding.
  14813. */
  14814. class JUCE_API RSAKey
  14815. {
  14816. public:
  14817. /** Creates a null key object.
  14818. Initialise a pair of objects for use with the createKeyPair() method.
  14819. */
  14820. RSAKey();
  14821. /** Loads a key from an encoded string representation.
  14822. This reloads a key from a string created by the toString() method.
  14823. */
  14824. explicit RSAKey (const String& stringRepresentation);
  14825. /** Destructor. */
  14826. ~RSAKey();
  14827. bool operator== (const RSAKey& other) const noexcept;
  14828. bool operator!= (const RSAKey& other) const noexcept;
  14829. /** Turns the key into a string representation.
  14830. This can be reloaded using the constructor that takes a string.
  14831. */
  14832. String toString() const;
  14833. /** Encodes or decodes a value.
  14834. Call this on the public key object to encode some data, then use the matching
  14835. private key object to decode it.
  14836. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14837. initialised correctly.
  14838. NOTE: This method dumbly applies this key to this data. If you encode some data
  14839. and then try to decode it with a key that doesn't match, this method will still
  14840. happily do its job and return true, but the result won't be what you were expecting.
  14841. It's your responsibility to check that the result is what you wanted.
  14842. */
  14843. bool applyToValue (BigInteger& value) const;
  14844. /** Creates a public/private key-pair.
  14845. Each key will perform one-way encryption that can only be reversed by
  14846. using the other key.
  14847. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14848. sizes are more secure, but this method will take longer to execute.
  14849. The randomSeeds parameter lets you optionally pass it a set of values with
  14850. which to seed the random number generation, improving the security of the
  14851. keys generated. If you supply these, make sure you provide more than 2 values,
  14852. and the more your provide, the better the security.
  14853. */
  14854. static void createKeyPair (RSAKey& publicKey,
  14855. RSAKey& privateKey,
  14856. int numBits,
  14857. const int* randomSeeds = nullptr,
  14858. int numRandomSeeds = 0);
  14859. protected:
  14860. BigInteger part1, part2;
  14861. private:
  14862. static BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14863. JUCE_LEAK_DETECTOR (RSAKey);
  14864. };
  14865. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14866. /*** End of inlined file: juce_RSAKey.h ***/
  14867. #endif
  14868. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14869. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14870. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14871. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14872. /**
  14873. Searches through a the files in a directory, returning each file that is found.
  14874. A DirectoryIterator will search through a directory and its subdirectories using
  14875. a wildcard filepattern match.
  14876. If you may be finding a large number of files, this is better than
  14877. using File::findChildFiles() because it doesn't block while it finds them
  14878. all, and this is more memory-efficient.
  14879. It can also guess how far it's got using a wildly inaccurate algorithm.
  14880. */
  14881. class JUCE_API DirectoryIterator
  14882. {
  14883. public:
  14884. /** Creates a DirectoryIterator for a given directory.
  14885. After creating one of these, call its next() method to get the
  14886. first file - e.g. @code
  14887. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14888. while (iter.next())
  14889. {
  14890. File theFileItFound (iter.getFile());
  14891. ... etc
  14892. }
  14893. @endcode
  14894. @param directory the directory to search in
  14895. @param isRecursive whether all the subdirectories should also be searched
  14896. @param wildCard the file pattern to match
  14897. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14898. whether to look for files, directories, or both.
  14899. */
  14900. DirectoryIterator (const File& directory,
  14901. bool isRecursive,
  14902. const String& wildCard = "*",
  14903. int whatToLookFor = File::findFiles);
  14904. /** Destructor. */
  14905. ~DirectoryIterator();
  14906. /** Moves the iterator along to the next file.
  14907. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14908. false if there are no more matching files.
  14909. */
  14910. bool next();
  14911. /** Moves the iterator along to the next file, and returns various properties of that file.
  14912. If you need to find out details about the file, it's more efficient to call this method than
  14913. to call the normal next() method and then find out the details afterwards.
  14914. All the parameters are optional, so pass null pointers for any items that you're not
  14915. interested in.
  14916. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14917. false if there are no more matching files. If it returns false, then none of the
  14918. parameters will be filled-in.
  14919. */
  14920. bool next (bool* isDirectory,
  14921. bool* isHidden,
  14922. int64* fileSize,
  14923. Time* modTime,
  14924. Time* creationTime,
  14925. bool* isReadOnly);
  14926. /** Returns the file that the iterator is currently pointing at.
  14927. The result of this call is only valid after a call to next() has returned true.
  14928. */
  14929. const File& getFile() const;
  14930. /** Returns a guess of how far through the search the iterator has got.
  14931. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14932. very accurate.
  14933. */
  14934. float getEstimatedProgress() const;
  14935. private:
  14936. class NativeIterator
  14937. {
  14938. public:
  14939. NativeIterator (const File& directory, const String& wildCard);
  14940. ~NativeIterator();
  14941. bool next (String& filenameFound,
  14942. bool* isDirectory, bool* isHidden, int64* fileSize,
  14943. Time* modTime, Time* creationTime, bool* isReadOnly);
  14944. class Pimpl;
  14945. private:
  14946. friend class DirectoryIterator;
  14947. friend class ScopedPointer<Pimpl>;
  14948. ScopedPointer<Pimpl> pimpl;
  14949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14950. };
  14951. friend class ScopedPointer<NativeIterator::Pimpl>;
  14952. NativeIterator fileFinder;
  14953. String wildCard, path;
  14954. int index;
  14955. mutable int totalNumFiles;
  14956. const int whatToLookFor;
  14957. const bool isRecursive;
  14958. bool hasBeenAdvanced;
  14959. ScopedPointer <DirectoryIterator> subIterator;
  14960. File currentFile;
  14961. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14962. };
  14963. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14964. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14965. #endif
  14966. #ifndef __JUCE_FILE_JUCEHEADER__
  14967. #endif
  14968. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14969. /*** Start of inlined file: juce_FileInputStream.h ***/
  14970. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14971. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14972. /**
  14973. An input stream that reads from a local file.
  14974. @see InputStream, FileOutputStream, File::createInputStream
  14975. */
  14976. class JUCE_API FileInputStream : public InputStream
  14977. {
  14978. public:
  14979. /** Creates a FileInputStream.
  14980. @param fileToRead the file to read from - if the file can't be accessed for some
  14981. reason, then the stream will just contain no data
  14982. */
  14983. explicit FileInputStream (const File& fileToRead);
  14984. /** Destructor. */
  14985. ~FileInputStream();
  14986. /** Returns the file that this stream is reading from. */
  14987. const File& getFile() const noexcept { return file; }
  14988. /** Returns the status of the file stream.
  14989. The result will be ok if the file opened successfully. If an error occurs while
  14990. opening or reading from the file, this will contain an error message.
  14991. */
  14992. Result getStatus() const { return status; }
  14993. int64 getTotalLength();
  14994. int read (void* destBuffer, int maxBytesToRead);
  14995. bool isExhausted();
  14996. int64 getPosition();
  14997. bool setPosition (int64 pos);
  14998. private:
  14999. File file;
  15000. void* fileHandle;
  15001. int64 currentPosition, totalSize;
  15002. Result status;
  15003. bool needToSeek;
  15004. void openHandle();
  15005. void closeHandle();
  15006. size_t readInternal (void* buffer, size_t numBytes);
  15007. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  15008. };
  15009. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  15010. /*** End of inlined file: juce_FileInputStream.h ***/
  15011. #endif
  15012. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15013. /*** Start of inlined file: juce_FileOutputStream.h ***/
  15014. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15015. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15016. /**
  15017. An output stream that writes into a local file.
  15018. @see OutputStream, FileInputStream, File::createOutputStream
  15019. */
  15020. class JUCE_API FileOutputStream : public OutputStream
  15021. {
  15022. public:
  15023. /** Creates a FileOutputStream.
  15024. If the file doesn't exist, it will first be created. If the file can't be
  15025. created or opened, the failedToOpen() method will return
  15026. true.
  15027. If the file already exists when opened, the stream's write-postion will
  15028. be set to the end of the file. To overwrite an existing file,
  15029. use File::deleteFile() before opening the stream, or use setPosition(0)
  15030. after it's opened (although this won't truncate the file).
  15031. It's better to use File::createOutputStream() to create one of these, rather
  15032. than using the class directly.
  15033. @see TemporaryFile
  15034. */
  15035. FileOutputStream (const File& fileToWriteTo,
  15036. int bufferSizeToUse = 16384);
  15037. /** Destructor. */
  15038. ~FileOutputStream();
  15039. /** Returns the file that this stream is writing to.
  15040. */
  15041. const File& getFile() const { return file; }
  15042. /** Returns the status of the file stream.
  15043. The result will be ok if the file opened successfully. If an error occurs while
  15044. opening or writing to the file, this will contain an error message.
  15045. */
  15046. Result getStatus() const { return status; }
  15047. /** Returns true if the stream couldn't be opened for some reason.
  15048. @see getResult()
  15049. */
  15050. bool failedToOpen() const { return status.failed(); }
  15051. void flush();
  15052. int64 getPosition();
  15053. bool setPosition (int64 pos);
  15054. bool write (const void* data, int numBytes);
  15055. void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  15056. private:
  15057. File file;
  15058. void* fileHandle;
  15059. Result status;
  15060. int64 currentPosition;
  15061. int bufferSize, bytesInBuffer;
  15062. HeapBlock <char> buffer;
  15063. void openHandle();
  15064. void closeHandle();
  15065. void flushInternal();
  15066. bool flushBuffer();
  15067. int64 setPositionInternal (int64 newPosition);
  15068. int writeInternal (const void* data, int numBytes);
  15069. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  15070. };
  15071. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15072. /*** End of inlined file: juce_FileOutputStream.h ***/
  15073. #endif
  15074. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  15075. /*** Start of inlined file: juce_FileSearchPath.h ***/
  15076. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  15077. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  15078. /**
  15079. Encapsulates a set of folders that make up a search path.
  15080. @see File
  15081. */
  15082. class JUCE_API FileSearchPath
  15083. {
  15084. public:
  15085. /** Creates an empty search path. */
  15086. FileSearchPath();
  15087. /** Creates a search path from a string of pathnames.
  15088. The path can be semicolon- or comma-separated, e.g.
  15089. "/foo/bar;/foo/moose;/fish/moose"
  15090. The separate folders are tokenised and added to the search path.
  15091. */
  15092. FileSearchPath (const String& path);
  15093. /** Creates a copy of another search path. */
  15094. FileSearchPath (const FileSearchPath& other);
  15095. /** Destructor. */
  15096. ~FileSearchPath();
  15097. /** Uses a string containing a list of pathnames to re-initialise this list.
  15098. This search path is cleared and the semicolon- or comma-separated folders
  15099. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  15100. */
  15101. FileSearchPath& operator= (const String& path);
  15102. /** Returns the number of folders in this search path.
  15103. @see operator[]
  15104. */
  15105. int getNumPaths() const;
  15106. /** Returns one of the folders in this search path.
  15107. The file returned isn't guaranteed to actually be a valid directory.
  15108. @see getNumPaths
  15109. */
  15110. File operator[] (int index) const;
  15111. /** Returns the search path as a semicolon-separated list of directories. */
  15112. String toString() const;
  15113. /** Adds a new directory to the search path.
  15114. The new directory is added to the end of the list if the insertIndex parameter is
  15115. less than zero, otherwise it is inserted at the given index.
  15116. */
  15117. void add (const File& directoryToAdd,
  15118. int insertIndex = -1);
  15119. /** Adds a new directory to the search path if it's not already in there. */
  15120. void addIfNotAlreadyThere (const File& directoryToAdd);
  15121. /** Removes a directory from the search path. */
  15122. void remove (int indexToRemove);
  15123. /** Merges another search path into this one.
  15124. This will remove any duplicate directories.
  15125. */
  15126. void addPath (const FileSearchPath& other);
  15127. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  15128. If the search is intended to be recursive, there's no point having nested folders in the search
  15129. path, because they'll just get searched twice and you'll get duplicate results.
  15130. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  15131. */
  15132. void removeRedundantPaths();
  15133. /** Removes any directories that don't actually exist. */
  15134. void removeNonExistentPaths();
  15135. /** Searches the path for a wildcard.
  15136. This will search all the directories in the search path in order, adding any
  15137. matching files to the results array.
  15138. @param results an array to append the results to
  15139. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  15140. return files, directories, or both.
  15141. @param searchRecursively whether to recursively search the subdirectories too
  15142. @param wildCardPattern a pattern to match against the filenames
  15143. @returns the number of files added to the array
  15144. @see File::findChildFiles
  15145. */
  15146. int findChildFiles (Array<File>& results,
  15147. int whatToLookFor,
  15148. bool searchRecursively,
  15149. const String& wildCardPattern = "*") const;
  15150. /** Finds out whether a file is inside one of the path's directories.
  15151. This will return true if the specified file is a child of one of the
  15152. directories specified by this path. Note that this doesn't actually do any
  15153. searching or check that the files exist - it just looks at the pathnames
  15154. to work out whether the file would be inside a directory.
  15155. @param fileToCheck the file to look for
  15156. @param checkRecursively if true, then this will return true if the file is inside a
  15157. subfolder of one of the path's directories (at any depth). If false
  15158. it will only return true if the file is actually a direct child
  15159. of one of the directories.
  15160. @see File::isAChildOf
  15161. */
  15162. bool isFileInPath (const File& fileToCheck,
  15163. bool checkRecursively) const;
  15164. private:
  15165. StringArray directories;
  15166. void init (const String& path);
  15167. JUCE_LEAK_DETECTOR (FileSearchPath);
  15168. };
  15169. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  15170. /*** End of inlined file: juce_FileSearchPath.h ***/
  15171. #endif
  15172. #ifndef __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15173. /*** Start of inlined file: juce_MemoryMappedFile.h ***/
  15174. #ifndef __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15175. #define __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15176. /**
  15177. Maps a file into virtual memory for easy reading and/or writing.
  15178. */
  15179. class JUCE_API MemoryMappedFile
  15180. {
  15181. public:
  15182. /** The read/write flags used when opening a memory mapped file. */
  15183. enum AccessMode
  15184. {
  15185. readOnly, /**< Indicates that the memory can only be read. */
  15186. readWrite /**< Indicates that the memory can be read and written to - changes that are
  15187. made will be flushed back to disk at the whim of the OS. */
  15188. };
  15189. /** Opens a file and maps it to an area of virtual memory.
  15190. The file should already exist, and should already be the size that you want to work with
  15191. when you call this. If the file is resized after being opened, the behaviour is undefined.
  15192. If the file exists and the operation succeeds, the getData() and getSize() methods will
  15193. return the location and size of the data that can be read or written. Note that the entire
  15194. file is not read into memory immediately - the OS simply creates a virtual mapping, which
  15195. will lazily pull the data into memory when blocks are accessed.
  15196. If the file can't be opened for some reason, the getData() method will return a null pointer.
  15197. */
  15198. MemoryMappedFile (const File& file, AccessMode mode);
  15199. /** Destructor. */
  15200. ~MemoryMappedFile();
  15201. /** Returns the address at which this file has been mapped, or a null pointer if
  15202. the file couldn't be successfully mapped.
  15203. */
  15204. void* getData() const noexcept { return address; }
  15205. /** Returns the number of bytes of data that are available for reading or writing.
  15206. This will normally be the size of the file.
  15207. */
  15208. size_t getSize() const noexcept { return length; }
  15209. private:
  15210. void* address;
  15211. size_t length;
  15212. #if JUCE_WINDOWS
  15213. void* fileHandle;
  15214. #else
  15215. int fileHandle;
  15216. #endif
  15217. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedFile);
  15218. };
  15219. #endif // __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15220. /*** End of inlined file: juce_MemoryMappedFile.h ***/
  15221. #endif
  15222. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15223. /*** Start of inlined file: juce_NamedPipe.h ***/
  15224. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15225. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  15226. /**
  15227. A cross-process pipe that can have data written to and read from it.
  15228. Two or more processes can use these for inter-process communication.
  15229. @see InterprocessConnection
  15230. */
  15231. class JUCE_API NamedPipe
  15232. {
  15233. public:
  15234. /** Creates a NamedPipe. */
  15235. NamedPipe();
  15236. /** Destructor. */
  15237. ~NamedPipe();
  15238. /** Tries to open a pipe that already exists.
  15239. Returns true if it succeeds.
  15240. */
  15241. bool openExisting (const String& pipeName);
  15242. /** Tries to create a new pipe.
  15243. Returns true if it succeeds.
  15244. */
  15245. bool createNewPipe (const String& pipeName);
  15246. /** Closes the pipe, if it's open. */
  15247. void close();
  15248. /** True if the pipe is currently open. */
  15249. bool isOpen() const;
  15250. /** Returns the last name that was used to try to open this pipe. */
  15251. String getName() const;
  15252. /** Reads data from the pipe.
  15253. This will block until another thread has written enough data into the pipe to fill
  15254. the number of bytes specified, or until another thread calls the cancelPendingReads()
  15255. method.
  15256. If the operation fails, it returns -1, otherwise, it will return the number of
  15257. bytes read.
  15258. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  15259. this is a maximum timeout for reading from the pipe.
  15260. */
  15261. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  15262. /** Writes some data to the pipe.
  15263. If the operation fails, it returns -1, otherwise, it will return the number of
  15264. bytes written.
  15265. */
  15266. int write (const void* sourceBuffer, int numBytesToWrite,
  15267. int timeOutMilliseconds = 2000);
  15268. /** If any threads are currently blocked on a read operation, this tells them to abort.
  15269. */
  15270. void cancelPendingReads();
  15271. private:
  15272. void* internal;
  15273. String currentPipeName;
  15274. CriticalSection lock;
  15275. bool openInternal (const String& pipeName, const bool createPipe);
  15276. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  15277. };
  15278. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  15279. /*** End of inlined file: juce_NamedPipe.h ***/
  15280. #endif
  15281. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15282. /*** Start of inlined file: juce_TemporaryFile.h ***/
  15283. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15284. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  15285. /**
  15286. Manages a temporary file, which will be deleted when this object is deleted.
  15287. This object is intended to be used as a stack based object, using its scope
  15288. to make sure the temporary file isn't left lying around.
  15289. For example:
  15290. @code
  15291. {
  15292. File myTargetFile ("~/myfile.txt");
  15293. // this will choose a file called something like "~/myfile_temp239348.txt"
  15294. // which definitely doesn't exist at the time the constructor is called.
  15295. TemporaryFile temp (myTargetFile);
  15296. // create a stream to the temporary file, and write some data to it...
  15297. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  15298. if (out != nullptr)
  15299. {
  15300. out->write ( ...etc )
  15301. out->flush();
  15302. out = nullptr; // (deletes the stream)
  15303. // ..now we've finished writing, this will rename the temp file to
  15304. // make it replace the target file we specified above.
  15305. bool succeeded = temp.overwriteTargetFileWithTemporary();
  15306. }
  15307. // ..and even if something went wrong and our overwrite failed,
  15308. // as the TemporaryFile object goes out of scope here, it'll make sure
  15309. // that the temp file gets deleted.
  15310. }
  15311. @endcode
  15312. @see File, FileOutputStream
  15313. */
  15314. class JUCE_API TemporaryFile
  15315. {
  15316. public:
  15317. enum OptionFlags
  15318. {
  15319. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  15320. i.e. its name should start with a dot. */
  15321. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  15322. the file is unique, they should go in brackets rather
  15323. than just being appended (see File::getNonexistentSibling() )*/
  15324. };
  15325. /** Creates a randomly-named temporary file in the default temp directory.
  15326. @param suffix a file suffix to use for the file
  15327. @param optionFlags a combination of the values listed in the OptionFlags enum
  15328. The file will not be created until you write to it. And remember that when
  15329. this object is deleted, the file will also be deleted!
  15330. */
  15331. TemporaryFile (const String& suffix = String::empty,
  15332. int optionFlags = 0);
  15333. /** Creates a temporary file in the same directory as a specified file.
  15334. This is useful if you have a file that you want to overwrite, but don't
  15335. want to harm the original file if the write operation fails. You can
  15336. use this to create a temporary file next to the target file, then
  15337. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  15338. to replace the target file with the one you've just written.
  15339. This class won't create any files until you actually write to them. And remember
  15340. that when this object is deleted, the temporary file will also be deleted!
  15341. @param targetFile the file that you intend to overwrite - the temporary
  15342. file will be created in the same directory as this
  15343. @param optionFlags a combination of the values listed in the OptionFlags enum
  15344. */
  15345. TemporaryFile (const File& targetFile,
  15346. int optionFlags = 0);
  15347. /** Destructor.
  15348. When this object is deleted it will make sure that its temporary file is
  15349. also deleted! If the operation fails, it'll throw an assertion in debug
  15350. mode.
  15351. */
  15352. ~TemporaryFile();
  15353. /** Returns the temporary file. */
  15354. const File& getFile() const { return temporaryFile; }
  15355. /** Returns the target file that was specified in the constructor. */
  15356. const File& getTargetFile() const { return targetFile; }
  15357. /** Tries to move the temporary file to overwrite the target file that was
  15358. specified in the constructor.
  15359. If you used the constructor that specified a target file, this will attempt
  15360. to replace that file with the temporary one.
  15361. Before calling this, make sure:
  15362. - that you've actually written to the temporary file
  15363. - that you've closed any open streams that you were using to write to it
  15364. - and that you don't have any streams open to the target file, which would
  15365. prevent it being overwritten
  15366. If the file move succeeds, this returns false, and the temporary file will
  15367. have disappeared. If it fails, the temporary file will probably still exist,
  15368. but will be deleted when this object is destroyed.
  15369. */
  15370. bool overwriteTargetFileWithTemporary() const;
  15371. /** Attempts to delete the temporary file, if it exists.
  15372. @returns true if the file is successfully deleted (or if it didn't exist).
  15373. */
  15374. bool deleteTemporaryFile() const;
  15375. private:
  15376. File temporaryFile, targetFile;
  15377. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  15378. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  15379. };
  15380. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  15381. /*** End of inlined file: juce_TemporaryFile.h ***/
  15382. #endif
  15383. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15384. /*** Start of inlined file: juce_ZipFile.h ***/
  15385. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15386. #define __JUCE_ZIPFILE_JUCEHEADER__
  15387. /*** Start of inlined file: juce_InputSource.h ***/
  15388. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15389. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  15390. /**
  15391. A lightweight object that can create a stream to read some kind of resource.
  15392. This may be used to refer to a file, or some other kind of source, allowing a
  15393. caller to create an input stream that can read from it when required.
  15394. @see FileInputSource
  15395. */
  15396. class JUCE_API InputSource
  15397. {
  15398. public:
  15399. InputSource() noexcept {}
  15400. /** Destructor. */
  15401. virtual ~InputSource() {}
  15402. /** Returns a new InputStream to read this item.
  15403. @returns an inputstream that the caller will delete, or 0 if
  15404. the filename isn't found.
  15405. */
  15406. virtual InputStream* createInputStream() = 0;
  15407. /** Returns a new InputStream to read an item, relative.
  15408. @param relatedItemPath the relative pathname of the resource that is required
  15409. @returns an inputstream that the caller will delete, or 0 if
  15410. the item isn't found.
  15411. */
  15412. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  15413. /** Returns a hash code that uniquely represents this item.
  15414. */
  15415. virtual int64 hashCode() const = 0;
  15416. private:
  15417. JUCE_LEAK_DETECTOR (InputSource);
  15418. };
  15419. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  15420. /*** End of inlined file: juce_InputSource.h ***/
  15421. /**
  15422. Decodes a ZIP file from a stream.
  15423. This can enumerate the items in a ZIP file and can create suitable stream objects
  15424. to read each one.
  15425. */
  15426. class JUCE_API ZipFile
  15427. {
  15428. public:
  15429. /** Creates a ZipFile for a given stream.
  15430. @param inputStream the stream to read from
  15431. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  15432. will be deleted when this ZipFile object is deleted
  15433. */
  15434. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  15435. /** Creates a ZipFile based for a file. */
  15436. ZipFile (const File& file);
  15437. /** Creates a ZipFile for an input source.
  15438. The inputSource object will be owned by the zip file, which will delete
  15439. it later when not needed.
  15440. */
  15441. ZipFile (InputSource* inputSource);
  15442. /** Destructor. */
  15443. ~ZipFile();
  15444. /**
  15445. Contains information about one of the entries in a ZipFile.
  15446. @see ZipFile::getEntry
  15447. */
  15448. struct ZipEntry
  15449. {
  15450. /** The name of the file, which may also include a partial pathname. */
  15451. String filename;
  15452. /** The file's original size. */
  15453. unsigned int uncompressedSize;
  15454. /** The last time the file was modified. */
  15455. Time fileTime;
  15456. };
  15457. /** Returns the number of items in the zip file. */
  15458. int getNumEntries() const noexcept;
  15459. /** Returns a structure that describes one of the entries in the zip file.
  15460. This may return zero if the index is out of range.
  15461. @see ZipFile::ZipEntry
  15462. */
  15463. const ZipEntry* getEntry (int index) const noexcept;
  15464. /** Returns the index of the first entry with a given filename.
  15465. This uses a case-sensitive comparison to look for a filename in the
  15466. list of entries. It might return -1 if no match is found.
  15467. @see ZipFile::ZipEntry
  15468. */
  15469. int getIndexOfFileName (const String& fileName) const noexcept;
  15470. /** Returns a structure that describes one of the entries in the zip file.
  15471. This uses a case-sensitive comparison to look for a filename in the
  15472. list of entries. It might return 0 if no match is found.
  15473. @see ZipFile::ZipEntry
  15474. */
  15475. const ZipEntry* getEntry (const String& fileName) const noexcept;
  15476. /** Sorts the list of entries, based on the filename.
  15477. */
  15478. void sortEntriesByFilename();
  15479. /** Creates a stream that can read from one of the zip file's entries.
  15480. The stream that is returned must be deleted by the caller (and
  15481. zero might be returned if a stream can't be opened for some reason).
  15482. The stream must not be used after the ZipFile object that created
  15483. has been deleted.
  15484. */
  15485. InputStream* createStreamForEntry (int index);
  15486. /** Creates a stream that can read from one of the zip file's entries.
  15487. The stream that is returned must be deleted by the caller (and
  15488. zero might be returned if a stream can't be opened for some reason).
  15489. The stream must not be used after the ZipFile object that created
  15490. has been deleted.
  15491. */
  15492. InputStream* createStreamForEntry (ZipEntry& entry);
  15493. /** Uncompresses all of the files in the zip file.
  15494. This will expand all the entries into a target directory. The relative
  15495. paths of the entries are used.
  15496. @param targetDirectory the root folder to uncompress to
  15497. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15498. @returns true if all the files are successfully unzipped
  15499. */
  15500. bool uncompressTo (const File& targetDirectory,
  15501. bool shouldOverwriteFiles = true);
  15502. /** Uncompresses one of the entries from the zip file.
  15503. This will expand the entry and write it in a target directory. The entry's path is used to
  15504. determine which subfolder of the target should contain the new file.
  15505. @param index the index of the entry to uncompress
  15506. @param targetDirectory the root folder to uncompress into
  15507. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15508. @returns true if the files is successfully unzipped
  15509. */
  15510. bool uncompressEntry (int index,
  15511. const File& targetDirectory,
  15512. bool shouldOverwriteFiles = true);
  15513. /** Used to create a new zip file.
  15514. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  15515. then you can write it to a stream with write().
  15516. Currently this just stores the files with no compression.. That will be added
  15517. soon!
  15518. */
  15519. class Builder
  15520. {
  15521. public:
  15522. Builder();
  15523. ~Builder();
  15524. /** Adds a file while should be added to the archive.
  15525. The file isn't read immediately, all the files will be read later when the writeToStream()
  15526. method is called.
  15527. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  15528. If the storedPathName parameter is specified, you can customise the partial pathname that
  15529. will be stored for this file.
  15530. */
  15531. void addFile (const File& fileToAdd, int compressionLevel,
  15532. const String& storedPathName = String::empty);
  15533. /** Generates the zip file, writing it to the specified stream. */
  15534. bool writeToStream (OutputStream& target) const;
  15535. private:
  15536. class Item;
  15537. friend class OwnedArray<Item>;
  15538. OwnedArray<Item> items;
  15539. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  15540. };
  15541. private:
  15542. class ZipInputStream;
  15543. class ZipFilenameComparator;
  15544. class ZipEntryInfo;
  15545. friend class ZipInputStream;
  15546. friend class ZipFilenameComparator;
  15547. friend class ZipEntryInfo;
  15548. OwnedArray <ZipEntryInfo> entries;
  15549. CriticalSection lock;
  15550. InputStream* inputStream;
  15551. ScopedPointer <InputStream> streamToDelete;
  15552. ScopedPointer <InputSource> inputSource;
  15553. #if JUCE_DEBUG
  15554. int numOpenStreams;
  15555. #endif
  15556. void init();
  15557. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  15558. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  15559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  15560. };
  15561. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  15562. /*** End of inlined file: juce_ZipFile.h ***/
  15563. #endif
  15564. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15565. /*** Start of inlined file: juce_MACAddress.h ***/
  15566. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15567. #define __JUCE_MACADDRESS_JUCEHEADER__
  15568. /**
  15569. A wrapper for a streaming (TCP) socket.
  15570. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15571. sockets, you could also try the InterprocessConnection class.
  15572. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15573. */
  15574. class JUCE_API MACAddress
  15575. {
  15576. public:
  15577. /** Populates a list of the MAC addresses of all the available network cards. */
  15578. static void findAllAddresses (Array<MACAddress>& results);
  15579. /** Creates a null address (00-00-00-00-00-00). */
  15580. MACAddress();
  15581. /** Creates a copy of another address. */
  15582. MACAddress (const MACAddress& other);
  15583. /** Creates a copy of another address. */
  15584. MACAddress& operator= (const MACAddress& other);
  15585. /** Creates an address from 6 bytes. */
  15586. explicit MACAddress (const uint8 bytes[6]);
  15587. /** Returns a pointer to the 6 bytes that make up this address. */
  15588. const uint8* getBytes() const noexcept { return asBytes; }
  15589. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  15590. const String toString() const;
  15591. /** Returns the address in the lower 6 bytes of an int64.
  15592. This uses a little-endian arrangement, with the first byte of the address being
  15593. stored in the least-significant byte of the result value.
  15594. */
  15595. int64 toInt64() const noexcept;
  15596. /** Returns true if this address is null (00-00-00-00-00-00). */
  15597. bool isNull() const noexcept;
  15598. bool operator== (const MACAddress& other) const noexcept;
  15599. bool operator!= (const MACAddress& other) const noexcept;
  15600. private:
  15601. #ifndef DOXYGEN
  15602. union
  15603. {
  15604. uint64 asInt64;
  15605. uint8 asBytes[6];
  15606. };
  15607. #endif
  15608. };
  15609. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  15610. /*** End of inlined file: juce_MACAddress.h ***/
  15611. #endif
  15612. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15613. /*** Start of inlined file: juce_Socket.h ***/
  15614. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15615. #define __JUCE_SOCKET_JUCEHEADER__
  15616. /**
  15617. A wrapper for a streaming (TCP) socket.
  15618. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15619. sockets, you could also try the InterprocessConnection class.
  15620. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15621. */
  15622. class JUCE_API StreamingSocket
  15623. {
  15624. public:
  15625. /** Creates an uninitialised socket.
  15626. To connect it, use the connect() method, after which you can read() or write()
  15627. to it.
  15628. To wait for other sockets to connect to this one, the createListener() method
  15629. enters "listener" mode, and can be used to spawn new sockets for each connection
  15630. that comes along.
  15631. */
  15632. StreamingSocket();
  15633. /** Destructor. */
  15634. ~StreamingSocket();
  15635. /** Binds the socket to the specified local port.
  15636. @returns true on success; false may indicate that another socket is already bound
  15637. on the same port
  15638. */
  15639. bool bindToPort (int localPortNumber);
  15640. /** Tries to connect the socket to hostname:port.
  15641. If timeOutMillisecs is 0, then this method will block until the operating system
  15642. rejects the connection (which could take a long time).
  15643. @returns true if it succeeds.
  15644. @see isConnected
  15645. */
  15646. bool connect (const String& remoteHostname,
  15647. int remotePortNumber,
  15648. int timeOutMillisecs = 3000);
  15649. /** True if the socket is currently connected. */
  15650. bool isConnected() const noexcept { return connected; }
  15651. /** Closes the connection. */
  15652. void close();
  15653. /** Returns the name of the currently connected host. */
  15654. const String& getHostName() const noexcept { return hostName; }
  15655. /** Returns the port number that's currently open. */
  15656. int getPort() const noexcept { return portNumber; }
  15657. /** True if the socket is connected to this machine rather than over the network. */
  15658. bool isLocal() const noexcept;
  15659. /** Waits until the socket is ready for reading or writing.
  15660. If readyForReading is true, it will wait until the socket is ready for
  15661. reading; if false, it will wait until it's ready for writing.
  15662. If the timeout is < 0, it will wait forever, or else will give up after
  15663. the specified time.
  15664. If the socket is ready on return, this returns 1. If it times-out before
  15665. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15666. */
  15667. int waitUntilReady (bool readyForReading,
  15668. int timeoutMsecs) const;
  15669. /** Reads bytes from the socket.
  15670. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15671. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15672. flag is false, the method will return as much data as is currently available
  15673. without blocking.
  15674. @returns the number of bytes read, or -1 if there was an error.
  15675. @see waitUntilReady
  15676. */
  15677. int read (void* destBuffer, int maxBytesToRead,
  15678. bool blockUntilSpecifiedAmountHasArrived);
  15679. /** Writes bytes to the socket from a buffer.
  15680. Note that this method will block unless you have checked the socket is ready
  15681. for writing before calling it (see the waitUntilReady() method).
  15682. @returns the number of bytes written, or -1 if there was an error.
  15683. */
  15684. int write (const void* sourceBuffer, int numBytesToWrite);
  15685. /** Puts this socket into "listener" mode.
  15686. When in this mode, your thread can call waitForNextConnection() repeatedly,
  15687. which will spawn new sockets for each new connection, so that these can
  15688. be handled in parallel by other threads.
  15689. @param portNumber the port number to listen on
  15690. @param localHostName the interface address to listen on - pass an empty
  15691. string to listen on all addresses
  15692. @returns true if it manages to open the socket successfully.
  15693. @see waitForNextConnection
  15694. */
  15695. bool createListener (int portNumber, const String& localHostName = String::empty);
  15696. /** When in "listener" mode, this waits for a connection and spawns it as a new
  15697. socket.
  15698. The object that gets returned will be owned by the caller.
  15699. This method can only be called after using createListener().
  15700. @see createListener
  15701. */
  15702. StreamingSocket* waitForNextConnection() const;
  15703. private:
  15704. String hostName;
  15705. int volatile portNumber, handle;
  15706. bool connected, isListener;
  15707. StreamingSocket (const String& hostname, int portNumber, int handle);
  15708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  15709. };
  15710. /**
  15711. A wrapper for a datagram (UDP) socket.
  15712. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15713. sockets, you could also try the InterprocessConnection class.
  15714. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  15715. */
  15716. class JUCE_API DatagramSocket
  15717. {
  15718. public:
  15719. /**
  15720. Creates an (uninitialised) datagram socket.
  15721. The localPortNumber is the port on which to bind this socket. If this value is 0,
  15722. the port number is assigned by the operating system.
  15723. To use the socket for sending, call the connect() method. This will not immediately
  15724. make a connection, but will save the destination you've provided. After this, you can
  15725. call read() or write().
  15726. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15727. (may require extra privileges on linux)
  15728. To wait for other sockets to connect to this one, call waitForNextConnection().
  15729. */
  15730. DatagramSocket (int localPortNumber,
  15731. bool enableBroadcasting = false);
  15732. /** Destructor. */
  15733. ~DatagramSocket();
  15734. /** Binds the socket to the specified local port.
  15735. @returns true on success; false may indicate that another socket is already bound
  15736. on the same port
  15737. */
  15738. bool bindToPort (int localPortNumber);
  15739. /** Tries to connect the socket to hostname:port.
  15740. If timeOutMillisecs is 0, then this method will block until the operating system
  15741. rejects the connection (which could take a long time).
  15742. @returns true if it succeeds.
  15743. @see isConnected
  15744. */
  15745. bool connect (const String& remoteHostname,
  15746. int remotePortNumber,
  15747. int timeOutMillisecs = 3000);
  15748. /** True if the socket is currently connected. */
  15749. bool isConnected() const noexcept { return connected; }
  15750. /** Closes the connection. */
  15751. void close();
  15752. /** Returns the name of the currently connected host. */
  15753. const String& getHostName() const noexcept { return hostName; }
  15754. /** Returns the port number that's currently open. */
  15755. int getPort() const noexcept { return portNumber; }
  15756. /** True if the socket is connected to this machine rather than over the network. */
  15757. bool isLocal() const noexcept;
  15758. /** Waits until the socket is ready for reading or writing.
  15759. If readyForReading is true, it will wait until the socket is ready for
  15760. reading; if false, it will wait until it's ready for writing.
  15761. If the timeout is < 0, it will wait forever, or else will give up after
  15762. the specified time.
  15763. If the socket is ready on return, this returns 1. If it times-out before
  15764. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15765. */
  15766. int waitUntilReady (bool readyForReading,
  15767. int timeoutMsecs) const;
  15768. /** Reads bytes from the socket.
  15769. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15770. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15771. flag is false, the method will return as much data as is currently available
  15772. without blocking.
  15773. @returns the number of bytes read, or -1 if there was an error.
  15774. @see waitUntilReady
  15775. */
  15776. int read (void* destBuffer, int maxBytesToRead,
  15777. bool blockUntilSpecifiedAmountHasArrived);
  15778. /** Writes bytes to the socket from a buffer.
  15779. Note that this method will block unless you have checked the socket is ready
  15780. for writing before calling it (see the waitUntilReady() method).
  15781. @returns the number of bytes written, or -1 if there was an error.
  15782. */
  15783. int write (const void* sourceBuffer, int numBytesToWrite);
  15784. /** This waits for incoming data to be sent, and returns a socket that can be used
  15785. to read it.
  15786. The object that gets returned is owned by the caller, and can't be used for
  15787. sending, but can be used to read the data.
  15788. */
  15789. DatagramSocket* waitForNextConnection() const;
  15790. private:
  15791. String hostName;
  15792. int volatile portNumber, handle;
  15793. bool connected, allowBroadcast;
  15794. void* serverAddress;
  15795. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15796. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15797. };
  15798. #endif // __JUCE_SOCKET_JUCEHEADER__
  15799. /*** End of inlined file: juce_Socket.h ***/
  15800. #endif
  15801. #ifndef __JUCE_URL_JUCEHEADER__
  15802. /*** Start of inlined file: juce_URL.h ***/
  15803. #ifndef __JUCE_URL_JUCEHEADER__
  15804. #define __JUCE_URL_JUCEHEADER__
  15805. class InputStream;
  15806. class XmlElement;
  15807. /**
  15808. Represents a URL and has a bunch of useful functions to manipulate it.
  15809. This class can be used to launch URLs in browsers, and also to create
  15810. InputStreams that can read from remote http or ftp sources.
  15811. */
  15812. class JUCE_API URL
  15813. {
  15814. public:
  15815. /** Creates an empty URL. */
  15816. URL();
  15817. /** Creates a URL from a string. */
  15818. URL (const String& url);
  15819. /** Creates a copy of another URL. */
  15820. URL (const URL& other);
  15821. /** Destructor. */
  15822. ~URL();
  15823. /** Copies this URL from another one. */
  15824. URL& operator= (const URL& other);
  15825. /** Returns a string version of the URL.
  15826. If includeGetParameters is true and any parameters have been set with the
  15827. withParameter() method, then the string will have these appended on the
  15828. end and url-encoded.
  15829. */
  15830. String toString (bool includeGetParameters) const;
  15831. /** True if it seems to be valid. */
  15832. bool isWellFormed() const;
  15833. /** Returns just the domain part of the URL.
  15834. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15835. */
  15836. String getDomain() const;
  15837. /** Returns the path part of the URL.
  15838. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15839. */
  15840. String getSubPath() const;
  15841. /** Returns the scheme of the URL.
  15842. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15843. include the colon).
  15844. */
  15845. String getScheme() const;
  15846. /** Returns a new version of this URL that uses a different sub-path.
  15847. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15848. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15849. */
  15850. const URL withNewSubPath (const String& newPath) const;
  15851. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15852. Any control characters in the value will be encoded.
  15853. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15854. would produce a new url whose toString(true) method would return
  15855. "www.fish.com?amount=some+fish".
  15856. */
  15857. const URL withParameter (const String& parameterName,
  15858. const String& parameterValue) const;
  15859. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15860. When performing a POST where one of your parameters is a binary file, this
  15861. lets you specify the file.
  15862. Note that the filename is stored, but the file itself won't actually be read
  15863. until this URL is later used to create a network input stream.
  15864. */
  15865. const URL withFileToUpload (const String& parameterName,
  15866. const File& fileToUpload,
  15867. const String& mimeType) const;
  15868. /** Returns a set of all the parameters encoded into the url.
  15869. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15870. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15871. The values returned will have been cleaned up to remove any escape characters.
  15872. @see getNamedParameter, withParameter
  15873. */
  15874. const StringPairArray& getParameters() const;
  15875. /** Returns the set of files that should be uploaded as part of a POST operation.
  15876. This is the set of files that were added to the URL with the withFileToUpload()
  15877. method.
  15878. */
  15879. const StringPairArray& getFilesToUpload() const;
  15880. /** Returns the set of mime types associated with each of the upload files.
  15881. */
  15882. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15883. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15884. If you're setting the POST data, be careful not to have any parameters set
  15885. as well, otherwise it'll all get thrown in together, and might not have the
  15886. desired effect.
  15887. If the URL already contains some POST data, this will replace it, rather
  15888. than being appended to it.
  15889. This data will only be used if you specify a post operation when you call
  15890. createInputStream().
  15891. */
  15892. const URL withPOSTData (const String& postData) const;
  15893. /** Returns the data that was set using withPOSTData().
  15894. */
  15895. String getPostData() const { return postData; }
  15896. /** Tries to launch the system's default browser to open the URL.
  15897. Returns true if this seems to have worked.
  15898. */
  15899. bool launchInDefaultBrowser() const;
  15900. /** Takes a guess as to whether a string might be a valid website address.
  15901. This isn't foolproof!
  15902. */
  15903. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15904. /** Takes a guess as to whether a string might be a valid email address.
  15905. This isn't foolproof!
  15906. */
  15907. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15908. /** This callback function can be used by the createInputStream() method.
  15909. It allows your app to receive progress updates during a lengthy POST operation. If you
  15910. want to continue the operation, this should return true, or false to abort.
  15911. */
  15912. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15913. /** Attempts to open a stream that can read from this URL.
  15914. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15915. the paramters, otherwise it'll encode them into the
  15916. URL and do a 'GET'.
  15917. @param progressCallback if this is non-zero, it lets you supply a callback function
  15918. to keep track of the operation's progress. This can be useful
  15919. for lengthy POST operations, so that you can provide user feedback.
  15920. @param progressCallbackContext if a callback is specified, this value will be passed to
  15921. the function
  15922. @param extraHeaders if not empty, this string is appended onto the headers that
  15923. are used for the request. It must therefore be a valid set of HTML
  15924. header directives, separated by newlines.
  15925. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15926. a negative number, it will be infinite. Otherwise it specifies a
  15927. time in milliseconds.
  15928. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15929. in the response will be stored in this array
  15930. @returns an input stream that the caller must delete, or a null pointer if there was an
  15931. error trying to open it.
  15932. */
  15933. InputStream* createInputStream (bool usePostCommand,
  15934. OpenStreamProgressCallback* progressCallback = nullptr,
  15935. void* progressCallbackContext = nullptr,
  15936. const String& extraHeaders = String::empty,
  15937. int connectionTimeOutMs = 0,
  15938. StringPairArray* responseHeaders = nullptr) const;
  15939. /** Tries to download the entire contents of this URL into a binary data block.
  15940. If it succeeds, this will return true and append the data it read onto the end
  15941. of the memory block.
  15942. @param destData the memory block to append the new data to
  15943. @param usePostCommand whether to use a POST command to get the data (uses
  15944. a GET command if this is false)
  15945. @see readEntireTextStream, readEntireXmlStream
  15946. */
  15947. bool readEntireBinaryStream (MemoryBlock& destData,
  15948. bool usePostCommand = false) const;
  15949. /** Tries to download the entire contents of this URL as a string.
  15950. If it fails, this will return an empty string, otherwise it will return the
  15951. contents of the downloaded file. If you need to distinguish between a read
  15952. operation that fails and one that returns an empty string, you'll need to use
  15953. a different method, such as readEntireBinaryStream().
  15954. @param usePostCommand whether to use a POST command to get the data (uses
  15955. a GET command if this is false)
  15956. @see readEntireBinaryStream, readEntireXmlStream
  15957. */
  15958. String readEntireTextStream (bool usePostCommand = false) const;
  15959. /** Tries to download the entire contents of this URL and parse it as XML.
  15960. If it fails, or if the text that it reads can't be parsed as XML, this will
  15961. return 0.
  15962. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15963. this object when no longer needed.
  15964. @param usePostCommand whether to use a POST command to get the data (uses
  15965. a GET command if this is false)
  15966. @see readEntireBinaryStream, readEntireTextStream
  15967. */
  15968. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15969. /** Adds escape sequences to a string to encode any characters that aren't
  15970. legal in a URL.
  15971. E.g. any spaces will be replaced with "%20".
  15972. This is the opposite of removeEscapeChars().
  15973. If isParameter is true, it means that the string is going to be used
  15974. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15975. be legal in a URL.
  15976. @see removeEscapeChars
  15977. */
  15978. static String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15979. bool isParameter);
  15980. /** Replaces any escape character sequences in a string with their original
  15981. character codes.
  15982. E.g. any instances of "%20" will be replaced by a space.
  15983. This is the opposite of addEscapeChars().
  15984. @see addEscapeChars
  15985. */
  15986. static String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15987. private:
  15988. String url, postData;
  15989. StringPairArray parameters, filesToUpload, mimeTypes;
  15990. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15991. OpenStreamProgressCallback* progressCallback,
  15992. void* progressCallbackContext, const String& headers,
  15993. const int timeOutMs, StringPairArray* responseHeaders);
  15994. JUCE_LEAK_DETECTOR (URL);
  15995. };
  15996. #endif // __JUCE_URL_JUCEHEADER__
  15997. /*** End of inlined file: juce_URL.h ***/
  15998. #endif
  15999. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16000. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  16001. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16002. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16003. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  16004. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16005. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16006. /**
  16007. Holds a pointer to an object which can optionally be deleted when this pointer
  16008. goes out of scope.
  16009. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  16010. not the object is deleted.
  16011. @see ScopedPointer
  16012. */
  16013. template <class ObjectType>
  16014. class OptionalScopedPointer
  16015. {
  16016. public:
  16017. /** Creates an empty OptionalScopedPointer. */
  16018. OptionalScopedPointer() : shouldDelete (false) {}
  16019. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  16020. the OptionalScopedPointer will delete it.
  16021. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  16022. deleting the object when it is itself deleted. If this parameter is false, then the
  16023. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  16024. */
  16025. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  16026. : object (objectToHold), shouldDelete (takeOwnership)
  16027. {
  16028. }
  16029. /** Takes ownership of the object that another OptionalScopedPointer holds.
  16030. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  16031. as ownership of the managed object is transferred to this object.
  16032. The flag to indicate whether or not to delete the managed object is also
  16033. copied from the source object.
  16034. */
  16035. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  16036. : object (objectToTransferFrom.release()),
  16037. shouldDelete (objectToTransferFrom.shouldDelete)
  16038. {
  16039. }
  16040. /** Takes ownership of the object that another OptionalScopedPointer holds.
  16041. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  16042. as ownership of the managed object is transferred to this object.
  16043. The ownership flag that says whether or not to delete the managed object is also
  16044. copied from the source object.
  16045. */
  16046. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  16047. {
  16048. if (object != objectToTransferFrom.object)
  16049. {
  16050. clear();
  16051. object = objectToTransferFrom.object;
  16052. }
  16053. shouldDelete = objectToTransferFrom.shouldDelete;
  16054. return *this;
  16055. }
  16056. /** The destructor may or may not delete the object that is being held, depending on the
  16057. takeOwnership flag that was specified when the object was first passed into an
  16058. OptionalScopedPointer constructor.
  16059. */
  16060. ~OptionalScopedPointer()
  16061. {
  16062. clear();
  16063. }
  16064. /** Returns the object that this pointer is managing. */
  16065. inline operator ObjectType*() const noexcept { return object; }
  16066. /** Returns the object that this pointer is managing. */
  16067. inline ObjectType& operator*() const noexcept { return *object; }
  16068. /** Lets you access methods and properties of the object that this pointer is holding. */
  16069. inline ObjectType* operator->() const noexcept { return object; }
  16070. /** Removes the current object from this OptionalScopedPointer without deleting it.
  16071. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  16072. */
  16073. ObjectType* release() noexcept { return object.release(); }
  16074. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  16075. ownership of it.
  16076. */
  16077. void clear()
  16078. {
  16079. if (! shouldDelete)
  16080. object.release();
  16081. }
  16082. /** Swaps this object with another OptionalScopedPointer.
  16083. The two objects simply exchange their states.
  16084. */
  16085. void swapWith (OptionalScopedPointer<ObjectType>& other) noexcept
  16086. {
  16087. object.swapWith (other.object);
  16088. std::swap (shouldDelete, other.shouldDelete);
  16089. }
  16090. private:
  16091. ScopedPointer<ObjectType> object;
  16092. bool shouldDelete;
  16093. };
  16094. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16095. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  16096. /** Wraps another input stream, and reads from it using an intermediate buffer
  16097. If you're using an input stream such as a file input stream, and making lots of
  16098. small read accesses to it, it's probably sensible to wrap it in one of these,
  16099. so that the source stream gets accessed in larger chunk sizes, meaning less
  16100. work for the underlying stream.
  16101. */
  16102. class JUCE_API BufferedInputStream : public InputStream
  16103. {
  16104. public:
  16105. /** Creates a BufferedInputStream from an input source.
  16106. @param sourceStream the source stream to read from
  16107. @param bufferSize the size of reservoir to use to buffer the source
  16108. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16109. deleted by this object when it is itself deleted.
  16110. */
  16111. BufferedInputStream (InputStream* sourceStream,
  16112. int bufferSize,
  16113. bool deleteSourceWhenDestroyed);
  16114. /** Creates a BufferedInputStream from an input source.
  16115. @param sourceStream the source stream to read from - the source stream must not
  16116. be deleted until this object has been destroyed.
  16117. @param bufferSize the size of reservoir to use to buffer the source
  16118. */
  16119. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  16120. /** Destructor.
  16121. This may also delete the source stream, if that option was chosen when the
  16122. buffered stream was created.
  16123. */
  16124. ~BufferedInputStream();
  16125. int64 getTotalLength();
  16126. int64 getPosition();
  16127. bool setPosition (int64 newPosition);
  16128. int read (void* destBuffer, int maxBytesToRead);
  16129. String readString();
  16130. bool isExhausted();
  16131. private:
  16132. OptionalScopedPointer<InputStream> source;
  16133. int bufferSize;
  16134. int64 position, lastReadPos, bufferStart, bufferOverlap;
  16135. HeapBlock <char> buffer;
  16136. void ensureBuffered();
  16137. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  16138. };
  16139. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16140. /*** End of inlined file: juce_BufferedInputStream.h ***/
  16141. #endif
  16142. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16143. /*** Start of inlined file: juce_FileInputSource.h ***/
  16144. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16145. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16146. /**
  16147. A type of InputSource that represents a normal file.
  16148. @see InputSource
  16149. */
  16150. class JUCE_API FileInputSource : public InputSource
  16151. {
  16152. public:
  16153. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  16154. ~FileInputSource();
  16155. InputStream* createInputStream();
  16156. InputStream* createInputStreamFor (const String& relatedItemPath);
  16157. int64 hashCode() const;
  16158. private:
  16159. const File file;
  16160. bool useFileTimeInHashGeneration;
  16161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  16162. };
  16163. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16164. /*** End of inlined file: juce_FileInputSource.h ***/
  16165. #endif
  16166. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16167. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16168. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16169. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16170. /**
  16171. A stream which uses zlib to compress the data written into it.
  16172. @see GZIPDecompressorInputStream
  16173. */
  16174. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  16175. {
  16176. public:
  16177. /** Creates a compression stream.
  16178. @param destStream the stream into which the compressed data should
  16179. be written
  16180. @param compressionLevel how much to compress the data, between 1 and 9, where
  16181. 1 is the fastest/lowest compression, and 9 is the
  16182. slowest/highest compression. Any value outside this range
  16183. indicates that a default compression level should be used.
  16184. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  16185. this stream is destroyed
  16186. @param windowBits this is used internally to change the window size used
  16187. by zlib - leave it as 0 unless you specifically need to set
  16188. its value for some reason
  16189. */
  16190. GZIPCompressorOutputStream (OutputStream* destStream,
  16191. int compressionLevel = 0,
  16192. bool deleteDestStreamWhenDestroyed = false,
  16193. int windowBits = 0);
  16194. /** Destructor. */
  16195. ~GZIPCompressorOutputStream();
  16196. void flush();
  16197. int64 getPosition();
  16198. bool setPosition (int64 newPosition);
  16199. bool write (const void* destBuffer, int howMany);
  16200. /** These are preset values that can be used for the constructor's windowBits paramter.
  16201. For more info about this, see the zlib documentation for its windowBits parameter.
  16202. */
  16203. enum WindowBitsValues
  16204. {
  16205. windowBitsRaw = -15,
  16206. windowBitsGZIP = 15 + 16
  16207. };
  16208. private:
  16209. OptionalScopedPointer<OutputStream> destStream;
  16210. HeapBlock <uint8> buffer;
  16211. class GZIPCompressorHelper;
  16212. friend class ScopedPointer <GZIPCompressorHelper>;
  16213. ScopedPointer <GZIPCompressorHelper> helper;
  16214. bool doNextBlock();
  16215. void flushInternal();
  16216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  16217. };
  16218. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16219. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16220. #endif
  16221. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16222. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16223. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16224. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16225. /**
  16226. This stream will decompress a source-stream using zlib.
  16227. Tip: if you're reading lots of small items from one of these streams, you
  16228. can increase the performance enormously by passing it through a
  16229. BufferedInputStream, so that it has to read larger blocks less often.
  16230. @see GZIPCompressorOutputStream
  16231. */
  16232. class JUCE_API GZIPDecompressorInputStream : public InputStream
  16233. {
  16234. public:
  16235. /** Creates a decompressor stream.
  16236. @param sourceStream the stream to read from
  16237. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  16238. when this object is destroyed
  16239. @param noWrap this is used internally by the ZipFile class
  16240. and should be ignored by user applications
  16241. @param uncompressedStreamLength if the creator knows the length that the
  16242. uncompressed stream will be, then it can supply this
  16243. value, which will be returned by getTotalLength()
  16244. */
  16245. GZIPDecompressorInputStream (InputStream* sourceStream,
  16246. bool deleteSourceWhenDestroyed,
  16247. bool noWrap = false,
  16248. int64 uncompressedStreamLength = -1);
  16249. /** Creates a decompressor stream.
  16250. @param sourceStream the stream to read from - the source stream must not be
  16251. deleted until this object has been destroyed
  16252. */
  16253. GZIPDecompressorInputStream (InputStream& sourceStream);
  16254. /** Destructor. */
  16255. ~GZIPDecompressorInputStream();
  16256. int64 getPosition();
  16257. bool setPosition (int64 pos);
  16258. int64 getTotalLength();
  16259. bool isExhausted();
  16260. int read (void* destBuffer, int maxBytesToRead);
  16261. private:
  16262. OptionalScopedPointer<InputStream> sourceStream;
  16263. const int64 uncompressedStreamLength;
  16264. const bool noWrap;
  16265. bool isEof;
  16266. int activeBufferSize;
  16267. int64 originalSourcePos, currentPos;
  16268. HeapBlock <uint8> buffer;
  16269. class GZIPDecompressHelper;
  16270. friend class ScopedPointer <GZIPDecompressHelper>;
  16271. ScopedPointer <GZIPDecompressHelper> helper;
  16272. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  16273. };
  16274. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16275. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16276. #endif
  16277. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  16278. #endif
  16279. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  16280. #endif
  16281. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16282. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  16283. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16284. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16285. /**
  16286. Allows a block of data and to be accessed as a stream.
  16287. This can either be used to refer to a shared block of memory, or can make its
  16288. own internal copy of the data when the MemoryInputStream is created.
  16289. */
  16290. class JUCE_API MemoryInputStream : public InputStream
  16291. {
  16292. public:
  16293. /** Creates a MemoryInputStream.
  16294. @param sourceData the block of data to use as the stream's source
  16295. @param sourceDataSize the number of bytes in the source data block
  16296. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  16297. the source data, so this data shouldn't be changed
  16298. for the lifetime of the stream; if this parameter is
  16299. true, the stream will make its own copy of the
  16300. data and use that.
  16301. */
  16302. MemoryInputStream (const void* sourceData,
  16303. size_t sourceDataSize,
  16304. bool keepInternalCopyOfData);
  16305. /** Creates a MemoryInputStream.
  16306. @param data a block of data to use as the stream's source
  16307. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  16308. the source data, so this data shouldn't be changed
  16309. for the lifetime of the stream; if this parameter is
  16310. true, the stream will make its own copy of the
  16311. data and use that.
  16312. */
  16313. MemoryInputStream (const MemoryBlock& data,
  16314. bool keepInternalCopyOfData);
  16315. /** Destructor. */
  16316. ~MemoryInputStream();
  16317. int64 getPosition();
  16318. bool setPosition (int64 pos);
  16319. int64 getTotalLength();
  16320. bool isExhausted();
  16321. int read (void* destBuffer, int maxBytesToRead);
  16322. private:
  16323. const char* data;
  16324. size_t dataSize, position;
  16325. HeapBlock<char> internalCopy;
  16326. void createInternalCopy();
  16327. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  16328. };
  16329. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16330. /*** End of inlined file: juce_MemoryInputStream.h ***/
  16331. #endif
  16332. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16333. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  16334. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16335. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16336. /**
  16337. Writes data to an internal memory buffer, which grows as required.
  16338. The data that was written into the stream can then be accessed later as
  16339. a contiguous block of memory.
  16340. */
  16341. class JUCE_API MemoryOutputStream : public OutputStream
  16342. {
  16343. public:
  16344. /** Creates an empty memory stream ready for writing into.
  16345. @param initialSize the intial amount of capacity to allocate for writing into
  16346. */
  16347. MemoryOutputStream (size_t initialSize = 256);
  16348. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  16349. Note that the destination block will always be larger than the amount of data
  16350. that has been written to the stream, because the MemoryOutputStream keeps some
  16351. spare capactity at its end. To trim the block's size down to fit the actual
  16352. data, call flush(), or delete the MemoryOutputStream.
  16353. @param memoryBlockToWriteTo the block into which new data will be written.
  16354. @param appendToExistingBlockContent if this is true, the contents of the block will be
  16355. kept, and new data will be appended to it. If false,
  16356. the block will be cleared before use
  16357. */
  16358. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  16359. bool appendToExistingBlockContent);
  16360. /** Destructor.
  16361. This will free any data that was written to it.
  16362. */
  16363. ~MemoryOutputStream();
  16364. /** Returns a pointer to the data that has been written to the stream.
  16365. @see getDataSize
  16366. */
  16367. const void* getData() const noexcept;
  16368. /** Returns the number of bytes of data that have been written to the stream.
  16369. @see getData
  16370. */
  16371. size_t getDataSize() const noexcept { return size; }
  16372. /** Resets the stream, clearing any data that has been written to it so far. */
  16373. void reset() noexcept;
  16374. /** Increases the internal storage capacity to be able to contain at least the specified
  16375. amount of data without needing to be resized.
  16376. */
  16377. void preallocate (size_t bytesToPreallocate);
  16378. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  16379. String toUTF8() const;
  16380. /** Attempts to detect the encoding of the data and convert it to a string.
  16381. @see String::createStringFromData
  16382. */
  16383. String toString() const;
  16384. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  16385. capacity off the block, so that its length matches the amount of actual data that
  16386. has been written so far.
  16387. */
  16388. void flush();
  16389. bool write (const void* buffer, int howMany);
  16390. int64 getPosition() { return position; }
  16391. bool setPosition (int64 newPosition);
  16392. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  16393. void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  16394. private:
  16395. MemoryBlock& data;
  16396. MemoryBlock internalBlock;
  16397. size_t position, size;
  16398. void trimExternalBlockSize();
  16399. void prepareToWrite (int numBytes);
  16400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  16401. };
  16402. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  16403. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  16404. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16405. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  16406. #endif
  16407. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  16408. #endif
  16409. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16410. /*** Start of inlined file: juce_SubregionStream.h ***/
  16411. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16412. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16413. /** Wraps another input stream, and reads from a specific part of it.
  16414. This lets you take a subsection of a stream and present it as an entire
  16415. stream in its own right.
  16416. */
  16417. class JUCE_API SubregionStream : public InputStream
  16418. {
  16419. public:
  16420. /** Creates a SubregionStream from an input source.
  16421. @param sourceStream the source stream to read from
  16422. @param startPositionInSourceStream this is the position in the source stream that
  16423. corresponds to position 0 in this stream
  16424. @param lengthOfSourceStream this specifies the maximum number of bytes
  16425. from the source stream that will be passed through
  16426. by this stream. When the position of this stream
  16427. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  16428. If the length passed in here is greater than the length
  16429. of the source stream (as returned by getTotalLength()),
  16430. then the smaller value will be used.
  16431. Passing a negative value for this parameter means it
  16432. will keep reading until the source's end-of-stream.
  16433. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16434. deleted by this object when it is itself deleted.
  16435. */
  16436. SubregionStream (InputStream* sourceStream,
  16437. int64 startPositionInSourceStream,
  16438. int64 lengthOfSourceStream,
  16439. bool deleteSourceWhenDestroyed);
  16440. /** Destructor.
  16441. This may also delete the source stream, if that option was chosen when the
  16442. buffered stream was created.
  16443. */
  16444. ~SubregionStream();
  16445. int64 getTotalLength();
  16446. int64 getPosition();
  16447. bool setPosition (int64 newPosition);
  16448. int read (void* destBuffer, int maxBytesToRead);
  16449. bool isExhausted();
  16450. private:
  16451. OptionalScopedPointer<InputStream> source;
  16452. const int64 startPositionInSourceStream, lengthOfSourceStream;
  16453. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  16454. };
  16455. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16456. /*** End of inlined file: juce_SubregionStream.h ***/
  16457. #endif
  16458. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  16459. #endif
  16460. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16461. /*** Start of inlined file: juce_Expression.h ***/
  16462. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16463. #define __JUCE_EXPRESSION_JUCEHEADER__
  16464. /**
  16465. A class for dynamically evaluating simple numeric expressions.
  16466. This class can parse a simple C-style string expression involving floating point
  16467. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  16468. are supported, as well as parentheses, and any alphanumeric identifiers are
  16469. assumed to be named symbols which will be resolved when the expression is
  16470. evaluated.
  16471. Expressions which use identifiers and functions require a subclass of
  16472. Expression::Scope to be supplied when evaluating them, and this object
  16473. is expected to be able to resolve the symbol names and perform the functions that
  16474. are used.
  16475. */
  16476. class JUCE_API Expression
  16477. {
  16478. public:
  16479. /** Creates a simple expression with a value of 0. */
  16480. Expression();
  16481. /** Destructor. */
  16482. ~Expression();
  16483. /** Creates a simple expression with a specified constant value. */
  16484. explicit Expression (double constant);
  16485. /** Creates a copy of an expression. */
  16486. Expression (const Expression& other);
  16487. /** Copies another expression. */
  16488. Expression& operator= (const Expression& other);
  16489. /** Creates an expression by parsing a string.
  16490. If there's a syntax error in the string, this will throw a ParseError exception.
  16491. @throws ParseError
  16492. */
  16493. explicit Expression (const String& stringToParse);
  16494. /** Returns a string version of the expression. */
  16495. String toString() const;
  16496. /** Returns an expression which is an addtion operation of two existing expressions. */
  16497. Expression operator+ (const Expression& other) const;
  16498. /** Returns an expression which is a subtraction operation of two existing expressions. */
  16499. Expression operator- (const Expression& other) const;
  16500. /** Returns an expression which is a multiplication operation of two existing expressions. */
  16501. Expression operator* (const Expression& other) const;
  16502. /** Returns an expression which is a division operation of two existing expressions. */
  16503. Expression operator/ (const Expression& other) const;
  16504. /** Returns an expression which performs a negation operation on an existing expression. */
  16505. Expression operator-() const;
  16506. /** Returns an Expression which is an identifier reference. */
  16507. static Expression symbol (const String& symbol);
  16508. /** Returns an Expression which is a function call. */
  16509. static Expression function (const String& functionName, const Array<Expression>& parameters);
  16510. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  16511. to indicate where it finished.
  16512. The pointer is incremented so that on return, it indicates the character that follows
  16513. the end of the expression that was parsed.
  16514. If there's a syntax error in the string, this will throw a ParseError exception.
  16515. @throws ParseError
  16516. */
  16517. static Expression parse (String::CharPointerType& stringToParse);
  16518. /** When evaluating an Expression object, this class is used to resolve symbols and
  16519. perform functions that the expression uses.
  16520. */
  16521. class JUCE_API Scope
  16522. {
  16523. public:
  16524. Scope();
  16525. virtual ~Scope();
  16526. /** Returns some kind of globally unique ID that identifies this scope. */
  16527. virtual const String getScopeUID() const;
  16528. /** Returns the value of a symbol.
  16529. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  16530. The member value is set to the part of the symbol that followed the dot, if there is
  16531. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  16532. @throws Expression::EvaluationError
  16533. */
  16534. virtual const Expression getSymbolValue (const String& symbol) const;
  16535. /** Executes a named function.
  16536. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  16537. @throws Expression::EvaluationError
  16538. */
  16539. virtual double evaluateFunction (const String& functionName,
  16540. const double* parameters, int numParameters) const;
  16541. /** Used as a callback by the Scope::visitRelativeScope() method.
  16542. You should never create an instance of this class yourself, it's used by the
  16543. expression evaluation code.
  16544. */
  16545. class Visitor
  16546. {
  16547. public:
  16548. virtual ~Visitor() {}
  16549. virtual void visit (const Scope&) = 0;
  16550. };
  16551. /** Creates a Scope object for a named scope, and then calls a visitor
  16552. to do some kind of processing with this new scope.
  16553. If the name is valid, this method must create a suitable (temporary) Scope
  16554. object to represent it, and must call the Visitor::visit() method with this
  16555. new scope.
  16556. */
  16557. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  16558. };
  16559. /** Evaluates this expression, without using a Scope.
  16560. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  16561. min, max are available.
  16562. To find out about any errors during evaluation, use the other version of this method which
  16563. takes a String parameter.
  16564. */
  16565. double evaluate() const;
  16566. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16567. or functions that it uses.
  16568. To find out about any errors during evaluation, use the other version of this method which
  16569. takes a String parameter.
  16570. */
  16571. double evaluate (const Scope& scope) const;
  16572. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16573. or functions that it uses.
  16574. */
  16575. double evaluate (const Scope& scope, String& evaluationError) const;
  16576. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  16577. to make the expression resolve to a target value.
  16578. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  16579. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  16580. case they might just be adjusted by adding a constant to the original expression.
  16581. @throws Expression::EvaluationError
  16582. */
  16583. Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  16584. /** Represents a symbol that is used in an Expression. */
  16585. struct Symbol
  16586. {
  16587. Symbol (const String& scopeUID, const String& symbolName);
  16588. bool operator== (const Symbol&) const noexcept;
  16589. bool operator!= (const Symbol&) const noexcept;
  16590. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  16591. String symbolName; /**< The name of the symbol. */
  16592. };
  16593. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  16594. Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  16595. /** Returns true if this expression makes use of the specified symbol.
  16596. If a suitable scope is supplied, the search will dereference and recursively check
  16597. all symbols, so that it can be determined whether this expression relies on the given
  16598. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  16599. whether the expression contains any direct references to the symbol.
  16600. @throws Expression::EvaluationError
  16601. */
  16602. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  16603. /** Returns true if this expression contains any symbols. */
  16604. bool usesAnySymbols() const;
  16605. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  16606. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  16607. /** An exception that can be thrown by Expression::parse(). */
  16608. class ParseError : public std::exception
  16609. {
  16610. public:
  16611. ParseError (const String& message);
  16612. String description;
  16613. };
  16614. /** Expression type.
  16615. @see Expression::getType()
  16616. */
  16617. enum Type
  16618. {
  16619. constantType,
  16620. functionType,
  16621. operatorType,
  16622. symbolType
  16623. };
  16624. /** Returns the type of this expression. */
  16625. Type getType() const noexcept;
  16626. /** If this expression is a symbol, function or operator, this returns its identifier. */
  16627. String getSymbolOrFunction() const;
  16628. /** Returns the number of inputs to this expression.
  16629. @see getInput
  16630. */
  16631. int getNumInputs() const;
  16632. /** Retrieves one of the inputs to this expression.
  16633. @see getNumInputs
  16634. */
  16635. Expression getInput (int index) const;
  16636. private:
  16637. class Term;
  16638. class Helpers;
  16639. friend class Term;
  16640. friend class Helpers;
  16641. friend class ScopedPointer<Term>;
  16642. friend class ReferenceCountedObjectPtr<Term>;
  16643. ReferenceCountedObjectPtr<Term> term;
  16644. explicit Expression (Term* term);
  16645. };
  16646. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  16647. /*** End of inlined file: juce_Expression.h ***/
  16648. #endif
  16649. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  16650. #endif
  16651. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16652. /*** Start of inlined file: juce_Random.h ***/
  16653. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16654. #define __JUCE_RANDOM_JUCEHEADER__
  16655. /**
  16656. A random number generator.
  16657. You can create a Random object and use it to generate a sequence of random numbers.
  16658. As a handy shortcut to avoid having to create and seed one yourself, you can call
  16659. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  16660. app launches.
  16661. */
  16662. class JUCE_API Random
  16663. {
  16664. public:
  16665. /** Creates a Random object based on a seed value.
  16666. For a given seed value, the subsequent numbers generated by this object
  16667. will be predictable, so a good idea is to set this value based
  16668. on the time, e.g.
  16669. new Random (Time::currentTimeMillis())
  16670. */
  16671. explicit Random (int64 seedValue) noexcept;
  16672. /** Creates a Random object using a random seed value.
  16673. Internally, this calls setSeedRandomly() to randomise the seed.
  16674. */
  16675. Random();
  16676. /** Destructor. */
  16677. ~Random() noexcept;
  16678. /** Returns the next random 32 bit integer.
  16679. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  16680. */
  16681. int nextInt() noexcept;
  16682. /** Returns the next random number, limited to a given range.
  16683. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  16684. */
  16685. int nextInt (int maxValue) noexcept;
  16686. /** Returns the next 64-bit random number.
  16687. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  16688. */
  16689. int64 nextInt64() noexcept;
  16690. /** Returns the next random floating-point number.
  16691. @returns a random value in the range 0 to 1.0
  16692. */
  16693. float nextFloat() noexcept;
  16694. /** Returns the next random floating-point number.
  16695. @returns a random value in the range 0 to 1.0
  16696. */
  16697. double nextDouble() noexcept;
  16698. /** Returns the next random boolean value.
  16699. */
  16700. bool nextBool() noexcept;
  16701. /** Returns a BigInteger containing a random number.
  16702. @returns a random value in the range 0 to (maximumValue - 1).
  16703. */
  16704. BigInteger nextLargeNumber (const BigInteger& maximumValue);
  16705. /** Sets a range of bits in a BigInteger to random values. */
  16706. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  16707. /** To avoid the overhead of having to create a new Random object whenever
  16708. you need a number, this is a shared application-wide object that
  16709. can be used.
  16710. It's not thread-safe though, so threads should use their own Random object.
  16711. */
  16712. static Random& getSystemRandom() noexcept;
  16713. /** Resets this Random object to a given seed value. */
  16714. void setSeed (int64 newSeed) noexcept;
  16715. /** Merges this object's seed with another value.
  16716. This sets the seed to be a value created by combining the current seed and this
  16717. new value.
  16718. */
  16719. void combineSeed (int64 seedValue) noexcept;
  16720. /** Reseeds this generator using a value generated from various semi-random system
  16721. properties like the current time, etc.
  16722. Because this function convolves the time with the last seed value, calling
  16723. it repeatedly will increase the randomness of the final result.
  16724. */
  16725. void setSeedRandomly();
  16726. private:
  16727. int64 seed;
  16728. JUCE_LEAK_DETECTOR (Random);
  16729. };
  16730. #endif // __JUCE_RANDOM_JUCEHEADER__
  16731. /*** End of inlined file: juce_Random.h ***/
  16732. #endif
  16733. #ifndef __JUCE_RANGE_JUCEHEADER__
  16734. #endif
  16735. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16736. #endif
  16737. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16738. #endif
  16739. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16740. #endif
  16741. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16742. #endif
  16743. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16744. #endif
  16745. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16746. #endif
  16747. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16748. #endif
  16749. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16750. #endif
  16751. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16752. #endif
  16753. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16754. /*** Start of inlined file: juce_WeakReference.h ***/
  16755. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16756. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16757. /**
  16758. This class acts as a pointer which will automatically become null if the object
  16759. to which it points is deleted.
  16760. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16761. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16762. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16763. E.g.
  16764. @code
  16765. class MyObject
  16766. {
  16767. public:
  16768. MyObject()
  16769. {
  16770. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16771. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16772. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16773. // the first call to getWeakReference().
  16774. }
  16775. ~MyObject()
  16776. {
  16777. // This will zero all the references - you need to call this in your destructor.
  16778. masterReference.clear();
  16779. }
  16780. // Your object must provide a method that looks pretty much identical to this (except
  16781. // for the templated class name, of course).
  16782. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16783. {
  16784. return masterReference (this);
  16785. }
  16786. private:
  16787. // You need to embed one of these inside your object. It can be private.
  16788. WeakReference<MyObject>::Master masterReference;
  16789. };
  16790. // Here's an example of using a pointer..
  16791. MyObject* n = new MyObject();
  16792. WeakReference<MyObject> myObjectRef = n;
  16793. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16794. delete n;
  16795. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16796. @endcode
  16797. @see WeakReference::Master
  16798. */
  16799. template <class ObjectType, class ReferenceCountingType = ReferenceCountedObject>
  16800. class WeakReference
  16801. {
  16802. public:
  16803. /** Creates a null SafePointer. */
  16804. inline WeakReference() noexcept {}
  16805. /** Creates a WeakReference that points at the given object. */
  16806. WeakReference (ObjectType* const object) : holder (object != nullptr ? object->getWeakReference() : nullptr) {}
  16807. /** Creates a copy of another WeakReference. */
  16808. WeakReference (const WeakReference& other) noexcept : holder (other.holder) {}
  16809. /** Copies another pointer to this one. */
  16810. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16811. /** Copies another pointer to this one. */
  16812. WeakReference& operator= (ObjectType* const newObject) { holder = (newObject != nullptr) ? newObject->getWeakReference() : nullptr; return *this; }
  16813. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16814. ObjectType* get() const noexcept { return holder != nullptr ? holder->get() : nullptr; }
  16815. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16816. operator ObjectType*() const noexcept { return get(); }
  16817. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16818. ObjectType* operator->() noexcept { return get(); }
  16819. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16820. const ObjectType* operator->() const noexcept { return get(); }
  16821. /** This returns true if this reference has been pointing at an object, but that object has
  16822. since been deleted.
  16823. If this reference was only ever pointing at a null pointer, this will return false. Using
  16824. operator=() to make this refer to a different object will reset this flag to match the status
  16825. of the reference from which you're copying.
  16826. */
  16827. bool wasObjectDeleted() const noexcept { return holder != nullptr && holder->get() == nullptr; }
  16828. bool operator== (ObjectType* const object) const noexcept { return get() == object; }
  16829. bool operator!= (ObjectType* const object) const noexcept { return get() != object; }
  16830. /** This class is used internally by the WeakReference class - don't use it directly
  16831. in your code!
  16832. @see WeakReference
  16833. */
  16834. class SharedPointer : public ReferenceCountingType
  16835. {
  16836. public:
  16837. explicit SharedPointer (ObjectType* const owner_) noexcept : owner (owner_) {}
  16838. inline ObjectType* get() const noexcept { return owner; }
  16839. void clearPointer() noexcept { owner = nullptr; }
  16840. private:
  16841. ObjectType* volatile owner;
  16842. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16843. };
  16844. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16845. /**
  16846. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16847. See the WeakReference class notes for an example of how to use this class.
  16848. @see WeakReference
  16849. */
  16850. class Master
  16851. {
  16852. public:
  16853. Master() noexcept {}
  16854. ~Master()
  16855. {
  16856. // You must remember to call clear() in your source object's destructor! See the notes
  16857. // for the WeakReference class for an example of how to do this.
  16858. jassert (sharedPointer == nullptr || sharedPointer->get() == nullptr);
  16859. }
  16860. /** The first call to this method will create an internal object that is shared by all weak
  16861. references to the object.
  16862. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16863. class notes for an example.
  16864. */
  16865. const SharedRef& operator() (ObjectType* const object)
  16866. {
  16867. if (sharedPointer == nullptr)
  16868. {
  16869. sharedPointer = new SharedPointer (object);
  16870. }
  16871. else
  16872. {
  16873. // You're trying to create a weak reference to an object that has already been deleted!!
  16874. jassert (sharedPointer->get() != nullptr);
  16875. }
  16876. return sharedPointer;
  16877. }
  16878. /** The object that owns this master pointer should call this before it gets destroyed,
  16879. to zero all the references to this object that may be out there. See the WeakReference
  16880. class notes for an example of how to do this.
  16881. */
  16882. void clear()
  16883. {
  16884. if (sharedPointer != nullptr)
  16885. sharedPointer->clearPointer();
  16886. }
  16887. private:
  16888. SharedRef sharedPointer;
  16889. JUCE_DECLARE_NON_COPYABLE (Master);
  16890. };
  16891. private:
  16892. SharedRef holder;
  16893. };
  16894. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16895. /*** End of inlined file: juce_WeakReference.h ***/
  16896. #endif
  16897. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16898. #endif
  16899. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16900. #endif
  16901. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16902. #endif
  16903. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16904. #endif
  16905. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16906. #endif
  16907. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16908. #endif
  16909. #ifndef __JUCE_JSON_JUCEHEADER__
  16910. /*** Start of inlined file: juce_JSON.h ***/
  16911. #ifndef __JUCE_JSON_JUCEHEADER__
  16912. #define __JUCE_JSON_JUCEHEADER__
  16913. class InputStream;
  16914. class OutputStream;
  16915. class File;
  16916. /**
  16917. Contains static methods for converting JSON-formatted text to and from var objects.
  16918. The var class is structurally compatible with JSON-formatted data, so these
  16919. functions allow you to parse JSON into a var object, and to convert a var
  16920. object to JSON-formatted text.
  16921. @see var
  16922. */
  16923. class JSON
  16924. {
  16925. public:
  16926. /** Parses a string of JSON-formatted text, and returns a result code containing
  16927. any parse errors.
  16928. This will return the parsed structure in the parsedResult parameter, and will
  16929. return a Result object to indicate whether parsing was successful, and if not,
  16930. it will contain an error message.
  16931. If you're not interested in the error message, you can use one of the other
  16932. shortcut parse methods, which simply return a var::null if the parsing fails.
  16933. */
  16934. static Result parse (const String& text, var& parsedResult);
  16935. /** Attempts to parse some JSON-formatted text, and returns the result as a var object.
  16936. If the parsing fails, this simply returns var::null - if you need to find out more
  16937. detail about the parse error, use the alternative parse() method which returns a Result.
  16938. */
  16939. static var parse (const String& text);
  16940. /** Attempts to parse some JSON-formatted text from a file, and returns the result
  16941. as a var object.
  16942. Note that this is just a short-cut for reading the entire file into a string and
  16943. parsing the result.
  16944. If the parsing fails, this simply returns var::null - if you need to find out more
  16945. detail about the parse error, use the alternative parse() method which returns a Result.
  16946. */
  16947. static var parse (const File& file);
  16948. /** Attempts to parse some JSON-formatted text from a stream, and returns the result
  16949. as a var object.
  16950. Note that this is just a short-cut for reading the entire stream into a string and
  16951. parsing the result.
  16952. If the parsing fails, this simply returns var::null - if you need to find out more
  16953. detail about the parse error, use the alternative parse() method which returns a Result.
  16954. */
  16955. static var parse (InputStream& input);
  16956. /** Returns a string which contains a JSON-formatted representation of the var object.
  16957. If allOnOneLine is true, the result will be compacted into a single line of text
  16958. with no carriage-returns. If false, it will be laid-out in a more human-readable format.
  16959. @see writeToStream
  16960. */
  16961. static String toString (const var& objectToFormat,
  16962. bool allOnOneLine = false);
  16963. /** Writes a JSON-formatted representation of the var object to the given stream.
  16964. If allOnOneLine is true, the result will be compacted into a single line of text
  16965. with no carriage-returns. If false, it will be laid-out in a more human-readable format.
  16966. @see toString
  16967. */
  16968. static void writeToStream (OutputStream& output,
  16969. const var& objectToFormat,
  16970. bool allOnOneLine = false);
  16971. private:
  16972. JSON(); // This class can't be instantiated - just use its static methods.
  16973. };
  16974. #endif // __JUCE_JSON_JUCEHEADER__
  16975. /*** End of inlined file: juce_JSON.h ***/
  16976. #endif
  16977. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16978. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16979. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16980. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16981. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16982. string into a localised version using the LocalisedStrings class.
  16983. @see LocalisedStrings
  16984. */
  16985. #define TRANS(stringLiteral) \
  16986. JUCE_NAMESPACE::LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16987. /**
  16988. Used to convert strings to localised foreign-language versions.
  16989. This is basically a look-up table of strings and their translated equivalents.
  16990. It can be loaded from a text file, so that you can supply a set of localised
  16991. versions of strings that you use in your app.
  16992. To use it in your code, simply call the translate() method on each string that
  16993. might have foreign versions, and if none is found, the method will just return
  16994. the original string.
  16995. The translation file should start with some lines specifying a description of
  16996. the language it contains, and also a list of ISO country codes where it might
  16997. be appropriate to use the file. After that, each line of the file should contain
  16998. a pair of quoted strings with an '=' sign.
  16999. E.g. for a french translation, the file might be:
  17000. @code
  17001. language: French
  17002. countries: fr be mc ch lu
  17003. "hello" = "bonjour"
  17004. "goodbye" = "au revoir"
  17005. @endcode
  17006. If the strings need to contain a quote character, they can use '\"' instead, and
  17007. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  17008. (you can use this to add comments).
  17009. Note that this is a singleton class, so don't create or destroy the object directly.
  17010. There's also a TRANS(text) macro defined to make it easy to use the this.
  17011. E.g. @code
  17012. printSomething (TRANS("hello"));
  17013. @endcode
  17014. This macro is used in the Juce classes themselves, so your application has a chance to
  17015. intercept and translate any internal Juce text strings that might be shown. (You can easily
  17016. get a list of all the messages by searching for the TRANS() macro in the Juce source
  17017. code).
  17018. */
  17019. class JUCE_API LocalisedStrings
  17020. {
  17021. public:
  17022. /** Creates a set of translations from the text of a translation file.
  17023. When you create one of these, you can call setCurrentMappings() to make it
  17024. the set of mappings that the system's using.
  17025. */
  17026. LocalisedStrings (const String& fileContents);
  17027. /** Creates a set of translations from a file.
  17028. When you create one of these, you can call setCurrentMappings() to make it
  17029. the set of mappings that the system's using.
  17030. */
  17031. LocalisedStrings (const File& fileToLoad);
  17032. /** Destructor. */
  17033. ~LocalisedStrings();
  17034. /** Selects the current set of mappings to be used by the system.
  17035. The object you pass in will be automatically deleted when no longer needed, so
  17036. don't keep a pointer to it. You can also pass in zero to remove the current
  17037. mappings.
  17038. See also the TRANS() macro, which uses the current set to do its translation.
  17039. @see translateWithCurrentMappings
  17040. */
  17041. static void setCurrentMappings (LocalisedStrings* newTranslations);
  17042. /** Returns the currently selected set of mappings.
  17043. This is the object that was last passed to setCurrentMappings(). It may
  17044. be 0 if none has been created.
  17045. */
  17046. static LocalisedStrings* getCurrentMappings();
  17047. /** Tries to translate a string using the currently selected set of mappings.
  17048. If no mapping has been set, or if the mapping doesn't contain a translation
  17049. for the string, this will just return the original string.
  17050. See also the TRANS() macro, which uses this method to do its translation.
  17051. @see setCurrentMappings, getCurrentMappings
  17052. */
  17053. static String translateWithCurrentMappings (const String& text);
  17054. /** Tries to translate a string using the currently selected set of mappings.
  17055. If no mapping has been set, or if the mapping doesn't contain a translation
  17056. for the string, this will just return the original string.
  17057. See also the TRANS() macro, which uses this method to do its translation.
  17058. @see setCurrentMappings, getCurrentMappings
  17059. */
  17060. static String translateWithCurrentMappings (const char* text);
  17061. /** Attempts to look up a string and return its localised version.
  17062. If the string isn't found in the list, the original string will be returned.
  17063. */
  17064. String translate (const String& text) const;
  17065. /** Returns the name of the language specified in the translation file.
  17066. This is specified in the file using a line starting with "language:", e.g.
  17067. @code
  17068. language: german
  17069. @endcode
  17070. */
  17071. String getLanguageName() const { return languageName; }
  17072. /** Returns the list of suitable country codes listed in the translation file.
  17073. These is specified in the file using a line starting with "countries:", e.g.
  17074. @code
  17075. countries: fr be mc ch lu
  17076. @endcode
  17077. The country codes are supposed to be 2-character ISO complient codes.
  17078. */
  17079. const StringArray getCountryCodes() const { return countryCodes; }
  17080. /** Indicates whether to use a case-insensitive search when looking up a string.
  17081. This defaults to true.
  17082. */
  17083. void setIgnoresCase (bool shouldIgnoreCase);
  17084. private:
  17085. String languageName;
  17086. StringArray countryCodes;
  17087. StringPairArray translations;
  17088. void loadFromText (const String& fileContents);
  17089. JUCE_LEAK_DETECTOR (LocalisedStrings);
  17090. };
  17091. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  17092. /*** End of inlined file: juce_LocalisedStrings.h ***/
  17093. #endif
  17094. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  17095. #endif
  17096. #ifndef __JUCE_STRING_JUCEHEADER__
  17097. #endif
  17098. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  17099. #endif
  17100. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  17101. #endif
  17102. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  17103. /*** Start of inlined file: juce_StringPool.h ***/
  17104. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  17105. #define __JUCE_STRINGPOOL_JUCEHEADER__
  17106. /**
  17107. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  17108. comparison speed when dealing with many duplicate strings.
  17109. When you add a string to a pool using getPooledString, it'll return a character
  17110. array containing the same string. This array is owned by the pool, and the same array
  17111. is returned every time a matching string is asked for. This means that it's trivial to
  17112. compare two pooled strings for equality, as you can simply compare their pointers. It
  17113. also cuts down on storage if you're using many copies of the same string.
  17114. */
  17115. class JUCE_API StringPool
  17116. {
  17117. public:
  17118. /** Creates an empty pool. */
  17119. StringPool() noexcept;
  17120. /** Destructor */
  17121. ~StringPool();
  17122. /** Returns a pointer to a copy of the string that is passed in.
  17123. The pool will always return the same pointer when asked for a string that matches it.
  17124. The pool will own all the pointers that it returns, deleting them when the pool itself
  17125. is deleted.
  17126. */
  17127. const String::CharPointerType getPooledString (const String& original);
  17128. /** Returns a pointer to a copy of the string that is passed in.
  17129. The pool will always return the same pointer when asked for a string that matches it.
  17130. The pool will own all the pointers that it returns, deleting them when the pool itself
  17131. is deleted.
  17132. */
  17133. const String::CharPointerType getPooledString (const char* original);
  17134. /** Returns a pointer to a copy of the string that is passed in.
  17135. The pool will always return the same pointer when asked for a string that matches it.
  17136. The pool will own all the pointers that it returns, deleting them when the pool itself
  17137. is deleted.
  17138. */
  17139. const String::CharPointerType getPooledString (const wchar_t* original);
  17140. /** Returns the number of strings in the pool. */
  17141. int size() const noexcept;
  17142. /** Returns one of the strings in the pool, by index. */
  17143. const String::CharPointerType operator[] (int index) const noexcept;
  17144. private:
  17145. Array <String> strings;
  17146. };
  17147. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  17148. /*** End of inlined file: juce_StringPool.h ***/
  17149. #endif
  17150. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  17151. /*** Start of inlined file: juce_XmlDocument.h ***/
  17152. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  17153. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  17154. class InputSource;
  17155. /**
  17156. Parses a text-based XML document and creates an XmlElement object from it.
  17157. The parser will parse DTDs to load external entities but won't
  17158. check the document for validity against the DTD.
  17159. e.g.
  17160. @code
  17161. XmlDocument myDocument (File ("myfile.xml"));
  17162. XmlElement* mainElement = myDocument.getDocumentElement();
  17163. if (mainElement == nullptr)
  17164. {
  17165. String error = myDocument.getLastParseError();
  17166. }
  17167. else
  17168. {
  17169. ..use the element
  17170. }
  17171. @endcode
  17172. Or you can use the static helper methods for quick parsing..
  17173. @code
  17174. XmlElement* xml = XmlDocument::parse (myXmlFile);
  17175. if (xml != nullptr && xml->hasTagName ("foobar"))
  17176. {
  17177. ...etc
  17178. @endcode
  17179. @see XmlElement
  17180. */
  17181. class JUCE_API XmlDocument
  17182. {
  17183. public:
  17184. /** Creates an XmlDocument from the xml text.
  17185. The text doesn't actually get parsed until the getDocumentElement() method is called.
  17186. */
  17187. XmlDocument (const String& documentText);
  17188. /** Creates an XmlDocument from a file.
  17189. The text doesn't actually get parsed until the getDocumentElement() method is called.
  17190. */
  17191. XmlDocument (const File& file);
  17192. /** Destructor. */
  17193. ~XmlDocument();
  17194. /** Creates an XmlElement object to represent the main document node.
  17195. This method will do the actual parsing of the text, and if there's a
  17196. parse error, it may returns 0 (and you can find out the error using
  17197. the getLastParseError() method).
  17198. See also the parse() methods, which provide a shorthand way to quickly
  17199. parse a file or string.
  17200. @param onlyReadOuterDocumentElement if true, the parser will only read the
  17201. first section of the file, and will only
  17202. return the outer document element - this
  17203. allows quick checking of large files to
  17204. see if they contain the correct type of
  17205. tag, without having to parse the entire file
  17206. @returns a new XmlElement which the caller will need to delete, or null if
  17207. there was an error.
  17208. @see getLastParseError
  17209. */
  17210. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  17211. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  17212. @returns the error, or an empty string if there was no error.
  17213. */
  17214. const String& getLastParseError() const noexcept;
  17215. /** Sets an input source object to use for parsing documents that reference external entities.
  17216. If the document has been created from a file, this probably won't be needed, but
  17217. if you're parsing some text and there might be a DTD that references external
  17218. files, you may need to create a custom input source that can retrieve the
  17219. other files it needs.
  17220. The object that is passed-in will be deleted automatically when no longer needed.
  17221. @see InputSource
  17222. */
  17223. void setInputSource (InputSource* newSource) noexcept;
  17224. /** Sets a flag to change the treatment of empty text elements.
  17225. If this is true (the default state), then any text elements that contain only
  17226. whitespace characters will be ingored during parsing. If you need to catch
  17227. whitespace-only text, then you should set this to false before calling the
  17228. getDocumentElement() method.
  17229. */
  17230. void setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept;
  17231. /** A handy static method that parses a file.
  17232. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17233. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17234. */
  17235. static XmlElement* parse (const File& file);
  17236. /** A handy static method that parses some XML data.
  17237. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17238. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17239. */
  17240. static XmlElement* parse (const String& xmlData);
  17241. private:
  17242. String originalText;
  17243. String::CharPointerType input;
  17244. bool outOfData, errorOccurred;
  17245. String lastError, dtdText;
  17246. StringArray tokenisedDTD;
  17247. bool needToLoadDTD, ignoreEmptyTextElements;
  17248. ScopedPointer <InputSource> inputSource;
  17249. void setLastError (const String& desc, bool carryOn);
  17250. void skipHeader();
  17251. void skipNextWhiteSpace();
  17252. juce_wchar readNextChar() noexcept;
  17253. XmlElement* readNextElement (bool alsoParseSubElements);
  17254. void readChildElements (XmlElement* parent);
  17255. int findNextTokenLength() noexcept;
  17256. void readQuotedString (String& result);
  17257. void readEntity (String& result);
  17258. String getFileContents (const String& filename) const;
  17259. String expandEntity (const String& entity);
  17260. String expandExternalEntity (const String& entity);
  17261. String getParameterEntity (const String& entity);
  17262. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  17263. };
  17264. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  17265. /*** End of inlined file: juce_XmlDocument.h ***/
  17266. #endif
  17267. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  17268. #endif
  17269. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  17270. #endif
  17271. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17272. /*** Start of inlined file: juce_InterProcessLock.h ***/
  17273. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17274. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17275. /**
  17276. Acts as a critical section which processes can use to block each other.
  17277. @see CriticalSection
  17278. */
  17279. class JUCE_API InterProcessLock
  17280. {
  17281. public:
  17282. /** Creates a lock object.
  17283. @param name a name that processes will use to identify this lock object
  17284. */
  17285. explicit InterProcessLock (const String& name);
  17286. /** Destructor.
  17287. This will also release the lock if it's currently held by this process.
  17288. */
  17289. ~InterProcessLock();
  17290. /** Attempts to lock the critical section.
  17291. @param timeOutMillisecs how many milliseconds to wait if the lock
  17292. is already held by another process - a value of
  17293. 0 will return immediately, negative values will wait
  17294. forever
  17295. @returns true if the lock could be gained within the timeout period, or
  17296. false if the timeout expired.
  17297. */
  17298. bool enter (int timeOutMillisecs = -1);
  17299. /** Releases the lock if it's currently held by this process.
  17300. */
  17301. void exit();
  17302. /**
  17303. Automatically locks and unlocks an InterProcessLock object.
  17304. This works like a ScopedLock, but using an InterprocessLock rather than
  17305. a CriticalSection.
  17306. @see ScopedLock
  17307. */
  17308. class ScopedLockType
  17309. {
  17310. public:
  17311. /** Creates a scoped lock.
  17312. As soon as it is created, this will lock the InterProcessLock, and
  17313. when the ScopedLockType object is deleted, the InterProcessLock will
  17314. be unlocked.
  17315. Note that since an InterprocessLock can fail due to errors, you should check
  17316. isLocked() to make sure that the lock was successful before using it.
  17317. Make sure this object is created and deleted by the same thread,
  17318. otherwise there are no guarantees what will happen! Best just to use it
  17319. as a local stack object, rather than creating one with the new() operator.
  17320. */
  17321. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  17322. /** Destructor.
  17323. The InterProcessLock will be unlocked when the destructor is called.
  17324. Make sure this object is created and deleted by the same thread,
  17325. otherwise there are no guarantees what will happen!
  17326. */
  17327. inline ~ScopedLockType() { lock_.exit(); }
  17328. /** Returns true if the InterProcessLock was successfully locked. */
  17329. bool isLocked() const noexcept { return lockWasSuccessful; }
  17330. private:
  17331. InterProcessLock& lock_;
  17332. bool lockWasSuccessful;
  17333. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  17334. };
  17335. private:
  17336. class Pimpl;
  17337. friend class ScopedPointer <Pimpl>;
  17338. ScopedPointer <Pimpl> pimpl;
  17339. CriticalSection lock;
  17340. String name;
  17341. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  17342. };
  17343. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17344. /*** End of inlined file: juce_InterProcessLock.h ***/
  17345. #endif
  17346. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17347. /*** Start of inlined file: juce_Process.h ***/
  17348. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17349. #define __JUCE_PROCESS_JUCEHEADER__
  17350. /** Represents the current executable's process.
  17351. This contains methods for controlling the current application at the
  17352. process-level.
  17353. @see Thread, JUCEApplication
  17354. */
  17355. class JUCE_API Process
  17356. {
  17357. public:
  17358. enum ProcessPriority
  17359. {
  17360. LowPriority = 0,
  17361. NormalPriority = 1,
  17362. HighPriority = 2,
  17363. RealtimePriority = 3
  17364. };
  17365. /** Changes the current process's priority.
  17366. @param priority the process priority, where
  17367. 0=low, 1=normal, 2=high, 3=realtime
  17368. */
  17369. static void setPriority (const ProcessPriority priority);
  17370. /** Kills the current process immediately.
  17371. This is an emergency process terminator that kills the application
  17372. immediately - it's intended only for use only when something goes
  17373. horribly wrong.
  17374. @see JUCEApplication::quit
  17375. */
  17376. static void terminate();
  17377. /** Returns true if this application process is the one that the user is
  17378. currently using.
  17379. */
  17380. static bool isForegroundProcess();
  17381. /** Raises the current process's privilege level.
  17382. Does nothing if this isn't supported by the current OS, or if process
  17383. privilege level is fixed.
  17384. */
  17385. static void raisePrivilege();
  17386. /** Lowers the current process's privilege level.
  17387. Does nothing if this isn't supported by the current OS, or if process
  17388. privilege level is fixed.
  17389. */
  17390. static void lowerPrivilege();
  17391. /** Returns true if this process is being hosted by a debugger.
  17392. */
  17393. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  17394. private:
  17395. Process();
  17396. JUCE_DECLARE_NON_COPYABLE (Process);
  17397. };
  17398. #endif // __JUCE_PROCESS_JUCEHEADER__
  17399. /*** End of inlined file: juce_Process.h ***/
  17400. #endif
  17401. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17402. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  17403. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17404. #define __JUCE_READWRITELOCK_JUCEHEADER__
  17405. /*** Start of inlined file: juce_SpinLock.h ***/
  17406. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17407. #define __JUCE_SPINLOCK_JUCEHEADER__
  17408. /**
  17409. A simple spin-lock class that can be used as a simple, low-overhead mutex for
  17410. uncontended situations.
  17411. Note that unlike a CriticalSection, this type of lock is not re-entrant, and may
  17412. be less efficient when used it a highly contended situation, but it's very small and
  17413. requires almost no initialisation.
  17414. It's most appropriate for simple situations where you're only going to hold the
  17415. lock for a very brief time.
  17416. @see CriticalSection
  17417. */
  17418. class JUCE_API SpinLock
  17419. {
  17420. public:
  17421. inline SpinLock() noexcept {}
  17422. inline ~SpinLock() noexcept {}
  17423. /** Acquires the lock.
  17424. This will block until the lock has been successfully acquired by this thread.
  17425. Note that a SpinLock is NOT re-entrant, and is not smart enough to know whether the
  17426. caller thread already has the lock - so if a thread tries to acquire a lock that it
  17427. already holds, this method will never return!
  17428. It's strongly recommended that you never call this method directly - instead use the
  17429. ScopedLockType class to manage the locking using an RAII pattern instead.
  17430. */
  17431. void enter() const noexcept;
  17432. /** Attempts to acquire the lock, returning true if this was successful. */
  17433. inline bool tryEnter() const noexcept
  17434. {
  17435. return lock.compareAndSetBool (1, 0);
  17436. }
  17437. /** Releases the lock. */
  17438. inline void exit() const noexcept
  17439. {
  17440. jassert (lock.value == 1); // Agh! Releasing a lock that isn't currently held!
  17441. lock = 0;
  17442. }
  17443. /** Provides the type of scoped lock to use for locking a SpinLock. */
  17444. typedef GenericScopedLock <SpinLock> ScopedLockType;
  17445. /** Provides the type of scoped unlocker to use with a SpinLock. */
  17446. typedef GenericScopedUnlock <SpinLock> ScopedUnlockType;
  17447. private:
  17448. mutable Atomic<int> lock;
  17449. JUCE_DECLARE_NON_COPYABLE (SpinLock);
  17450. };
  17451. #endif // __JUCE_SPINLOCK_JUCEHEADER__
  17452. /*** End of inlined file: juce_SpinLock.h ***/
  17453. /*** Start of inlined file: juce_WaitableEvent.h ***/
  17454. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17455. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  17456. /**
  17457. Allows threads to wait for events triggered by other threads.
  17458. A thread can call wait() on a WaitableObject, and this will suspend the
  17459. calling thread until another thread wakes it up by calling the signal()
  17460. method.
  17461. */
  17462. class JUCE_API WaitableEvent
  17463. {
  17464. public:
  17465. /** Creates a WaitableEvent object.
  17466. @param manualReset If this is false, the event will be reset automatically when the wait()
  17467. method is called. If manualReset is true, then once the event is signalled,
  17468. the only way to reset it will be by calling the reset() method.
  17469. */
  17470. WaitableEvent (bool manualReset = false) noexcept;
  17471. /** Destructor.
  17472. If other threads are waiting on this object when it gets deleted, this
  17473. can cause nasty errors, so be careful!
  17474. */
  17475. ~WaitableEvent() noexcept;
  17476. /** Suspends the calling thread until the event has been signalled.
  17477. This will wait until the object's signal() method is called by another thread,
  17478. or until the timeout expires.
  17479. After the event has been signalled, this method will return true and if manualReset
  17480. was set to false in the WaitableEvent's constructor, then the event will be reset.
  17481. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  17482. value will cause it to wait forever.
  17483. @returns true if the object has been signalled, false if the timeout expires first.
  17484. @see signal, reset
  17485. */
  17486. bool wait (int timeOutMilliseconds = -1) const noexcept;
  17487. /** Wakes up any threads that are currently waiting on this object.
  17488. If signal() is called when nothing is waiting, the next thread to call wait()
  17489. will return immediately and reset the signal.
  17490. If the WaitableEvent is manual reset, all current and future threads that wait upon this
  17491. object will be woken, until reset() is explicitly called.
  17492. If the WaitableEvent is automatic reset, and one or more threads is waiting upon the object,
  17493. then one of them will be woken up. If no threads are currently waiting, then the next thread
  17494. to call wait() will be woken up. As soon as a thread is woken, the signal is automatically
  17495. reset.
  17496. @see wait, reset
  17497. */
  17498. void signal() const noexcept;
  17499. /** Resets the event to an unsignalled state.
  17500. If it's not already signalled, this does nothing.
  17501. */
  17502. void reset() const noexcept;
  17503. private:
  17504. void* internal;
  17505. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  17506. };
  17507. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  17508. /*** End of inlined file: juce_WaitableEvent.h ***/
  17509. /*** Start of inlined file: juce_Thread.h ***/
  17510. #ifndef __JUCE_THREAD_JUCEHEADER__
  17511. #define __JUCE_THREAD_JUCEHEADER__
  17512. /**
  17513. Encapsulates a thread.
  17514. Subclasses derive from Thread and implement the run() method, in which they
  17515. do their business. The thread can then be started with the startThread() method
  17516. and controlled with various other methods.
  17517. This class also contains some thread-related static methods, such
  17518. as sleep(), yield(), getCurrentThreadId() etc.
  17519. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  17520. MessageManagerLock
  17521. */
  17522. class JUCE_API Thread
  17523. {
  17524. public:
  17525. /**
  17526. Creates a thread.
  17527. When first created, the thread is not running. Use the startThread()
  17528. method to start it.
  17529. */
  17530. explicit Thread (const String& threadName);
  17531. /** Destructor.
  17532. Deleting a Thread object that is running will only give the thread a
  17533. brief opportunity to stop itself cleanly, so it's recommended that you
  17534. should always call stopThread() with a decent timeout before deleting,
  17535. to avoid the thread being forcibly killed (which is a Bad Thing).
  17536. */
  17537. virtual ~Thread();
  17538. /** Must be implemented to perform the thread's actual code.
  17539. Remember that the thread must regularly check the threadShouldExit()
  17540. method whilst running, and if this returns true it should return from
  17541. the run() method as soon as possible to avoid being forcibly killed.
  17542. @see threadShouldExit, startThread
  17543. */
  17544. virtual void run() = 0;
  17545. // Thread control functions..
  17546. /** Starts the thread running.
  17547. This will start the thread's run() method.
  17548. (if it's already started, startThread() won't do anything).
  17549. @see stopThread
  17550. */
  17551. void startThread();
  17552. /** Starts the thread with a given priority.
  17553. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  17554. If the thread is already running, its priority will be changed.
  17555. @see startThread, setPriority
  17556. */
  17557. void startThread (int priority);
  17558. /** Attempts to stop the thread running.
  17559. This method will cause the threadShouldExit() method to return true
  17560. and call notify() in case the thread is currently waiting.
  17561. Hopefully the thread will then respond to this by exiting cleanly, and
  17562. the stopThread method will wait for a given time-period for this to
  17563. happen.
  17564. If the thread is stuck and fails to respond after the time-out, it gets
  17565. forcibly killed, which is a very bad thing to happen, as it could still
  17566. be holding locks, etc. which are needed by other parts of your program.
  17567. @param timeOutMilliseconds The number of milliseconds to wait for the
  17568. thread to finish before killing it by force. A negative
  17569. value in here will wait forever.
  17570. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  17571. */
  17572. void stopThread (int timeOutMilliseconds);
  17573. /** Returns true if the thread is currently active */
  17574. bool isThreadRunning() const;
  17575. /** Sets a flag to tell the thread it should stop.
  17576. Calling this means that the threadShouldExit() method will then return true.
  17577. The thread should be regularly checking this to see whether it should exit.
  17578. If your thread makes use of wait(), you might want to call notify() after calling
  17579. this method, to interrupt any waits that might be in progress, and allow it
  17580. to reach a point where it can exit.
  17581. @see threadShouldExit
  17582. @see waitForThreadToExit
  17583. */
  17584. void signalThreadShouldExit();
  17585. /** Checks whether the thread has been told to stop running.
  17586. Threads need to check this regularly, and if it returns true, they should
  17587. return from their run() method at the first possible opportunity.
  17588. @see signalThreadShouldExit
  17589. */
  17590. inline bool threadShouldExit() const { return threadShouldExit_; }
  17591. /** Waits for the thread to stop.
  17592. This will waits until isThreadRunning() is false or until a timeout expires.
  17593. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  17594. is less than zero, it will wait forever.
  17595. @returns true if the thread exits, or false if the timeout expires first.
  17596. */
  17597. bool waitForThreadToExit (int timeOutMilliseconds) const;
  17598. /** Changes the thread's priority.
  17599. May return false if for some reason the priority can't be changed.
  17600. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  17601. of 5 is normal.
  17602. */
  17603. bool setPriority (int priority);
  17604. /** Changes the priority of the caller thread.
  17605. Similar to setPriority(), but this static method acts on the caller thread.
  17606. May return false if for some reason the priority can't be changed.
  17607. @see setPriority
  17608. */
  17609. static bool setCurrentThreadPriority (int priority);
  17610. /** Sets the affinity mask for the thread.
  17611. This will only have an effect next time the thread is started - i.e. if the
  17612. thread is already running when called, it'll have no effect.
  17613. @see setCurrentThreadAffinityMask
  17614. */
  17615. void setAffinityMask (uint32 affinityMask);
  17616. /** Changes the affinity mask for the caller thread.
  17617. This will change the affinity mask for the thread that calls this static method.
  17618. @see setAffinityMask
  17619. */
  17620. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  17621. // this can be called from any thread that needs to pause..
  17622. static void JUCE_CALLTYPE sleep (int milliseconds);
  17623. /** Yields the calling thread's current time-slot. */
  17624. static void JUCE_CALLTYPE yield();
  17625. /** Makes the thread wait for a notification.
  17626. This puts the thread to sleep until either the timeout period expires, or
  17627. another thread calls the notify() method to wake it up.
  17628. A negative time-out value means that the method will wait indefinitely.
  17629. @returns true if the event has been signalled, false if the timeout expires.
  17630. */
  17631. bool wait (int timeOutMilliseconds) const;
  17632. /** Wakes up the thread.
  17633. If the thread has called the wait() method, this will wake it up.
  17634. @see wait
  17635. */
  17636. void notify() const;
  17637. /** A value type used for thread IDs.
  17638. @see getCurrentThreadId(), getThreadId()
  17639. */
  17640. typedef void* ThreadID;
  17641. /** Returns an id that identifies the caller thread.
  17642. To find the ID of a particular thread object, use getThreadId().
  17643. @returns a unique identifier that identifies the calling thread.
  17644. @see getThreadId
  17645. */
  17646. static ThreadID getCurrentThreadId();
  17647. /** Finds the thread object that is currently running.
  17648. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  17649. object associated with them, so this will return 0.
  17650. */
  17651. static Thread* getCurrentThread();
  17652. /** Returns the ID of this thread.
  17653. That means the ID of this thread object - not of the thread that's calling the method.
  17654. This can change when the thread is started and stopped, and will be invalid if the
  17655. thread's not actually running.
  17656. @see getCurrentThreadId
  17657. */
  17658. ThreadID getThreadId() const noexcept { return threadId_; }
  17659. /** Returns the name of the thread.
  17660. This is the name that gets set in the constructor.
  17661. */
  17662. const String& getThreadName() const { return threadName_; }
  17663. /** Changes the name of the caller thread.
  17664. Different OSes may place different length or content limits on this name.
  17665. */
  17666. static void setCurrentThreadName (const String& newThreadName);
  17667. /** Returns the number of currently-running threads.
  17668. @returns the number of Thread objects known to be currently running.
  17669. @see stopAllThreads
  17670. */
  17671. static int getNumRunningThreads();
  17672. /** Tries to stop all currently-running threads.
  17673. This will attempt to stop all the threads known to be running at the moment.
  17674. */
  17675. static void stopAllThreads (int timeoutInMillisecs);
  17676. private:
  17677. const String threadName_;
  17678. void* volatile threadHandle_;
  17679. ThreadID threadId_;
  17680. CriticalSection startStopLock;
  17681. WaitableEvent startSuspensionEvent_, defaultEvent_;
  17682. int threadPriority_;
  17683. uint32 affinityMask_;
  17684. bool volatile threadShouldExit_;
  17685. #ifndef DOXYGEN
  17686. friend class MessageManager;
  17687. friend void JUCE_API juce_threadEntryPoint (void*);
  17688. #endif
  17689. void launchThread();
  17690. void closeThreadHandle();
  17691. void killThread();
  17692. void threadEntryPoint();
  17693. static bool setThreadPriority (void* handle, int priority);
  17694. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  17695. };
  17696. #endif // __JUCE_THREAD_JUCEHEADER__
  17697. /*** End of inlined file: juce_Thread.h ***/
  17698. /**
  17699. A critical section that allows multiple simultaneous readers.
  17700. Features of this type of lock are:
  17701. - Multiple readers can hold the lock at the same time, but only one writer
  17702. can hold it at once.
  17703. - Writers trying to gain the lock will be blocked until all readers and writers
  17704. have released it
  17705. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  17706. blocked until the writer has obtained and released it
  17707. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  17708. there are no other readers
  17709. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  17710. - Recursive locking is supported.
  17711. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  17712. */
  17713. class JUCE_API ReadWriteLock
  17714. {
  17715. public:
  17716. /**
  17717. Creates a ReadWriteLock object.
  17718. */
  17719. ReadWriteLock() noexcept;
  17720. /** Destructor.
  17721. If the object is deleted whilst locked, any subsequent behaviour
  17722. is unpredictable.
  17723. */
  17724. ~ReadWriteLock() noexcept;
  17725. /** Locks this object for reading.
  17726. Multiple threads can simulaneously lock the object for reading, but if another
  17727. thread has it locked for writing, then this will block until it releases the
  17728. lock.
  17729. @see exitRead, ScopedReadLock
  17730. */
  17731. void enterRead() const noexcept;
  17732. /** Releases the read-lock.
  17733. If the caller thread hasn't got the lock, this can have unpredictable results.
  17734. If the enterRead() method has been called multiple times by the thread, each
  17735. call must be matched by a call to exitRead() before other threads will be allowed
  17736. to take over the lock.
  17737. @see enterRead, ScopedReadLock
  17738. */
  17739. void exitRead() const noexcept;
  17740. /** Locks this object for writing.
  17741. This will block until any other threads that have it locked for reading or
  17742. writing have released their lock.
  17743. @see exitWrite, ScopedWriteLock
  17744. */
  17745. void enterWrite() const noexcept;
  17746. /** Tries to lock this object for writing.
  17747. This is like enterWrite(), but doesn't block - it returns true if it manages
  17748. to obtain the lock.
  17749. @see enterWrite
  17750. */
  17751. bool tryEnterWrite() const noexcept;
  17752. /** Releases the write-lock.
  17753. If the caller thread hasn't got the lock, this can have unpredictable results.
  17754. If the enterWrite() method has been called multiple times by the thread, each
  17755. call must be matched by a call to exit() before other threads will be allowed
  17756. to take over the lock.
  17757. @see enterWrite, ScopedWriteLock
  17758. */
  17759. void exitWrite() const noexcept;
  17760. private:
  17761. SpinLock accessLock;
  17762. WaitableEvent waitEvent;
  17763. mutable int numWaitingWriters, numWriters;
  17764. mutable Thread::ThreadID writerThreadId;
  17765. mutable Array <Thread::ThreadID> readerThreads;
  17766. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  17767. };
  17768. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  17769. /*** End of inlined file: juce_ReadWriteLock.h ***/
  17770. #endif
  17771. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  17772. #endif
  17773. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17774. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  17775. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17776. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17777. /**
  17778. Automatically locks and unlocks a ReadWriteLock object.
  17779. Use one of these as a local variable to control access to a ReadWriteLock.
  17780. e.g. @code
  17781. ReadWriteLock myLock;
  17782. for (;;)
  17783. {
  17784. const ScopedReadLock myScopedLock (myLock);
  17785. // myLock is now locked
  17786. ...do some stuff...
  17787. // myLock gets unlocked here.
  17788. }
  17789. @endcode
  17790. @see ReadWriteLock, ScopedWriteLock
  17791. */
  17792. class JUCE_API ScopedReadLock
  17793. {
  17794. public:
  17795. /** Creates a ScopedReadLock.
  17796. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  17797. when the ScopedReadLock object is deleted, the ReadWriteLock will
  17798. be unlocked.
  17799. Make sure this object is created and deleted by the same thread,
  17800. otherwise there are no guarantees what will happen! Best just to use it
  17801. as a local stack object, rather than creating one with the new() operator.
  17802. */
  17803. inline explicit ScopedReadLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterRead(); }
  17804. /** Destructor.
  17805. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  17806. Make sure this object is created and deleted by the same thread,
  17807. otherwise there are no guarantees what will happen!
  17808. */
  17809. inline ~ScopedReadLock() noexcept { lock_.exitRead(); }
  17810. private:
  17811. const ReadWriteLock& lock_;
  17812. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  17813. };
  17814. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17815. /*** End of inlined file: juce_ScopedReadLock.h ***/
  17816. #endif
  17817. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17818. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  17819. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17820. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17821. /**
  17822. Automatically locks and unlocks a ReadWriteLock object.
  17823. Use one of these as a local variable to control access to a ReadWriteLock.
  17824. e.g. @code
  17825. ReadWriteLock myLock;
  17826. for (;;)
  17827. {
  17828. const ScopedWriteLock myScopedLock (myLock);
  17829. // myLock is now locked
  17830. ...do some stuff...
  17831. // myLock gets unlocked here.
  17832. }
  17833. @endcode
  17834. @see ReadWriteLock, ScopedReadLock
  17835. */
  17836. class JUCE_API ScopedWriteLock
  17837. {
  17838. public:
  17839. /** Creates a ScopedWriteLock.
  17840. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  17841. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  17842. be unlocked.
  17843. Make sure this object is created and deleted by the same thread,
  17844. otherwise there are no guarantees what will happen! Best just to use it
  17845. as a local stack object, rather than creating one with the new() operator.
  17846. */
  17847. inline explicit ScopedWriteLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterWrite(); }
  17848. /** Destructor.
  17849. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  17850. Make sure this object is created and deleted by the same thread,
  17851. otherwise there are no guarantees what will happen!
  17852. */
  17853. inline ~ScopedWriteLock() noexcept { lock_.exitWrite(); }
  17854. private:
  17855. const ReadWriteLock& lock_;
  17856. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17857. };
  17858. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17859. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17860. #endif
  17861. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17862. #endif
  17863. #ifndef __JUCE_THREAD_JUCEHEADER__
  17864. #endif
  17865. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17866. /*** Start of inlined file: juce_ThreadPool.h ***/
  17867. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17868. #define __JUCE_THREADPOOL_JUCEHEADER__
  17869. class ThreadPool;
  17870. class ThreadPoolThread;
  17871. /**
  17872. A task that is executed by a ThreadPool object.
  17873. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17874. its threads.
  17875. The runJob() method needs to be implemented to do the task, and if the code that
  17876. does the work takes a significant time to run, it must keep checking the shouldExit()
  17877. method to see if something is trying to interrupt the job. If shouldExit() returns
  17878. true, the runJob() method must return immediately.
  17879. @see ThreadPool, Thread
  17880. */
  17881. class JUCE_API ThreadPoolJob
  17882. {
  17883. public:
  17884. /** Creates a thread pool job object.
  17885. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17886. */
  17887. explicit ThreadPoolJob (const String& name);
  17888. /** Destructor. */
  17889. virtual ~ThreadPoolJob();
  17890. /** Returns the name of this job.
  17891. @see setJobName
  17892. */
  17893. String getJobName() const;
  17894. /** Changes the job's name.
  17895. @see getJobName
  17896. */
  17897. void setJobName (const String& newName);
  17898. /** These are the values that can be returned by the runJob() method.
  17899. */
  17900. enum JobStatus
  17901. {
  17902. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17903. removed from the pool. */
  17904. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17905. should be automatically deleted by the pool. */
  17906. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17907. again when a thread is free. */
  17908. };
  17909. /** Peforms the actual work that this job needs to do.
  17910. Your subclass must implement this method, in which is does its work.
  17911. If the code in this method takes a significant time to run, it must repeatedly check
  17912. the shouldExit() method to see if something is trying to interrupt the job.
  17913. If shouldExit() ever returns true, the runJob() method must return immediately.
  17914. If this method returns jobHasFinished, then the job will be removed from the pool
  17915. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17916. pool and will get a chance to run again as soon as a thread is free.
  17917. @see shouldExit()
  17918. */
  17919. virtual JobStatus runJob() = 0;
  17920. /** Returns true if this job is currently running its runJob() method. */
  17921. bool isRunning() const { return isActive; }
  17922. /** Returns true if something is trying to interrupt this job and make it stop.
  17923. Your runJob() method must call this whenever it gets a chance, and if it ever
  17924. returns true, the runJob() method must return immediately.
  17925. @see signalJobShouldExit()
  17926. */
  17927. bool shouldExit() const { return shouldStop; }
  17928. /** Calling this will cause the shouldExit() method to return true, and the job
  17929. should (if it's been implemented correctly) stop as soon as possible.
  17930. @see shouldExit()
  17931. */
  17932. void signalJobShouldExit();
  17933. private:
  17934. friend class ThreadPool;
  17935. friend class ThreadPoolThread;
  17936. String jobName;
  17937. ThreadPool* pool;
  17938. bool shouldStop, isActive, shouldBeDeleted;
  17939. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17940. };
  17941. /**
  17942. A set of threads that will run a list of jobs.
  17943. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17944. will be called by the next pooled thread that becomes free.
  17945. @see ThreadPoolJob, Thread
  17946. */
  17947. class JUCE_API ThreadPool
  17948. {
  17949. public:
  17950. /** Creates a thread pool.
  17951. Once you've created a pool, you can give it some things to do with the addJob()
  17952. method.
  17953. @param numberOfThreads the maximum number of actual threads to run.
  17954. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17955. until there are some jobs to run. If false, then
  17956. all the threads will be fired-up immediately so that
  17957. they're ready for action
  17958. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17959. inactive for this length of time, they will automatically
  17960. be stopped until more jobs come along and they're needed
  17961. */
  17962. ThreadPool (int numberOfThreads,
  17963. bool startThreadsOnlyWhenNeeded = true,
  17964. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17965. /** Destructor.
  17966. This will attempt to remove all the jobs before deleting, but if you want to
  17967. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17968. the pool.
  17969. */
  17970. ~ThreadPool();
  17971. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17972. for some kind of operation.
  17973. @see ThreadPool::removeAllJobs
  17974. */
  17975. class JUCE_API JobSelector
  17976. {
  17977. public:
  17978. virtual ~JobSelector() {}
  17979. /** Should return true if the specified thread matches your criteria for whatever
  17980. operation that this object is being used for.
  17981. Any implementation of this method must be extremely fast and thread-safe!
  17982. */
  17983. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17984. };
  17985. /** Adds a job to the queue.
  17986. Once a job has been added, then the next time a thread is free, it will run
  17987. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17988. runJob() method, the pool will either remove the job from the pool or add it to
  17989. the back of the queue to be run again.
  17990. */
  17991. void addJob (ThreadPoolJob* job);
  17992. /** Tries to remove a job from the pool.
  17993. If the job isn't yet running, this will simply remove it. If it is running, it
  17994. will wait for it to finish.
  17995. If the timeout period expires before the job finishes running, then the job will be
  17996. left in the pool and this will return false. It returns true if the job is sucessfully
  17997. stopped and removed.
  17998. @param job the job to remove
  17999. @param interruptIfRunning if true, then if the job is currently busy, its
  18000. ThreadPoolJob::signalJobShouldExit() method will be called to try
  18001. to interrupt it. If false, then if the job will be allowed to run
  18002. until it stops normally (or the timeout expires)
  18003. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  18004. before giving up and returning false
  18005. */
  18006. bool removeJob (ThreadPoolJob* job,
  18007. bool interruptIfRunning,
  18008. int timeOutMilliseconds);
  18009. /** Tries to remove all jobs from the pool.
  18010. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  18011. methods called to try to interrupt them
  18012. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  18013. before giving up and returning false
  18014. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  18015. they will simply be removed from the pool. Jobs that are already running when
  18016. this method is called can choose whether they should be deleted by
  18017. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  18018. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  18019. jobs should be removed. If it is zero, all jobs are removed
  18020. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  18021. expires while waiting for one or more jobs to stop
  18022. */
  18023. bool removeAllJobs (bool interruptRunningJobs,
  18024. int timeOutMilliseconds,
  18025. bool deleteInactiveJobs = false,
  18026. JobSelector* selectedJobsToRemove = 0);
  18027. /** Returns the number of jobs currently running or queued.
  18028. */
  18029. int getNumJobs() const;
  18030. /** Returns one of the jobs in the queue.
  18031. Note that this can be a very volatile list as jobs might be continuously getting shifted
  18032. around in the list, and this method may return 0 if the index is currently out-of-range.
  18033. */
  18034. ThreadPoolJob* getJob (int index) const;
  18035. /** Returns true if the given job is currently queued or running.
  18036. @see isJobRunning()
  18037. */
  18038. bool contains (const ThreadPoolJob* job) const;
  18039. /** Returns true if the given job is currently being run by a thread.
  18040. */
  18041. bool isJobRunning (const ThreadPoolJob* job) const;
  18042. /** Waits until a job has finished running and has been removed from the pool.
  18043. This will wait until the job is no longer in the pool - i.e. until its
  18044. runJob() method returns ThreadPoolJob::jobHasFinished.
  18045. If the timeout period expires before the job finishes, this will return false;
  18046. it returns true if the job has finished successfully.
  18047. */
  18048. bool waitForJobToFinish (const ThreadPoolJob* job,
  18049. int timeOutMilliseconds) const;
  18050. /** Returns a list of the names of all the jobs currently running or queued.
  18051. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  18052. */
  18053. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  18054. /** Changes the priority of all the threads.
  18055. This will call Thread::setPriority() for each thread in the pool.
  18056. May return false if for some reason the priority can't be changed.
  18057. */
  18058. bool setThreadPriorities (int newPriority);
  18059. private:
  18060. const int threadStopTimeout;
  18061. int priority;
  18062. class ThreadPoolThread;
  18063. friend class OwnedArray <ThreadPoolThread>;
  18064. OwnedArray <ThreadPoolThread> threads;
  18065. Array <ThreadPoolJob*> jobs;
  18066. CriticalSection lock;
  18067. uint32 lastJobEndTime;
  18068. WaitableEvent jobFinishedSignal;
  18069. friend class ThreadPoolThread;
  18070. bool runNextJob();
  18071. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  18072. };
  18073. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  18074. /*** End of inlined file: juce_ThreadPool.h ***/
  18075. #endif
  18076. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18077. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  18078. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18079. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18080. class TimeSliceThread;
  18081. /**
  18082. Used by the TimeSliceThread class.
  18083. To register your class with a TimeSliceThread, derive from this class and
  18084. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  18085. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  18086. deleting your client!
  18087. @see TimeSliceThread
  18088. */
  18089. class JUCE_API TimeSliceClient
  18090. {
  18091. public:
  18092. /** Destructor. */
  18093. virtual ~TimeSliceClient() {}
  18094. /** Called back by a TimeSliceThread.
  18095. When you register this class with it, a TimeSliceThread will repeatedly call
  18096. this method.
  18097. The implementation of this method should use its time-slice to do something that's
  18098. quick - never block for longer than absolutely necessary.
  18099. @returns Your method should return the number of milliseconds which it would like to wait before being called
  18100. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  18101. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  18102. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  18103. thread - the actual time before the next callback may be more or less than specified.
  18104. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  18105. */
  18106. virtual int useTimeSlice() = 0;
  18107. private:
  18108. friend class TimeSliceThread;
  18109. Time nextCallTime;
  18110. };
  18111. /**
  18112. A thread that keeps a list of clients, and calls each one in turn, giving them
  18113. all a chance to run some sort of short task.
  18114. @see TimeSliceClient, Thread
  18115. */
  18116. class JUCE_API TimeSliceThread : public Thread
  18117. {
  18118. public:
  18119. /**
  18120. Creates a TimeSliceThread.
  18121. When first created, the thread is not running. Use the startThread()
  18122. method to start it.
  18123. */
  18124. explicit TimeSliceThread (const String& threadName);
  18125. /** Destructor.
  18126. Deleting a Thread object that is running will only give the thread a
  18127. brief opportunity to stop itself cleanly, so it's recommended that you
  18128. should always call stopThread() with a decent timeout before deleting,
  18129. to avoid the thread being forcibly killed (which is a Bad Thing).
  18130. */
  18131. ~TimeSliceThread();
  18132. /** Adds a client to the list.
  18133. The client's callbacks will start after the number of milliseconds specified
  18134. by millisecondsBeforeStarting (and this may happen before this method has returned).
  18135. */
  18136. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  18137. /** Removes a client from the list.
  18138. This method will make sure that all callbacks to the client have completely
  18139. finished before the method returns.
  18140. */
  18141. void removeTimeSliceClient (TimeSliceClient* client);
  18142. /** Returns the number of registered clients. */
  18143. int getNumClients() const;
  18144. /** Returns one of the registered clients. */
  18145. TimeSliceClient* getClient (int index) const;
  18146. #ifndef DOXYGEN
  18147. void run();
  18148. #endif
  18149. private:
  18150. CriticalSection callbackLock, listLock;
  18151. Array <TimeSliceClient*> clients;
  18152. TimeSliceClient* clientBeingCalled;
  18153. TimeSliceClient* getNextClient (int index) const;
  18154. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  18155. };
  18156. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18157. /*** End of inlined file: juce_TimeSliceThread.h ***/
  18158. #endif
  18159. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  18160. #endif
  18161. #endif
  18162. /*** End of inlined file: juce_core_includes.h ***/
  18163. // if you're compiling a command-line app, you might want to just include the core headers,
  18164. // so you can set this macro before including juce.h
  18165. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  18166. /*** Start of inlined file: juce_app_includes.h ***/
  18167. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  18168. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  18169. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  18170. /*** Start of inlined file: juce_Application.h ***/
  18171. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  18172. #define __JUCE_APPLICATION_JUCEHEADER__
  18173. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  18174. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18175. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18176. /*** Start of inlined file: juce_Component.h ***/
  18177. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  18178. #define __JUCE_COMPONENT_JUCEHEADER__
  18179. /*** Start of inlined file: juce_MouseCursor.h ***/
  18180. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  18181. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  18182. class Image;
  18183. class ComponentPeer;
  18184. class Component;
  18185. /**
  18186. Represents a mouse cursor image.
  18187. This object can either be used to represent one of the standard mouse
  18188. cursor shapes, or a custom one generated from an image.
  18189. */
  18190. class JUCE_API MouseCursor
  18191. {
  18192. public:
  18193. /** The set of available standard mouse cursors. */
  18194. enum StandardCursorType
  18195. {
  18196. NoCursor = 0, /**< An invisible cursor. */
  18197. NormalCursor, /**< The stardard arrow cursor. */
  18198. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  18199. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  18200. CrosshairCursor, /**< A pair of crosshairs. */
  18201. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  18202. that you're dragging a copy of something. */
  18203. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  18204. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  18205. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  18206. UpDownResizeCursor, /**< an arrow pointing up and down. */
  18207. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  18208. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  18209. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  18210. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  18211. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  18212. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  18213. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  18214. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  18215. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  18216. };
  18217. /** Creates the standard arrow cursor. */
  18218. MouseCursor();
  18219. /** Creates one of the standard mouse cursor */
  18220. MouseCursor (StandardCursorType type);
  18221. /** Creates a custom cursor from an image.
  18222. @param image the image to use for the cursor - if this is bigger than the
  18223. system can manage, it might get scaled down first, and might
  18224. also have to be turned to black-and-white if it can't do colour
  18225. cursors.
  18226. @param hotSpotX the x position of the cursor's hotspot within the image
  18227. @param hotSpotY the y position of the cursor's hotspot within the image
  18228. */
  18229. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  18230. /** Creates a copy of another cursor object. */
  18231. MouseCursor (const MouseCursor& other);
  18232. /** Copies this cursor from another object. */
  18233. MouseCursor& operator= (const MouseCursor& other);
  18234. /** Destructor. */
  18235. ~MouseCursor();
  18236. /** Checks whether two mouse cursors are the same.
  18237. For custom cursors, two cursors created from the same image won't be
  18238. recognised as the same, only MouseCursor objects that have been
  18239. copied from the same object.
  18240. */
  18241. bool operator== (const MouseCursor& other) const noexcept;
  18242. /** Checks whether two mouse cursors are the same.
  18243. For custom cursors, two cursors created from the same image won't be
  18244. recognised as the same, only MouseCursor objects that have been
  18245. copied from the same object.
  18246. */
  18247. bool operator!= (const MouseCursor& other) const noexcept;
  18248. /** Makes the system show its default 'busy' cursor.
  18249. This will turn the system cursor to an hourglass or spinning beachball
  18250. until the next time the mouse is moved, or hideWaitCursor() is called.
  18251. This is handy if the message loop is about to block for a couple of
  18252. seconds while busy and you want to give the user feedback about this.
  18253. @see MessageManager::setTimeBeforeShowingWaitCursor
  18254. */
  18255. static void showWaitCursor();
  18256. /** If showWaitCursor has been called, this will return the mouse to its
  18257. normal state.
  18258. This will look at what component is under the mouse, and update the
  18259. cursor to be the correct one for that component.
  18260. @see showWaitCursor
  18261. */
  18262. static void hideWaitCursor();
  18263. private:
  18264. class SharedCursorHandle;
  18265. friend class SharedCursorHandle;
  18266. SharedCursorHandle* cursorHandle;
  18267. friend class MouseInputSourceInternal;
  18268. void showInWindow (ComponentPeer* window) const;
  18269. void showInAllWindows() const;
  18270. void* getHandle() const noexcept;
  18271. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  18272. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  18273. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  18274. JUCE_LEAK_DETECTOR (MouseCursor);
  18275. };
  18276. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  18277. /*** End of inlined file: juce_MouseCursor.h ***/
  18278. /*** Start of inlined file: juce_MouseListener.h ***/
  18279. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  18280. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  18281. class MouseEvent;
  18282. /**
  18283. A MouseListener can be registered with a component to receive callbacks
  18284. about mouse events that happen to that component.
  18285. @see Component::addMouseListener, Component::removeMouseListener
  18286. */
  18287. class JUCE_API MouseListener
  18288. {
  18289. public:
  18290. /** Destructor. */
  18291. virtual ~MouseListener() {}
  18292. /** Called when the mouse moves inside a component.
  18293. If the mouse button isn't pressed and the mouse moves over a component,
  18294. this will be called to let the component react to this.
  18295. A component will always get a mouseEnter callback before a mouseMove.
  18296. @param e details about the position and status of the mouse event, including
  18297. the source component in which it occurred
  18298. @see mouseEnter, mouseExit, mouseDrag, contains
  18299. */
  18300. virtual void mouseMove (const MouseEvent& e);
  18301. /** Called when the mouse first enters a component.
  18302. If the mouse button isn't pressed and the mouse moves into a component,
  18303. this will be called to let the component react to this.
  18304. When the mouse button is pressed and held down while being moved in
  18305. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  18306. mouseDrag messages are sent to the component that the mouse was originally
  18307. clicked on, until the button is released.
  18308. @param e details about the position and status of the mouse event, including
  18309. the source component in which it occurred
  18310. @see mouseExit, mouseDrag, mouseMove, contains
  18311. */
  18312. virtual void mouseEnter (const MouseEvent& e);
  18313. /** Called when the mouse moves out of a component.
  18314. This will be called when the mouse moves off the edge of this
  18315. component.
  18316. If the mouse button was pressed, and it was then dragged off the
  18317. edge of the component and released, then this callback will happen
  18318. when the button is released, after the mouseUp callback.
  18319. @param e details about the position and status of the mouse event, including
  18320. the source component in which it occurred
  18321. @see mouseEnter, mouseDrag, mouseMove, contains
  18322. */
  18323. virtual void mouseExit (const MouseEvent& e);
  18324. /** Called when a mouse button is pressed.
  18325. The MouseEvent object passed in contains lots of methods for finding out
  18326. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18327. were held down at the time.
  18328. Once a button is held down, the mouseDrag method will be called when the
  18329. mouse moves, until the button is released.
  18330. @param e details about the position and status of the mouse event, including
  18331. the source component in which it occurred
  18332. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18333. */
  18334. virtual void mouseDown (const MouseEvent& e);
  18335. /** Called when the mouse is moved while a button is held down.
  18336. When a mouse button is pressed inside a component, that component
  18337. receives mouseDrag callbacks each time the mouse moves, even if the
  18338. mouse strays outside the component's bounds.
  18339. @param e details about the position and status of the mouse event, including
  18340. the source component in which it occurred
  18341. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  18342. */
  18343. virtual void mouseDrag (const MouseEvent& e);
  18344. /** Called when a mouse button is released.
  18345. A mouseUp callback is sent to the component in which a button was pressed
  18346. even if the mouse is actually over a different component when the
  18347. button is released.
  18348. The MouseEvent object passed in contains lots of methods for finding out
  18349. which buttons were down just before they were released.
  18350. @param e details about the position and status of the mouse event, including
  18351. the source component in which it occurred
  18352. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18353. */
  18354. virtual void mouseUp (const MouseEvent& e);
  18355. /** Called when a mouse button has been double-clicked on a component.
  18356. The MouseEvent object passed in contains lots of methods for finding out
  18357. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18358. were held down at the time.
  18359. @param e details about the position and status of the mouse event, including
  18360. the source component in which it occurred
  18361. @see mouseDown, mouseUp
  18362. */
  18363. virtual void mouseDoubleClick (const MouseEvent& e);
  18364. /** Called when the mouse-wheel is moved.
  18365. This callback is sent to the component that the mouse is over when the
  18366. wheel is moved.
  18367. If not overridden, the component will forward this message to its parent, so
  18368. that parent components can collect mouse-wheel messages that happen to
  18369. child components which aren't interested in them.
  18370. @param e details about the position and status of the mouse event, including
  18371. the source component in which it occurred
  18372. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18373. value means the wheel has been pushed to the right, negative means it
  18374. was pushed to the left
  18375. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18376. value means the wheel has been pushed upwards, negative means it
  18377. was pushed downwards
  18378. */
  18379. virtual void mouseWheelMove (const MouseEvent& e,
  18380. float wheelIncrementX,
  18381. float wheelIncrementY);
  18382. };
  18383. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  18384. /*** End of inlined file: juce_MouseListener.h ***/
  18385. /*** Start of inlined file: juce_MouseEvent.h ***/
  18386. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  18387. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  18388. class Component;
  18389. class MouseInputSource;
  18390. /*** Start of inlined file: juce_ModifierKeys.h ***/
  18391. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  18392. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  18393. /**
  18394. Represents the state of the mouse buttons and modifier keys.
  18395. This is used both by mouse events and by KeyPress objects to describe
  18396. the state of keys such as shift, control, alt, etc.
  18397. @see KeyPress, MouseEvent::mods
  18398. */
  18399. class JUCE_API ModifierKeys
  18400. {
  18401. public:
  18402. /** Creates a ModifierKeys object from a raw set of flags.
  18403. @param flags to represent the keys that are down
  18404. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  18405. rightButtonModifier, commandModifier, popupMenuClickModifier
  18406. */
  18407. ModifierKeys (int flags = 0) noexcept;
  18408. /** Creates a copy of another object. */
  18409. ModifierKeys (const ModifierKeys& other) noexcept;
  18410. /** Copies this object from another one. */
  18411. ModifierKeys& operator= (const ModifierKeys& other) noexcept;
  18412. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  18413. This is a platform-agnostic way of checking for the operating system's
  18414. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  18415. Windows/Linux, it's actually checking for the CTRL key.
  18416. */
  18417. inline bool isCommandDown() const noexcept { return (flags & commandModifier) != 0; }
  18418. /** Checks whether the user is trying to launch a pop-up menu.
  18419. This checks for platform-specific modifiers that might indicate that the user
  18420. is following the operating system's normal method of showing a pop-up menu.
  18421. So on Windows/Linux, this method is really testing for a right-click.
  18422. On the Mac, it tests for either the CTRL key being down, or a right-click.
  18423. */
  18424. inline bool isPopupMenu() const noexcept { return (flags & popupMenuClickModifier) != 0; }
  18425. /** Checks whether the flag is set for the left mouse-button. */
  18426. inline bool isLeftButtonDown() const noexcept { return (flags & leftButtonModifier) != 0; }
  18427. /** Checks whether the flag is set for the right mouse-button.
  18428. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  18429. this is platform-independent (and makes your code more explanatory too).
  18430. */
  18431. inline bool isRightButtonDown() const noexcept { return (flags & rightButtonModifier) != 0; }
  18432. inline bool isMiddleButtonDown() const noexcept { return (flags & middleButtonModifier) != 0; }
  18433. /** Tests for any of the mouse-button flags. */
  18434. inline bool isAnyMouseButtonDown() const noexcept { return (flags & allMouseButtonModifiers) != 0; }
  18435. /** Tests for any of the modifier key flags. */
  18436. inline bool isAnyModifierKeyDown() const noexcept { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  18437. /** Checks whether the shift key's flag is set. */
  18438. inline bool isShiftDown() const noexcept { return (flags & shiftModifier) != 0; }
  18439. /** Checks whether the CTRL key's flag is set.
  18440. Remember that it's better to use the platform-agnostic routines to test for command-key and
  18441. popup-menu modifiers.
  18442. @see isCommandDown, isPopupMenu
  18443. */
  18444. inline bool isCtrlDown() const noexcept { return (flags & ctrlModifier) != 0; }
  18445. /** Checks whether the shift key's flag is set. */
  18446. inline bool isAltDown() const noexcept { return (flags & altModifier) != 0; }
  18447. /** Flags that represent the different keys. */
  18448. enum Flags
  18449. {
  18450. /** Shift key flag. */
  18451. shiftModifier = 1,
  18452. /** CTRL key flag. */
  18453. ctrlModifier = 2,
  18454. /** ALT key flag. */
  18455. altModifier = 4,
  18456. /** Left mouse button flag. */
  18457. leftButtonModifier = 16,
  18458. /** Right mouse button flag. */
  18459. rightButtonModifier = 32,
  18460. /** Middle mouse button flag. */
  18461. middleButtonModifier = 64,
  18462. #if JUCE_MAC
  18463. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18464. commandModifier = 8,
  18465. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18466. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18467. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  18468. #else
  18469. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18470. commandModifier = ctrlModifier,
  18471. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18472. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18473. popupMenuClickModifier = rightButtonModifier,
  18474. #endif
  18475. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  18476. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  18477. /** Represents a combination of all the mouse buttons at once. */
  18478. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  18479. };
  18480. /** Returns a copy of only the mouse-button flags */
  18481. const ModifierKeys withOnlyMouseButtons() const noexcept { return ModifierKeys (flags & allMouseButtonModifiers); }
  18482. /** Returns a copy of only the non-mouse flags */
  18483. const ModifierKeys withoutMouseButtons() const noexcept { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  18484. bool operator== (const ModifierKeys& other) const noexcept { return flags == other.flags; }
  18485. bool operator!= (const ModifierKeys& other) const noexcept { return flags != other.flags; }
  18486. /** Returns the raw flags for direct testing. */
  18487. inline int getRawFlags() const noexcept { return flags; }
  18488. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const noexcept { return ModifierKeys (flags & ~rawFlagsToClear); }
  18489. inline const ModifierKeys withFlags (int rawFlagsToSet) const noexcept { return ModifierKeys (flags | rawFlagsToSet); }
  18490. /** Tests a combination of flags and returns true if any of them are set. */
  18491. inline bool testFlags (const int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  18492. /** Returns the total number of mouse buttons that are down. */
  18493. int getNumMouseButtonsDown() const noexcept;
  18494. /** Creates a ModifierKeys object to represent the last-known state of the
  18495. keyboard and mouse buttons.
  18496. @see getCurrentModifiersRealtime
  18497. */
  18498. static const ModifierKeys getCurrentModifiers() noexcept;
  18499. /** Creates a ModifierKeys object to represent the current state of the
  18500. keyboard and mouse buttons.
  18501. This isn't often needed and isn't recommended, but will actively check all the
  18502. mouse and key states rather than just returning their last-known state like
  18503. getCurrentModifiers() does.
  18504. This is only needed in special circumstances for up-to-date modifier information
  18505. at times when the app's event loop isn't running normally.
  18506. Another reason to avoid this method is that it's not stateless, and calling it may
  18507. update the value returned by getCurrentModifiers(), which could cause subtle changes
  18508. in the behaviour of some components.
  18509. */
  18510. static const ModifierKeys getCurrentModifiersRealtime() noexcept;
  18511. private:
  18512. int flags;
  18513. static ModifierKeys currentModifiers;
  18514. friend class ComponentPeer;
  18515. friend class MouseInputSource;
  18516. friend class MouseInputSourceInternal;
  18517. static void updateCurrentModifiers() noexcept;
  18518. };
  18519. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  18520. /*** End of inlined file: juce_ModifierKeys.h ***/
  18521. /*** Start of inlined file: juce_Point.h ***/
  18522. #ifndef __JUCE_POINT_JUCEHEADER__
  18523. #define __JUCE_POINT_JUCEHEADER__
  18524. /*** Start of inlined file: juce_AffineTransform.h ***/
  18525. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18526. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18527. /**
  18528. Represents a 2D affine-transformation matrix.
  18529. An affine transformation is a transformation such as a rotation, scale, shear,
  18530. resize or translation.
  18531. These are used for various 2D transformation tasks, e.g. with Path objects.
  18532. @see Path, Point, Line
  18533. */
  18534. class JUCE_API AffineTransform
  18535. {
  18536. public:
  18537. /** Creates an identity transform. */
  18538. AffineTransform() noexcept;
  18539. /** Creates a copy of another transform. */
  18540. AffineTransform (const AffineTransform& other) noexcept;
  18541. /** Creates a transform from a set of raw matrix values.
  18542. The resulting matrix is:
  18543. (mat00 mat01 mat02)
  18544. (mat10 mat11 mat12)
  18545. ( 0 0 1 )
  18546. */
  18547. AffineTransform (float mat00, float mat01, float mat02,
  18548. float mat10, float mat11, float mat12) noexcept;
  18549. /** Copies from another AffineTransform object */
  18550. AffineTransform& operator= (const AffineTransform& other) noexcept;
  18551. /** Compares two transforms. */
  18552. bool operator== (const AffineTransform& other) const noexcept;
  18553. /** Compares two transforms. */
  18554. bool operator!= (const AffineTransform& other) const noexcept;
  18555. /** A ready-to-use identity transform, which you can use to append other
  18556. transformations to.
  18557. e.g. @code
  18558. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  18559. .scaled (2.0f);
  18560. @endcode
  18561. */
  18562. static const AffineTransform identity;
  18563. /** Transforms a 2D co-ordinate using this matrix. */
  18564. template <typename ValueType>
  18565. void transformPoint (ValueType& x, ValueType& y) const noexcept
  18566. {
  18567. const ValueType oldX = x;
  18568. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  18569. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  18570. }
  18571. /** Transforms two 2D co-ordinates using this matrix.
  18572. This is just a shortcut for calling transformPoint() on each of these pairs of
  18573. coordinates in turn. (And putting all the calculations into one function hopefully
  18574. also gives the compiler a bit more scope for pipelining it).
  18575. */
  18576. template <typename ValueType>
  18577. void transformPoints (ValueType& x1, ValueType& y1,
  18578. ValueType& x2, ValueType& y2) const noexcept
  18579. {
  18580. const ValueType oldX1 = x1, oldX2 = x2;
  18581. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18582. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18583. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18584. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18585. }
  18586. /** Transforms three 2D co-ordinates using this matrix.
  18587. This is just a shortcut for calling transformPoint() on each of these pairs of
  18588. coordinates in turn. (And putting all the calculations into one function hopefully
  18589. also gives the compiler a bit more scope for pipelining it).
  18590. */
  18591. template <typename ValueType>
  18592. void transformPoints (ValueType& x1, ValueType& y1,
  18593. ValueType& x2, ValueType& y2,
  18594. ValueType& x3, ValueType& y3) const noexcept
  18595. {
  18596. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  18597. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18598. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18599. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18600. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18601. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  18602. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  18603. }
  18604. /** Returns a new transform which is the same as this one followed by a translation. */
  18605. AffineTransform translated (float deltaX,
  18606. float deltaY) const noexcept;
  18607. /** Returns a new transform which is a translation. */
  18608. static AffineTransform translation (float deltaX,
  18609. float deltaY) noexcept;
  18610. /** Returns a transform which is the same as this one followed by a rotation.
  18611. The rotation is specified by a number of radians to rotate clockwise, centred around
  18612. the origin (0, 0).
  18613. */
  18614. AffineTransform rotated (float angleInRadians) const noexcept;
  18615. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  18616. The rotation is specified by a number of radians to rotate clockwise, centred around
  18617. the co-ordinates passed in.
  18618. */
  18619. AffineTransform rotated (float angleInRadians,
  18620. float pivotX,
  18621. float pivotY) const noexcept;
  18622. /** Returns a new transform which is a rotation about (0, 0). */
  18623. static AffineTransform rotation (float angleInRadians) noexcept;
  18624. /** Returns a new transform which is a rotation about a given point. */
  18625. static AffineTransform rotation (float angleInRadians,
  18626. float pivotX,
  18627. float pivotY) noexcept;
  18628. /** Returns a transform which is the same as this one followed by a re-scaling.
  18629. The scaling is centred around the origin (0, 0).
  18630. */
  18631. AffineTransform scaled (float factorX,
  18632. float factorY) const noexcept;
  18633. /** Returns a transform which is the same as this one followed by a re-scaling.
  18634. The scaling is centred around the origin provided.
  18635. */
  18636. AffineTransform scaled (float factorX, float factorY,
  18637. float pivotX, float pivotY) const noexcept;
  18638. /** Returns a new transform which is a re-scale about the origin. */
  18639. static AffineTransform scale (float factorX,
  18640. float factorY) noexcept;
  18641. /** Returns a new transform which is a re-scale centred around the point provided. */
  18642. static AffineTransform scale (float factorX, float factorY,
  18643. float pivotX, float pivotY) noexcept;
  18644. /** Returns a transform which is the same as this one followed by a shear.
  18645. The shear is centred around the origin (0, 0).
  18646. */
  18647. AffineTransform sheared (float shearX, float shearY) const noexcept;
  18648. /** Returns a shear transform, centred around the origin (0, 0). */
  18649. static AffineTransform shear (float shearX, float shearY) noexcept;
  18650. /** Returns a matrix which is the inverse operation of this one.
  18651. Some matrices don't have an inverse - in this case, the method will just return
  18652. an identity transform.
  18653. */
  18654. AffineTransform inverted() const noexcept;
  18655. /** Returns the transform that will map three known points onto three coordinates
  18656. that are supplied.
  18657. This returns the transform that will transform (0, 0) into (x00, y00),
  18658. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  18659. */
  18660. static AffineTransform fromTargetPoints (float x00, float y00,
  18661. float x10, float y10,
  18662. float x01, float y01) noexcept;
  18663. /** Returns the transform that will map three specified points onto three target points.
  18664. */
  18665. static AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  18666. float sourceX2, float sourceY2, float targetX2, float targetY2,
  18667. float sourceX3, float sourceY3, float targetX3, float targetY3) noexcept;
  18668. /** Returns the result of concatenating another transformation after this one. */
  18669. AffineTransform followedBy (const AffineTransform& other) const noexcept;
  18670. /** Returns true if this transform has no effect on points. */
  18671. bool isIdentity() const noexcept;
  18672. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  18673. bool isSingularity() const noexcept;
  18674. /** Returns true if the transform only translates, and doesn't scale or rotate the
  18675. points. */
  18676. bool isOnlyTranslation() const noexcept;
  18677. /** If this transform is only a translation, this returns the X offset.
  18678. @see isOnlyTranslation
  18679. */
  18680. float getTranslationX() const noexcept { return mat02; }
  18681. /** If this transform is only a translation, this returns the X offset.
  18682. @see isOnlyTranslation
  18683. */
  18684. float getTranslationY() const noexcept { return mat12; }
  18685. /** Returns the approximate scale factor by which lengths will be transformed.
  18686. Obviously a length may be scaled by entirely different amounts depending on its
  18687. direction, so this is only appropriate as a rough guide.
  18688. */
  18689. float getScaleFactor() const noexcept;
  18690. /* The transform matrix is:
  18691. (mat00 mat01 mat02)
  18692. (mat10 mat11 mat12)
  18693. ( 0 0 1 )
  18694. */
  18695. float mat00, mat01, mat02;
  18696. float mat10, mat11, mat12;
  18697. private:
  18698. JUCE_LEAK_DETECTOR (AffineTransform);
  18699. };
  18700. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18701. /*** End of inlined file: juce_AffineTransform.h ***/
  18702. /**
  18703. A pair of (x, y) co-ordinates.
  18704. The ValueType template should be a primitive type such as int, float, double,
  18705. rather than a class.
  18706. @see Line, Path, AffineTransform
  18707. */
  18708. template <typename ValueType>
  18709. class Point
  18710. {
  18711. public:
  18712. /** Creates a point with co-ordinates (0, 0). */
  18713. Point() noexcept : x(), y() {}
  18714. /** Creates a copy of another point. */
  18715. Point (const Point& other) noexcept : x (other.x), y (other.y) {}
  18716. /** Creates a point from an (x, y) position. */
  18717. Point (const ValueType initialX, const ValueType initialY) noexcept : x (initialX), y (initialY) {}
  18718. /** Destructor. */
  18719. ~Point() noexcept {}
  18720. /** Copies this point from another one. */
  18721. Point& operator= (const Point& other) noexcept { x = other.x; y = other.y; return *this; }
  18722. inline bool operator== (const Point& other) const noexcept { return x == other.x && y == other.y; }
  18723. inline bool operator!= (const Point& other) const noexcept { return x != other.x || y != other.y; }
  18724. /** Returns true if the point is (0, 0). */
  18725. bool isOrigin() const noexcept { return x == ValueType() && y == ValueType(); }
  18726. /** Returns the point's x co-ordinate. */
  18727. inline ValueType getX() const noexcept { return x; }
  18728. /** Returns the point's y co-ordinate. */
  18729. inline ValueType getY() const noexcept { return y; }
  18730. /** Sets the point's x co-ordinate. */
  18731. inline void setX (const ValueType newX) noexcept { x = newX; }
  18732. /** Sets the point's y co-ordinate. */
  18733. inline void setY (const ValueType newY) noexcept { y = newY; }
  18734. /** Returns a point which has the same Y position as this one, but a new X. */
  18735. Point withX (const ValueType newX) const noexcept { return Point (newX, y); }
  18736. /** Returns a point which has the same X position as this one, but a new Y. */
  18737. Point withY (const ValueType newY) const noexcept { return Point (x, newY); }
  18738. /** Changes the point's x and y co-ordinates. */
  18739. void setXY (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  18740. /** Adds a pair of co-ordinates to this value. */
  18741. void addXY (const ValueType xToAdd, const ValueType yToAdd) noexcept { x += xToAdd; y += yToAdd; }
  18742. /** Returns a point with a given offset from this one. */
  18743. Point translated (const ValueType xDelta, const ValueType yDelta) const noexcept { return Point (x + xDelta, y + yDelta); }
  18744. /** Adds two points together. */
  18745. Point operator+ (const Point& other) const noexcept { return Point (x + other.x, y + other.y); }
  18746. /** Adds another point's co-ordinates to this one. */
  18747. Point& operator+= (const Point& other) noexcept { x += other.x; y += other.y; return *this; }
  18748. /** Subtracts one points from another. */
  18749. Point operator- (const Point& other) const noexcept { return Point (x - other.x, y - other.y); }
  18750. /** Subtracts another point's co-ordinates to this one. */
  18751. Point& operator-= (const Point& other) noexcept { x -= other.x; y -= other.y; return *this; }
  18752. /** Returns a point whose coordinates are multiplied by a given value. */
  18753. Point operator* (const ValueType multiplier) const noexcept { return Point (x * multiplier, y * multiplier); }
  18754. /** Multiplies the point's co-ordinates by a value. */
  18755. Point& operator*= (const ValueType multiplier) noexcept { x *= multiplier; y *= multiplier; return *this; }
  18756. /** Returns a point whose coordinates are divided by a given value. */
  18757. Point operator/ (const ValueType divisor) const noexcept { return Point (x / divisor, y / divisor); }
  18758. /** Divides the point's co-ordinates by a value. */
  18759. Point& operator/= (const ValueType divisor) noexcept { x /= divisor; y /= divisor; return *this; }
  18760. /** Returns the inverse of this point. */
  18761. Point operator-() const noexcept { return Point (-x, -y); }
  18762. /** Returns the straight-line distance between this point and another one. */
  18763. ValueType getDistanceFromOrigin() const noexcept { return juce_hypot (x, y); }
  18764. /** Returns the straight-line distance between this point and another one. */
  18765. ValueType getDistanceFrom (const Point& other) const noexcept { return juce_hypot (x - other.x, y - other.y); }
  18766. /** Returns the angle from this point to another one.
  18767. The return value is the number of radians clockwise from the 3 o'clock direction,
  18768. where this point is the centre and the other point is on the circumference.
  18769. */
  18770. ValueType getAngleToPoint (const Point& other) const noexcept { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  18771. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  18772. @param radius the radius of the circle.
  18773. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18774. */
  18775. Point getPointOnCircumference (const float radius, const float angle) const noexcept { return Point<float> (x + radius * std::sin (angle),
  18776. y - radius * std::cos (angle)); }
  18777. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  18778. @param radiusX the horizontal radius of the circle.
  18779. @param radiusY the vertical radius of the circle.
  18780. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18781. */
  18782. Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const noexcept { return Point<float> (x + radiusX * std::sin (angle),
  18783. y - radiusY * std::cos (angle)); }
  18784. /** Uses a transform to change the point's co-ordinates.
  18785. This will only compile if ValueType = float!
  18786. @see AffineTransform::transformPoint
  18787. */
  18788. void applyTransform (const AffineTransform& transform) noexcept { transform.transformPoint (x, y); }
  18789. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  18790. Point transformedBy (const AffineTransform& transform) const noexcept { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  18791. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  18792. /** Casts this point to a Point<int> object. */
  18793. Point<int> toInt() const noexcept { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  18794. /** Casts this point to a Point<float> object. */
  18795. Point<float> toFloat() const noexcept { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  18796. /** Casts this point to a Point<double> object. */
  18797. Point<double> toDouble() const noexcept { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  18798. /** Returns the point as a string in the form "x, y". */
  18799. String toString() const { return String (x) + ", " + String (y); }
  18800. private:
  18801. ValueType x, y;
  18802. };
  18803. #endif // __JUCE_POINT_JUCEHEADER__
  18804. /*** End of inlined file: juce_Point.h ***/
  18805. /**
  18806. Contains position and status information about a mouse event.
  18807. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  18808. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  18809. */
  18810. class JUCE_API MouseEvent
  18811. {
  18812. public:
  18813. /** Creates a MouseEvent.
  18814. Normally an application will never need to use this.
  18815. @param source the source that's invoking the event
  18816. @param position the position of the mouse, relative to the component that is passed-in
  18817. @param modifiers the key modifiers at the time of the event
  18818. @param eventComponent the component that the mouse event applies to
  18819. @param originator the component that originally received the event
  18820. @param eventTime the time the event happened
  18821. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  18822. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18823. the same as the current mouse-x position.
  18824. @param mouseDownTime the time at which the corresponding mouse-down event happened
  18825. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18826. the same as the current mouse-event time.
  18827. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  18828. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  18829. */
  18830. MouseEvent (MouseInputSource& source,
  18831. const Point<int>& position,
  18832. const ModifierKeys& modifiers,
  18833. Component* eventComponent,
  18834. Component* originator,
  18835. const Time& eventTime,
  18836. const Point<int> mouseDownPos,
  18837. const Time& mouseDownTime,
  18838. int numberOfClicks,
  18839. bool mouseWasDragged) noexcept;
  18840. /** Destructor. */
  18841. ~MouseEvent() noexcept;
  18842. /** The x-position of the mouse when the event occurred.
  18843. This value is relative to the top-left of the component to which the
  18844. event applies (as indicated by the MouseEvent::eventComponent field).
  18845. */
  18846. const int x;
  18847. /** The y-position of the mouse when the event occurred.
  18848. This value is relative to the top-left of the component to which the
  18849. event applies (as indicated by the MouseEvent::eventComponent field).
  18850. */
  18851. const int y;
  18852. /** The key modifiers associated with the event.
  18853. This will let you find out which mouse buttons were down, as well as which
  18854. modifier keys were held down.
  18855. When used for mouse-up events, this will indicate the state of the mouse buttons
  18856. just before they were released, so that you can tell which button they let go of.
  18857. */
  18858. const ModifierKeys mods;
  18859. /** The component that this event applies to.
  18860. This is usually the component that the mouse was over at the time, but for mouse-drag
  18861. events the mouse could actually be over a different component and the events are
  18862. still sent to the component that the button was originally pressed on.
  18863. The x and y member variables are relative to this component's position.
  18864. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18865. component, this pointer will be updated, but originalComponent remains unchanged.
  18866. @see originalComponent
  18867. */
  18868. Component* const eventComponent;
  18869. /** The component that the event first occurred on.
  18870. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18871. component, this value remains unchanged to indicate the first component that received it.
  18872. @see eventComponent
  18873. */
  18874. Component* const originalComponent;
  18875. /** The time that this mouse-event occurred.
  18876. */
  18877. const Time eventTime;
  18878. /** The source device that generated this event.
  18879. */
  18880. MouseInputSource& source;
  18881. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18882. The co-ordinate is relative to the component specified in MouseEvent::component.
  18883. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18884. */
  18885. int getMouseDownX() const noexcept;
  18886. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18887. The co-ordinate is relative to the component specified in MouseEvent::component.
  18888. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18889. */
  18890. int getMouseDownY() const noexcept;
  18891. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18892. The co-ordinates are relative to the component specified in MouseEvent::component.
  18893. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18894. */
  18895. const Point<int> getMouseDownPosition() const noexcept;
  18896. /** Returns the straight-line distance between where the mouse is now and where it
  18897. was the last time the button was pressed.
  18898. This is quite handy for things like deciding whether the user has moved far enough
  18899. for it to be considered a drag operation.
  18900. @see getDistanceFromDragStartX
  18901. */
  18902. int getDistanceFromDragStart() const noexcept;
  18903. /** Returns the difference between the mouse's current x postion and where it was
  18904. when the button was last pressed.
  18905. @see getDistanceFromDragStart
  18906. */
  18907. int getDistanceFromDragStartX() const noexcept;
  18908. /** Returns the difference between the mouse's current y postion and where it was
  18909. when the button was last pressed.
  18910. @see getDistanceFromDragStart
  18911. */
  18912. int getDistanceFromDragStartY() const noexcept;
  18913. /** Returns the difference between the mouse's current postion and where it was
  18914. when the button was last pressed.
  18915. @see getDistanceFromDragStart
  18916. */
  18917. const Point<int> getOffsetFromDragStart() const noexcept;
  18918. /** Returns true if the mouse has just been clicked.
  18919. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18920. the user has dragged the mouse more than a few pixels from the place where the
  18921. mouse-down occurred.
  18922. Once they have dragged it far enough for this method to return false, it will continue
  18923. to return false until the mouse-up, even if they move the mouse back to the same
  18924. position where they originally pressed it. This means that it's very handy for
  18925. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18926. callback to ignore any small movements they might make while clicking.
  18927. @returns true if the mouse wasn't dragged by more than a few pixels between
  18928. the last time the button was pressed and released.
  18929. */
  18930. bool mouseWasClicked() const noexcept;
  18931. /** For a click event, the number of times the mouse was clicked in succession.
  18932. So for example a double-click event will return 2, a triple-click 3, etc.
  18933. */
  18934. int getNumberOfClicks() const noexcept { return numberOfClicks; }
  18935. /** Returns the time that the mouse button has been held down for.
  18936. If called from a mouseDrag or mouseUp callback, this will return the
  18937. number of milliseconds since the corresponding mouseDown event occurred.
  18938. If called in other contexts, e.g. a mouseMove, then the returned value
  18939. may be 0 or an undefined value.
  18940. */
  18941. int getLengthOfMousePress() const noexcept;
  18942. /** The position of the mouse when the event occurred.
  18943. This position is relative to the top-left of the component to which the
  18944. event applies (as indicated by the MouseEvent::eventComponent field).
  18945. */
  18946. const Point<int> getPosition() const noexcept;
  18947. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18948. The co-ordinates are relative to the top-left of the main monitor.
  18949. @see getScreenPosition
  18950. */
  18951. int getScreenX() const;
  18952. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18953. The co-ordinates are relative to the top-left of the main monitor.
  18954. @see getScreenPosition
  18955. */
  18956. int getScreenY() const;
  18957. /** Returns the mouse position of this event, in global screen co-ordinates.
  18958. The co-ordinates are relative to the top-left of the main monitor.
  18959. @see getMouseDownScreenPosition
  18960. */
  18961. const Point<int> getScreenPosition() const;
  18962. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18963. The co-ordinates are relative to the top-left of the main monitor.
  18964. @see getMouseDownScreenPosition
  18965. */
  18966. int getMouseDownScreenX() const;
  18967. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18968. The co-ordinates are relative to the top-left of the main monitor.
  18969. @see getMouseDownScreenPosition
  18970. */
  18971. int getMouseDownScreenY() const;
  18972. /** Returns the co-ordinates at which the mouse button was last pressed.
  18973. The co-ordinates are relative to the top-left of the main monitor.
  18974. @see getScreenPosition
  18975. */
  18976. const Point<int> getMouseDownScreenPosition() const;
  18977. /** Creates a version of this event that is relative to a different component.
  18978. The x and y positions of the event that is returned will have been
  18979. adjusted to be relative to the new component.
  18980. */
  18981. MouseEvent getEventRelativeTo (Component* otherComponent) const noexcept;
  18982. /** Creates a copy of this event with a different position.
  18983. All other members of the event object are the same, but the x and y are
  18984. replaced with these new values.
  18985. */
  18986. MouseEvent withNewPosition (const Point<int>& newPosition) const noexcept;
  18987. /** Changes the application-wide setting for the double-click time limit.
  18988. This is the maximum length of time between mouse-clicks for it to be
  18989. considered a double-click. It's used by the Component class.
  18990. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18991. */
  18992. static void setDoubleClickTimeout (int timeOutMilliseconds) noexcept;
  18993. /** Returns the application-wide setting for the double-click time limit.
  18994. This is the maximum length of time between mouse-clicks for it to be
  18995. considered a double-click. It's used by the Component class.
  18996. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18997. */
  18998. static int getDoubleClickTimeout() noexcept;
  18999. private:
  19000. const Point<int> mouseDownPos;
  19001. const Time mouseDownTime;
  19002. const int numberOfClicks;
  19003. const bool wasMovedSinceMouseDown;
  19004. static int doubleClickTimeOutMs;
  19005. MouseEvent& operator= (const MouseEvent&);
  19006. };
  19007. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  19008. /*** End of inlined file: juce_MouseEvent.h ***/
  19009. /*** Start of inlined file: juce_ComponentListener.h ***/
  19010. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  19011. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  19012. class Component;
  19013. /**
  19014. Gets informed about changes to a component's hierarchy or position.
  19015. To monitor a component for changes, register a subclass of ComponentListener
  19016. with the component using Component::addComponentListener().
  19017. Be sure to deregister listeners before you delete them!
  19018. @see Component::addComponentListener, Component::removeComponentListener
  19019. */
  19020. class JUCE_API ComponentListener
  19021. {
  19022. public:
  19023. /** Destructor. */
  19024. virtual ~ComponentListener() {}
  19025. /** Called when the component's position or size changes.
  19026. @param component the component that was moved or resized
  19027. @param wasMoved true if the component's top-left corner has just moved
  19028. @param wasResized true if the component's width or height has just changed
  19029. @see Component::setBounds, Component::resized, Component::moved
  19030. */
  19031. virtual void componentMovedOrResized (Component& component,
  19032. bool wasMoved,
  19033. bool wasResized);
  19034. /** Called when the component is brought to the top of the z-order.
  19035. @param component the component that was moved
  19036. @see Component::toFront, Component::broughtToFront
  19037. */
  19038. virtual void componentBroughtToFront (Component& component);
  19039. /** Called when the component is made visible or invisible.
  19040. @param component the component that changed
  19041. @see Component::setVisible
  19042. */
  19043. virtual void componentVisibilityChanged (Component& component);
  19044. /** Called when the component has children added or removed.
  19045. @param component the component whose children were changed
  19046. @see Component::childrenChanged, Component::addChildComponent,
  19047. Component::removeChildComponent
  19048. */
  19049. virtual void componentChildrenChanged (Component& component);
  19050. /** Called to indicate that the component's parents have changed.
  19051. When a component is added or removed from its parent, all of its children
  19052. will produce this notification (recursively - so all children of its
  19053. children will also be called as well).
  19054. @param component the component that this listener is registered with
  19055. @see Component::parentHierarchyChanged
  19056. */
  19057. virtual void componentParentHierarchyChanged (Component& component);
  19058. /** Called when the component's name is changed.
  19059. @see Component::setName, Component::getName
  19060. */
  19061. virtual void componentNameChanged (Component& component);
  19062. /** Called when the component is in the process of being deleted.
  19063. This callback is made from inside the destructor, so be very, very cautious
  19064. about what you do in here.
  19065. In particular, bear in mind that it's the Component base class's destructor that calls
  19066. this - so if the object that's being deleted is a subclass of Component, then the
  19067. subclass layers of the object will already have been destructed when it gets to this
  19068. point!
  19069. */
  19070. virtual void componentBeingDeleted (Component& component);
  19071. };
  19072. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  19073. /*** End of inlined file: juce_ComponentListener.h ***/
  19074. /*** Start of inlined file: juce_KeyListener.h ***/
  19075. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  19076. #define __JUCE_KEYLISTENER_JUCEHEADER__
  19077. /*** Start of inlined file: juce_KeyPress.h ***/
  19078. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  19079. #define __JUCE_KEYPRESS_JUCEHEADER__
  19080. /**
  19081. Represents a key press, including any modifier keys that are needed.
  19082. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  19083. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  19084. */
  19085. class JUCE_API KeyPress
  19086. {
  19087. public:
  19088. /** Creates an (invalid) KeyPress.
  19089. @see isValid
  19090. */
  19091. KeyPress() noexcept;
  19092. /** Creates a KeyPress for a key and some modifiers.
  19093. e.g.
  19094. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  19095. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  19096. @param keyCode a code that represents the key - this value must be
  19097. one of special constants listed in this class, or an
  19098. 8-bit character code such as a letter (case is ignored),
  19099. digit or a simple key like "," or ".". Note that this
  19100. isn't the same as the textCharacter parameter, so for example
  19101. a keyCode of 'a' and a shift-key modifier should have a
  19102. textCharacter value of 'A'.
  19103. @param modifiers the modifiers to associate with the keystroke
  19104. @param textCharacter the character that would be printed if someone typed
  19105. this keypress into a text editor. This value may be
  19106. null if the keypress is a non-printing character
  19107. @see getKeyCode, isKeyCode, getModifiers
  19108. */
  19109. KeyPress (int keyCode,
  19110. const ModifierKeys& modifiers,
  19111. juce_wchar textCharacter) noexcept;
  19112. /** Creates a keypress with a keyCode but no modifiers or text character.
  19113. */
  19114. KeyPress (int keyCode) noexcept;
  19115. /** Creates a copy of another KeyPress. */
  19116. KeyPress (const KeyPress& other) noexcept;
  19117. /** Copies this KeyPress from another one. */
  19118. KeyPress& operator= (const KeyPress& other) noexcept;
  19119. /** Compares two KeyPress objects. */
  19120. bool operator== (const KeyPress& other) const noexcept;
  19121. /** Compares two KeyPress objects. */
  19122. bool operator!= (const KeyPress& other) const noexcept;
  19123. /** Returns true if this is a valid KeyPress.
  19124. A null keypress can be created by the default constructor, in case it's
  19125. needed.
  19126. */
  19127. bool isValid() const noexcept { return keyCode != 0; }
  19128. /** Returns the key code itself.
  19129. This will either be one of the special constants defined in this class,
  19130. or an 8-bit character code.
  19131. */
  19132. int getKeyCode() const noexcept { return keyCode; }
  19133. /** Returns the key modifiers.
  19134. @see ModifierKeys
  19135. */
  19136. const ModifierKeys getModifiers() const noexcept { return mods; }
  19137. /** Returns the character that is associated with this keypress.
  19138. This is the character that you'd expect to see printed if you press this
  19139. keypress in a text editor or similar component.
  19140. */
  19141. juce_wchar getTextCharacter() const noexcept { return textCharacter; }
  19142. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  19143. the modifiers.
  19144. The values for key codes can either be one of the special constants defined in
  19145. this class, or an 8-bit character code.
  19146. @see getKeyCode
  19147. */
  19148. bool isKeyCode (int keyCodeToCompare) const noexcept { return keyCode == keyCodeToCompare; }
  19149. /** Converts a textual key description to a KeyPress.
  19150. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  19151. This isn't designed to cope with any kind of input, but should be given the
  19152. strings that are created by the getTextDescription() method.
  19153. If the string can't be parsed, the object returned will be invalid.
  19154. @see getTextDescription
  19155. */
  19156. static const KeyPress createFromDescription (const String& textVersion);
  19157. /** Creates a textual description of the key combination.
  19158. e.g. "CTRL + C" or "DELETE".
  19159. To store a keypress in a file, use this method, along with createFromDescription()
  19160. to retrieve it later.
  19161. */
  19162. String getTextDescription() const;
  19163. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  19164. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  19165. modifier key descriptions that are returned by getTextDescription()
  19166. */
  19167. String getTextDescriptionWithIcons() const;
  19168. /** Checks whether the user is currently holding down the keys that make up this
  19169. KeyPress.
  19170. Note that this will return false if any extra modifier keys are
  19171. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  19172. then it will be false.
  19173. */
  19174. bool isCurrentlyDown() const;
  19175. /** Checks whether a particular key is held down, irrespective of modifiers.
  19176. The values for key codes can either be one of the special constants defined in
  19177. this class, or an 8-bit character code.
  19178. */
  19179. static bool isKeyCurrentlyDown (int keyCode);
  19180. // Key codes
  19181. //
  19182. // Note that the actual values of these are platform-specific and may change
  19183. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  19184. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  19185. //
  19186. static const int spaceKey; /**< key-code for the space bar */
  19187. static const int escapeKey; /**< key-code for the escape key */
  19188. static const int returnKey; /**< key-code for the return key*/
  19189. static const int tabKey; /**< key-code for the tab key*/
  19190. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  19191. static const int backspaceKey; /**< key-code for the backspace key */
  19192. static const int insertKey; /**< key-code for the insert key */
  19193. static const int upKey; /**< key-code for the cursor-up key */
  19194. static const int downKey; /**< key-code for the cursor-down key */
  19195. static const int leftKey; /**< key-code for the cursor-left key */
  19196. static const int rightKey; /**< key-code for the cursor-right key */
  19197. static const int pageUpKey; /**< key-code for the page-up key */
  19198. static const int pageDownKey; /**< key-code for the page-down key */
  19199. static const int homeKey; /**< key-code for the home key */
  19200. static const int endKey; /**< key-code for the end key */
  19201. static const int F1Key; /**< key-code for the F1 key */
  19202. static const int F2Key; /**< key-code for the F2 key */
  19203. static const int F3Key; /**< key-code for the F3 key */
  19204. static const int F4Key; /**< key-code for the F4 key */
  19205. static const int F5Key; /**< key-code for the F5 key */
  19206. static const int F6Key; /**< key-code for the F6 key */
  19207. static const int F7Key; /**< key-code for the F7 key */
  19208. static const int F8Key; /**< key-code for the F8 key */
  19209. static const int F9Key; /**< key-code for the F9 key */
  19210. static const int F10Key; /**< key-code for the F10 key */
  19211. static const int F11Key; /**< key-code for the F11 key */
  19212. static const int F12Key; /**< key-code for the F12 key */
  19213. static const int F13Key; /**< key-code for the F13 key */
  19214. static const int F14Key; /**< key-code for the F14 key */
  19215. static const int F15Key; /**< key-code for the F15 key */
  19216. static const int F16Key; /**< key-code for the F16 key */
  19217. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  19218. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  19219. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  19220. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  19221. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  19222. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  19223. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  19224. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  19225. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  19226. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  19227. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  19228. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  19229. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  19230. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  19231. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  19232. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  19233. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  19234. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  19235. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  19236. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  19237. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  19238. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  19239. private:
  19240. int keyCode;
  19241. ModifierKeys mods;
  19242. juce_wchar textCharacter;
  19243. JUCE_LEAK_DETECTOR (KeyPress);
  19244. };
  19245. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  19246. /*** End of inlined file: juce_KeyPress.h ***/
  19247. class Component;
  19248. /**
  19249. Receives callbacks when keys are pressed.
  19250. You can add a key listener to a component to be informed when that component
  19251. gets key events. See the Component::addListener method for more details.
  19252. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  19253. */
  19254. class JUCE_API KeyListener
  19255. {
  19256. public:
  19257. /** Destructor. */
  19258. virtual ~KeyListener() {}
  19259. /** Called to indicate that a key has been pressed.
  19260. If your implementation returns true, then the key event is considered to have
  19261. been consumed, and will not be passed on to any other components. If it returns
  19262. false, then the key will be passed to other components that might want to use it.
  19263. @param key the keystroke, including modifier keys
  19264. @param originatingComponent the component that received the key event
  19265. @see keyStateChanged, Component::keyPressed
  19266. */
  19267. virtual bool keyPressed (const KeyPress& key,
  19268. Component* originatingComponent) = 0;
  19269. /** Called when any key is pressed or released.
  19270. When this is called, classes that might be interested in
  19271. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  19272. check whether their key has changed.
  19273. If your implementation returns true, then the key event is considered to have
  19274. been consumed, and will not be passed on to any other components. If it returns
  19275. false, then the key will be passed to other components that might want to use it.
  19276. @param originatingComponent the component that received the key event
  19277. @param isKeyDown true if a key is being pressed, false if one is being released
  19278. @see KeyPress, Component::keyStateChanged
  19279. */
  19280. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  19281. };
  19282. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  19283. /*** End of inlined file: juce_KeyListener.h ***/
  19284. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  19285. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19286. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19287. class Component;
  19288. /**
  19289. Controls the order in which focus moves between components.
  19290. The default algorithm used by this class to work out the order of traversal
  19291. is as follows:
  19292. - if two components both have an explicit focus order specified, then the
  19293. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  19294. method).
  19295. - any component with an explicit focus order greater than 0 comes before ones
  19296. that don't have an order specified.
  19297. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  19298. order.
  19299. If you need traversal in a more customised way, you can create a subclass
  19300. of KeyboardFocusTraverser that uses your own algorithm, and use
  19301. Component::createFocusTraverser() to create it.
  19302. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  19303. */
  19304. class JUCE_API KeyboardFocusTraverser
  19305. {
  19306. public:
  19307. KeyboardFocusTraverser();
  19308. /** Destructor. */
  19309. virtual ~KeyboardFocusTraverser();
  19310. /** Returns the component that should be given focus after the specified one
  19311. when moving "forwards".
  19312. The default implementation will return the next component which is to the
  19313. right of or below this one.
  19314. This may return 0 if there's no suitable candidate.
  19315. */
  19316. virtual Component* getNextComponent (Component* current);
  19317. /** Returns the component that should be given focus after the specified one
  19318. when moving "backwards".
  19319. The default implementation will return the next component which is to the
  19320. left of or above this one.
  19321. This may return 0 if there's no suitable candidate.
  19322. */
  19323. virtual Component* getPreviousComponent (Component* current);
  19324. /** Returns the component that should receive focus be default within the given
  19325. parent component.
  19326. The default implementation will just return the foremost child component that
  19327. wants focus.
  19328. This may return 0 if there's no suitable candidate.
  19329. */
  19330. virtual Component* getDefaultComponent (Component* parentComponent);
  19331. };
  19332. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19333. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  19334. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  19335. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19336. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19337. /*** Start of inlined file: juce_Graphics.h ***/
  19338. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  19339. #define __JUCE_GRAPHICS_JUCEHEADER__
  19340. /*** Start of inlined file: juce_Font.h ***/
  19341. #ifndef __JUCE_FONT_JUCEHEADER__
  19342. #define __JUCE_FONT_JUCEHEADER__
  19343. /*** Start of inlined file: juce_Typeface.h ***/
  19344. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  19345. #define __JUCE_TYPEFACE_JUCEHEADER__
  19346. class Path;
  19347. class Font;
  19348. class EdgeTable;
  19349. class AffineTransform;
  19350. /**
  19351. A typeface represents a size-independent font.
  19352. This base class is abstract, but calling createSystemTypefaceFor() will return
  19353. a platform-specific subclass that can be used.
  19354. The CustomTypeface subclass allow you to build your own typeface, and to
  19355. load and save it in the Juce typeface format.
  19356. Normally you should never need to deal directly with Typeface objects - the Font
  19357. class does everything you typically need for rendering text.
  19358. @see CustomTypeface, Font
  19359. */
  19360. class JUCE_API Typeface : public SingleThreadedReferenceCountedObject
  19361. {
  19362. public:
  19363. /** A handy typedef for a pointer to a typeface. */
  19364. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  19365. /** Returns the name of the typeface.
  19366. @see Font::getTypefaceName
  19367. */
  19368. const String& getName() const noexcept { return name; }
  19369. /** Creates a new system typeface. */
  19370. static const Ptr createSystemTypefaceFor (const Font& font);
  19371. /** Destructor. */
  19372. virtual ~Typeface();
  19373. /** Returns true if this typeface can be used to render the specified font.
  19374. When called, the font will already have been checked to make sure that its name and
  19375. style flags match the typeface.
  19376. */
  19377. virtual bool isSuitableForFont (const Font&) const { return true; }
  19378. /** Returns the ascent of the font, as a proportion of its height.
  19379. The height is considered to always be normalised as 1.0, so this will be a
  19380. value less that 1.0, indicating the proportion of the font that lies above
  19381. its baseline.
  19382. */
  19383. virtual float getAscent() const = 0;
  19384. /** Returns the descent of the font, as a proportion of its height.
  19385. The height is considered to always be normalised as 1.0, so this will be a
  19386. value less that 1.0, indicating the proportion of the font that lies below
  19387. its baseline.
  19388. */
  19389. virtual float getDescent() const = 0;
  19390. /** Measures the width of a line of text.
  19391. The distance returned is based on the font having an normalised height of 1.0.
  19392. You should never need to call this directly! Use Font::getStringWidth() instead!
  19393. */
  19394. virtual float getStringWidth (const String& text) = 0;
  19395. /** Converts a line of text into its glyph numbers and their positions.
  19396. The distances returned are based on the font having an normalised height of 1.0.
  19397. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  19398. */
  19399. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  19400. /** Returns the outline for a glyph.
  19401. The path returned will be normalised to a font height of 1.0.
  19402. */
  19403. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  19404. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  19405. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  19406. /** Returns true if the typeface uses hinting. */
  19407. virtual bool isHinted() const { return false; }
  19408. /** Changes the number of fonts that are cached in memory. */
  19409. static void setTypefaceCacheSize (int numFontsToCache);
  19410. protected:
  19411. String name;
  19412. explicit Typeface (const String& name) noexcept;
  19413. static const Ptr getFallbackTypeface();
  19414. private:
  19415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  19416. };
  19417. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  19418. /*** End of inlined file: juce_Typeface.h ***/
  19419. class LowLevelGraphicsContext;
  19420. /**
  19421. Represents a particular font, including its size, style, etc.
  19422. Apart from the typeface to be used, a Font object also dictates whether
  19423. the font is bold, italic, underlined, how big it is, and its kerning and
  19424. horizontal scale factor.
  19425. @see Typeface
  19426. */
  19427. class JUCE_API Font
  19428. {
  19429. public:
  19430. /** A combination of these values is used by the constructor to specify the
  19431. style of font to use.
  19432. */
  19433. enum FontStyleFlags
  19434. {
  19435. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  19436. bold = 1, /**< boldens the font. @see setStyleFlags */
  19437. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  19438. underlined = 4 /**< underlines the font. @see setStyleFlags */
  19439. };
  19440. /** Creates a sans-serif font in a given size.
  19441. @param fontHeight the height in pixels (can be fractional)
  19442. @param styleFlags the style to use - this can be a combination of the
  19443. Font::bold, Font::italic and Font::underlined, or
  19444. just Font::plain for the normal style.
  19445. @see FontStyleFlags, getDefaultSansSerifFontName
  19446. */
  19447. Font (float fontHeight, int styleFlags = plain);
  19448. /** Creates a font with a given typeface and parameters.
  19449. @param typefaceName the name of the typeface to use
  19450. @param fontHeight the height in pixels (can be fractional)
  19451. @param styleFlags the style to use - this can be a combination of the
  19452. Font::bold, Font::italic and Font::underlined, or
  19453. just Font::plain for the normal style.
  19454. @see FontStyleFlags, getDefaultSansSerifFontName
  19455. */
  19456. Font (const String& typefaceName, float fontHeight, int styleFlags);
  19457. /** Creates a copy of another Font object. */
  19458. Font (const Font& other) noexcept;
  19459. /** Creates a font for a typeface. */
  19460. Font (const Typeface::Ptr& typeface);
  19461. /** Creates a basic sans-serif font at a default height.
  19462. You should use one of the other constructors for creating a font that you're planning
  19463. on drawing with - this constructor is here to help initialise objects before changing
  19464. the font's settings later.
  19465. */
  19466. Font();
  19467. /** Copies this font from another one. */
  19468. Font& operator= (const Font& other) noexcept;
  19469. bool operator== (const Font& other) const noexcept;
  19470. bool operator!= (const Font& other) const noexcept;
  19471. /** Destructor. */
  19472. ~Font() noexcept;
  19473. /** Changes the name of the typeface family.
  19474. e.g. "Arial", "Courier", etc.
  19475. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19476. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19477. but are generic names that are used to represent the various default fonts.
  19478. If you need to know the exact typeface name being used, you can call
  19479. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19480. If a suitable font isn't found on the machine, it'll just use a default instead.
  19481. */
  19482. void setTypefaceName (const String& faceName);
  19483. /** Returns the name of the typeface family that this font uses.
  19484. e.g. "Arial", "Courier", etc.
  19485. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19486. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19487. but are generic names that are used to represent the various default fonts.
  19488. If you need to know the exact typeface name being used, you can call
  19489. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19490. */
  19491. const String& getTypefaceName() const noexcept { return font->typefaceName; }
  19492. /** Returns a typeface name that represents the default sans-serif font.
  19493. This is also the typeface that will be used when a font is created without
  19494. specifying any typeface details.
  19495. Note that this method just returns a generic placeholder string that means "the default
  19496. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  19497. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19498. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  19499. */
  19500. static const String& getDefaultSansSerifFontName();
  19501. /** Returns a typeface name that represents the default sans-serif font.
  19502. Note that this method just returns a generic placeholder string that means "the default
  19503. serif font" - it's not the actual name of this font. To get the actual name, use
  19504. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19505. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  19506. */
  19507. static const String& getDefaultSerifFontName();
  19508. /** Returns a typeface name that represents the default sans-serif font.
  19509. Note that this method just returns a generic placeholder string that means "the default
  19510. monospaced font" - it's not the actual name of this font. To get the actual name, use
  19511. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19512. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  19513. */
  19514. static const String& getDefaultMonospacedFontName();
  19515. /** Returns the typeface names of the default fonts on the current platform. */
  19516. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  19517. /** Returns the total height of this font.
  19518. This is the maximum height, from the top of the ascent to the bottom of the
  19519. descenders.
  19520. @see setHeight, setHeightWithoutChangingWidth, getAscent
  19521. */
  19522. float getHeight() const noexcept { return font->height; }
  19523. /** Changes the font's height.
  19524. @see getHeight, setHeightWithoutChangingWidth
  19525. */
  19526. void setHeight (float newHeight);
  19527. /** Changes the font's height without changing its width.
  19528. This alters the horizontal scale to compensate for the change in height.
  19529. */
  19530. void setHeightWithoutChangingWidth (float newHeight);
  19531. /** Returns the height of the font above its baseline.
  19532. This is the maximum height from the baseline to the top.
  19533. @see getHeight, getDescent
  19534. */
  19535. float getAscent() const;
  19536. /** Returns the amount that the font descends below its baseline.
  19537. This is calculated as (getHeight() - getAscent()).
  19538. @see getAscent, getHeight
  19539. */
  19540. float getDescent() const;
  19541. /** Returns the font's style flags.
  19542. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  19543. enum, to describe whether the font is bold, italic, etc.
  19544. @see FontStyleFlags
  19545. */
  19546. int getStyleFlags() const noexcept { return font->styleFlags; }
  19547. /** Changes the font's style.
  19548. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  19549. enum, to set the font's properties
  19550. @see FontStyleFlags
  19551. */
  19552. void setStyleFlags (int newFlags);
  19553. /** Makes the font bold or non-bold. */
  19554. void setBold (bool shouldBeBold);
  19555. /** Returns a copy of this font with the bold attribute set. */
  19556. Font boldened() const;
  19557. /** Returns true if the font is bold. */
  19558. bool isBold() const noexcept;
  19559. /** Makes the font italic or non-italic. */
  19560. void setItalic (bool shouldBeItalic);
  19561. /** Returns a copy of this font with the italic attribute set. */
  19562. Font italicised() const;
  19563. /** Returns true if the font is italic. */
  19564. bool isItalic() const noexcept;
  19565. /** Makes the font underlined or non-underlined. */
  19566. void setUnderline (bool shouldBeUnderlined);
  19567. /** Returns true if the font is underlined. */
  19568. bool isUnderlined() const noexcept;
  19569. /** Changes the font's horizontal scale factor.
  19570. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  19571. narrower, greater than 1.0 will be stretched out.
  19572. */
  19573. void setHorizontalScale (float scaleFactor);
  19574. /** Returns the font's horizontal scale.
  19575. A value of 1.0 is the normal scale, less than this will be narrower, greater
  19576. than 1.0 will be stretched out.
  19577. @see setHorizontalScale
  19578. */
  19579. float getHorizontalScale() const noexcept { return font->horizontalScale; }
  19580. /** Changes the font's kerning.
  19581. @param extraKerning a multiple of the font's height that will be added
  19582. to space between the characters. So a value of zero is
  19583. normal spacing, positive values spread the letters out,
  19584. negative values make them closer together.
  19585. */
  19586. void setExtraKerningFactor (float extraKerning);
  19587. /** Returns the font's kerning.
  19588. This is the extra space added between adjacent characters, as a proportion
  19589. of the font's height.
  19590. A value of zero is normal spacing, positive values will spread the letters
  19591. out more, and negative values make them closer together.
  19592. */
  19593. float getExtraKerningFactor() const noexcept { return font->kerning; }
  19594. /** Changes all the font's characteristics with one call. */
  19595. void setSizeAndStyle (float newHeight,
  19596. int newStyleFlags,
  19597. float newHorizontalScale,
  19598. float newKerningAmount);
  19599. /** Returns the total width of a string as it would be drawn using this font.
  19600. For a more accurate floating-point result, use getStringWidthFloat().
  19601. */
  19602. int getStringWidth (const String& text) const;
  19603. /** Returns the total width of a string as it would be drawn using this font.
  19604. @see getStringWidth
  19605. */
  19606. float getStringWidthFloat (const String& text) const;
  19607. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  19608. An extra x offset is added at the end of the run, to indicate where the right hand
  19609. edge of the last character is.
  19610. */
  19611. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  19612. /** Returns the typeface used by this font.
  19613. Note that the object returned may go out of scope if this font is deleted
  19614. or has its style changed.
  19615. */
  19616. Typeface* getTypeface() const;
  19617. /** Creates an array of Font objects to represent all the fonts on the system.
  19618. If you just need the names of the typefaces, you can also use
  19619. findAllTypefaceNames() instead.
  19620. @param results the array to which new Font objects will be added.
  19621. */
  19622. static void findFonts (Array<Font>& results);
  19623. /** Returns a list of all the available typeface names.
  19624. The names returned can be passed into setTypefaceName().
  19625. You can use this instead of findFonts() if you only need their names, and not
  19626. font objects.
  19627. */
  19628. static StringArray findAllTypefaceNames();
  19629. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  19630. in the requested typeface.
  19631. */
  19632. static const String& getFallbackFontName();
  19633. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  19634. available in whatever font you're trying to use.
  19635. */
  19636. static void setFallbackFontName (const String& name);
  19637. /** Creates a string to describe this font.
  19638. The string will contain information to describe the font's typeface, size, and
  19639. style. To recreate the font from this string, use fromString().
  19640. */
  19641. String toString() const;
  19642. /** Recreates a font from its stringified encoding.
  19643. This method takes a string that was created by toString(), and recreates the
  19644. original font.
  19645. */
  19646. static Font fromString (const String& fontDescription);
  19647. private:
  19648. friend class FontGlyphAlphaMap;
  19649. friend class TypefaceCache;
  19650. class SharedFontInternal : public SingleThreadedReferenceCountedObject
  19651. {
  19652. public:
  19653. SharedFontInternal (float height, int styleFlags) noexcept;
  19654. SharedFontInternal (const String& typefaceName, float height, int styleFlags) noexcept;
  19655. SharedFontInternal (const Typeface::Ptr& typeface) noexcept;
  19656. SharedFontInternal (const SharedFontInternal& other) noexcept;
  19657. bool operator== (const SharedFontInternal&) const noexcept;
  19658. String typefaceName;
  19659. float height, horizontalScale, kerning, ascent;
  19660. int styleFlags;
  19661. Typeface::Ptr typeface;
  19662. };
  19663. ReferenceCountedObjectPtr <SharedFontInternal> font;
  19664. void dupeInternalIfShared();
  19665. JUCE_LEAK_DETECTOR (Font);
  19666. };
  19667. #endif // __JUCE_FONT_JUCEHEADER__
  19668. /*** End of inlined file: juce_Font.h ***/
  19669. /*** Start of inlined file: juce_Rectangle.h ***/
  19670. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  19671. #define __JUCE_RECTANGLE_JUCEHEADER__
  19672. class RectangleList;
  19673. /**
  19674. Manages a rectangle and allows geometric operations to be performed on it.
  19675. @see RectangleList, Path, Line, Point
  19676. */
  19677. template <typename ValueType>
  19678. class Rectangle
  19679. {
  19680. public:
  19681. /** Creates a rectangle of zero size.
  19682. The default co-ordinates will be (0, 0, 0, 0).
  19683. */
  19684. Rectangle() noexcept
  19685. : x(), y(), w(), h()
  19686. {
  19687. }
  19688. /** Creates a copy of another rectangle. */
  19689. Rectangle (const Rectangle& other) noexcept
  19690. : x (other.x), y (other.y),
  19691. w (other.w), h (other.h)
  19692. {
  19693. }
  19694. /** Creates a rectangle with a given position and size. */
  19695. Rectangle (const ValueType initialX, const ValueType initialY,
  19696. const ValueType width, const ValueType height) noexcept
  19697. : x (initialX), y (initialY),
  19698. w (width), h (height)
  19699. {
  19700. }
  19701. /** Creates a rectangle with a given size, and a position of (0, 0). */
  19702. Rectangle (const ValueType width, const ValueType height) noexcept
  19703. : x(), y(), w (width), h (height)
  19704. {
  19705. }
  19706. /** Creates a Rectangle from the positions of two opposite corners. */
  19707. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) noexcept
  19708. : x (jmin (corner1.getX(), corner2.getX())),
  19709. y (jmin (corner1.getY(), corner2.getY())),
  19710. w (corner1.getX() - corner2.getX()),
  19711. h (corner1.getY() - corner2.getY())
  19712. {
  19713. if (w < ValueType()) w = -w;
  19714. if (h < ValueType()) h = -h;
  19715. }
  19716. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  19717. The right and bottom values must be larger than the left and top ones, or the resulting
  19718. rectangle will have a negative size.
  19719. */
  19720. static Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  19721. const ValueType right, const ValueType bottom) noexcept
  19722. {
  19723. return Rectangle (left, top, right - left, bottom - top);
  19724. }
  19725. Rectangle& operator= (const Rectangle& other) noexcept
  19726. {
  19727. x = other.x; y = other.y;
  19728. w = other.w; h = other.h;
  19729. return *this;
  19730. }
  19731. /** Destructor. */
  19732. ~Rectangle() noexcept {}
  19733. /** Returns true if the rectangle's width and height are both zero or less */
  19734. bool isEmpty() const noexcept { return w <= ValueType() || h <= ValueType(); }
  19735. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  19736. inline ValueType getX() const noexcept { return x; }
  19737. /** Returns the y co-ordinate of the rectangle's top edge. */
  19738. inline ValueType getY() const noexcept { return y; }
  19739. /** Returns the width of the rectangle. */
  19740. inline ValueType getWidth() const noexcept { return w; }
  19741. /** Returns the height of the rectangle. */
  19742. inline ValueType getHeight() const noexcept { return h; }
  19743. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  19744. inline ValueType getRight() const noexcept { return x + w; }
  19745. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  19746. inline ValueType getBottom() const noexcept { return y + h; }
  19747. /** Returns the x co-ordinate of the rectangle's centre. */
  19748. ValueType getCentreX() const noexcept { return x + w / (ValueType) 2; }
  19749. /** Returns the y co-ordinate of the rectangle's centre. */
  19750. ValueType getCentreY() const noexcept { return y + h / (ValueType) 2; }
  19751. /** Returns the centre point of the rectangle. */
  19752. Point<ValueType> getCentre() const noexcept { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  19753. /** Returns the aspect ratio of the rectangle's width / height.
  19754. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  19755. it returns height / width. */
  19756. ValueType getAspectRatio (const bool widthOverHeight = true) const noexcept { return widthOverHeight ? w / h : h / w; }
  19757. /** Returns the rectangle's top-left position as a Point. */
  19758. Point<ValueType> getPosition() const noexcept { return Point<ValueType> (x, y); }
  19759. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19760. void setPosition (const Point<ValueType>& newPos) noexcept { x = newPos.getX(); y = newPos.getY(); }
  19761. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19762. void setPosition (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  19763. /** Returns a rectangle with the same size as this one, but a new position. */
  19764. Rectangle withPosition (const ValueType newX, const ValueType newY) const noexcept { return Rectangle (newX, newY, w, h); }
  19765. /** Returns a rectangle with the same size as this one, but a new position. */
  19766. Rectangle withPosition (const Point<ValueType>& newPos) const noexcept { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  19767. /** Returns the rectangle's top-left position as a Point. */
  19768. Point<ValueType> getTopLeft() const noexcept { return getPosition(); }
  19769. /** Returns the rectangle's top-right position as a Point. */
  19770. Point<ValueType> getTopRight() const noexcept { return Point<ValueType> (x + w, y); }
  19771. /** Returns the rectangle's bottom-left position as a Point. */
  19772. Point<ValueType> getBottomLeft() const noexcept { return Point<ValueType> (x, y + h); }
  19773. /** Returns the rectangle's bottom-right position as a Point. */
  19774. Point<ValueType> getBottomRight() const noexcept { return Point<ValueType> (x + w, y + h); }
  19775. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  19776. void setSize (const ValueType newWidth, const ValueType newHeight) noexcept { w = newWidth; h = newHeight; }
  19777. /** Returns a rectangle with the same position as this one, but a new size. */
  19778. Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const noexcept { return Rectangle (x, y, newWidth, newHeight); }
  19779. /** Changes all the rectangle's co-ordinates. */
  19780. void setBounds (const ValueType newX, const ValueType newY,
  19781. const ValueType newWidth, const ValueType newHeight) noexcept
  19782. {
  19783. x = newX; y = newY; w = newWidth; h = newHeight;
  19784. }
  19785. /** Changes the rectangle's X coordinate */
  19786. void setX (const ValueType newX) noexcept { x = newX; }
  19787. /** Changes the rectangle's Y coordinate */
  19788. void setY (const ValueType newY) noexcept { y = newY; }
  19789. /** Changes the rectangle's width */
  19790. void setWidth (const ValueType newWidth) noexcept { w = newWidth; }
  19791. /** Changes the rectangle's height */
  19792. void setHeight (const ValueType newHeight) noexcept { h = newHeight; }
  19793. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  19794. Rectangle withX (const ValueType newX) const noexcept { return Rectangle (newX, y, w, h); }
  19795. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  19796. Rectangle withY (const ValueType newY) const noexcept { return Rectangle (x, newY, w, h); }
  19797. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  19798. Rectangle withWidth (const ValueType newWidth) const noexcept { return Rectangle (x, y, newWidth, h); }
  19799. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  19800. Rectangle withHeight (const ValueType newHeight) const noexcept { return Rectangle (x, y, w, newHeight); }
  19801. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  19802. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  19803. @see withLeft
  19804. */
  19805. void setLeft (const ValueType newLeft) noexcept
  19806. {
  19807. w = jmax (ValueType(), x + w - newLeft);
  19808. x = newLeft;
  19809. }
  19810. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  19811. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  19812. @see setLeft
  19813. */
  19814. Rectangle withLeft (const ValueType newLeft) const noexcept { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  19815. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  19816. If the y is moved to be below the current bottom edge, the height will be set to zero.
  19817. @see withTop
  19818. */
  19819. void setTop (const ValueType newTop) noexcept
  19820. {
  19821. h = jmax (ValueType(), y + h - newTop);
  19822. y = newTop;
  19823. }
  19824. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  19825. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19826. @see setTop
  19827. */
  19828. Rectangle withTop (const ValueType newTop) const noexcept { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  19829. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  19830. If the new right is below the current X value, the X will be pushed down to match it.
  19831. @see getRight, withRight
  19832. */
  19833. void setRight (const ValueType newRight) noexcept
  19834. {
  19835. x = jmin (x, newRight);
  19836. w = newRight - x;
  19837. }
  19838. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  19839. If the new right edge is below the current left-hand edge, the width will be set to zero.
  19840. @see setRight
  19841. */
  19842. Rectangle withRight (const ValueType newRight) const noexcept { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  19843. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  19844. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  19845. @see getBottom, withBottom
  19846. */
  19847. void setBottom (const ValueType newBottom) noexcept
  19848. {
  19849. y = jmin (y, newBottom);
  19850. h = newBottom - y;
  19851. }
  19852. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  19853. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19854. @see setBottom
  19855. */
  19856. Rectangle withBottom (const ValueType newBottom) const noexcept { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  19857. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  19858. void translate (const ValueType deltaX,
  19859. const ValueType deltaY) noexcept
  19860. {
  19861. x += deltaX;
  19862. y += deltaY;
  19863. }
  19864. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19865. Rectangle translated (const ValueType deltaX,
  19866. const ValueType deltaY) const noexcept
  19867. {
  19868. return Rectangle (x + deltaX, y + deltaY, w, h);
  19869. }
  19870. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19871. Rectangle operator+ (const Point<ValueType>& deltaPosition) const noexcept
  19872. {
  19873. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19874. }
  19875. /** Moves this rectangle by a given amount. */
  19876. Rectangle& operator+= (const Point<ValueType>& deltaPosition) noexcept
  19877. {
  19878. x += deltaPosition.getX(); y += deltaPosition.getY();
  19879. return *this;
  19880. }
  19881. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19882. Rectangle operator- (const Point<ValueType>& deltaPosition) const noexcept
  19883. {
  19884. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19885. }
  19886. /** Moves this rectangle by a given amount. */
  19887. Rectangle& operator-= (const Point<ValueType>& deltaPosition) noexcept
  19888. {
  19889. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19890. return *this;
  19891. }
  19892. /** Expands the rectangle by a given amount.
  19893. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19894. @see expanded, reduce, reduced
  19895. */
  19896. void expand (const ValueType deltaX,
  19897. const ValueType deltaY) noexcept
  19898. {
  19899. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19900. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19901. setBounds (x - deltaX, y - deltaY, nw, nh);
  19902. }
  19903. /** Returns a rectangle that is larger than this one by a given amount.
  19904. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19905. @see expand, reduce, reduced
  19906. */
  19907. Rectangle expanded (const ValueType deltaX,
  19908. const ValueType deltaY) const noexcept
  19909. {
  19910. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19911. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19912. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19913. }
  19914. /** Shrinks the rectangle by a given amount.
  19915. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19916. @see reduced, expand, expanded
  19917. */
  19918. void reduce (const ValueType deltaX,
  19919. const ValueType deltaY) noexcept
  19920. {
  19921. expand (-deltaX, -deltaY);
  19922. }
  19923. /** Returns a rectangle that is smaller than this one by a given amount.
  19924. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19925. @see reduce, expand, expanded
  19926. */
  19927. Rectangle reduced (const ValueType deltaX,
  19928. const ValueType deltaY) const noexcept
  19929. {
  19930. return expanded (-deltaX, -deltaY);
  19931. }
  19932. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19933. by the specified amount and returning the section that was removed.
  19934. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19935. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19936. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19937. that value.
  19938. */
  19939. Rectangle removeFromTop (const ValueType amountToRemove) noexcept
  19940. {
  19941. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19942. y += r.h; h -= r.h;
  19943. return r;
  19944. }
  19945. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19946. by the specified amount and returning the section that was removed.
  19947. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19948. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19949. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19950. that value.
  19951. */
  19952. Rectangle removeFromLeft (const ValueType amountToRemove) noexcept
  19953. {
  19954. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19955. x += r.w; w -= r.w;
  19956. return r;
  19957. }
  19958. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19959. by the specified amount and returning the section that was removed.
  19960. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19961. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19962. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19963. that value.
  19964. */
  19965. Rectangle removeFromRight (ValueType amountToRemove) noexcept
  19966. {
  19967. amountToRemove = jmin (amountToRemove, w);
  19968. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19969. w -= amountToRemove;
  19970. return r;
  19971. }
  19972. /** Removes a strip from the bottom 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, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19976. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19977. that value.
  19978. */
  19979. Rectangle removeFromBottom (ValueType amountToRemove) noexcept
  19980. {
  19981. amountToRemove = jmin (amountToRemove, h);
  19982. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19983. h -= amountToRemove;
  19984. return r;
  19985. }
  19986. /** Returns true if the two rectangles are identical. */
  19987. bool operator== (const Rectangle& other) const noexcept
  19988. {
  19989. return x == other.x && y == other.y
  19990. && w == other.w && h == other.h;
  19991. }
  19992. /** Returns true if the two rectangles are not identical. */
  19993. bool operator!= (const Rectangle& other) const noexcept
  19994. {
  19995. return x != other.x || y != other.y
  19996. || w != other.w || h != other.h;
  19997. }
  19998. /** Returns true if this co-ordinate is inside the rectangle. */
  19999. bool contains (const ValueType xCoord, const ValueType yCoord) const noexcept
  20000. {
  20001. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  20002. }
  20003. /** Returns true if this co-ordinate is inside the rectangle. */
  20004. bool contains (const Point<ValueType>& point) const noexcept
  20005. {
  20006. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  20007. }
  20008. /** Returns true if this other rectangle is completely inside this one. */
  20009. bool contains (const Rectangle& other) const noexcept
  20010. {
  20011. return x <= other.x && y <= other.y
  20012. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  20013. }
  20014. /** Returns the nearest point to the specified point that lies within this rectangle. */
  20015. Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const noexcept
  20016. {
  20017. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  20018. jlimit (y, y + h, point.getY()));
  20019. }
  20020. /** Returns true if any part of another rectangle overlaps this one. */
  20021. bool intersects (const Rectangle& other) const noexcept
  20022. {
  20023. return x + w > other.x
  20024. && y + h > other.y
  20025. && x < other.x + other.w
  20026. && y < other.y + other.h
  20027. && w > ValueType() && h > ValueType();
  20028. }
  20029. /** Returns the region that is the overlap between this and another rectangle.
  20030. If the two rectangles don't overlap, the rectangle returned will be empty.
  20031. */
  20032. Rectangle getIntersection (const Rectangle& other) const noexcept
  20033. {
  20034. const ValueType nx = jmax (x, other.x);
  20035. const ValueType ny = jmax (y, other.y);
  20036. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  20037. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  20038. if (nw >= ValueType() && nh >= ValueType())
  20039. return Rectangle (nx, ny, nw, nh);
  20040. return Rectangle();
  20041. }
  20042. /** Clips a rectangle so that it lies only within this one.
  20043. This is a non-static version of intersectRectangles().
  20044. Returns false if the two regions didn't overlap.
  20045. */
  20046. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const noexcept
  20047. {
  20048. const int maxX = jmax (otherX, x);
  20049. otherW = jmin (otherX + otherW, x + w) - maxX;
  20050. if (otherW > ValueType())
  20051. {
  20052. const int maxY = jmax (otherY, y);
  20053. otherH = jmin (otherY + otherH, y + h) - maxY;
  20054. if (otherH > ValueType())
  20055. {
  20056. otherX = maxX; otherY = maxY;
  20057. return true;
  20058. }
  20059. }
  20060. return false;
  20061. }
  20062. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  20063. If either this or the other rectangle are empty, they will not be counted as
  20064. part of the resulting region.
  20065. */
  20066. Rectangle getUnion (const Rectangle& other) const noexcept
  20067. {
  20068. if (other.isEmpty()) return *this;
  20069. if (isEmpty()) return other;
  20070. const ValueType newX = jmin (x, other.x);
  20071. const ValueType newY = jmin (y, other.y);
  20072. return Rectangle (newX, newY,
  20073. jmax (x + w, other.x + other.w) - newX,
  20074. jmax (y + h, other.y + other.h) - newY);
  20075. }
  20076. /** If this rectangle merged with another one results in a simple rectangle, this
  20077. will set this rectangle to the result, and return true.
  20078. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  20079. or if they form a complex region.
  20080. */
  20081. bool enlargeIfAdjacent (const Rectangle& other) noexcept
  20082. {
  20083. if (x == other.x && getRight() == other.getRight()
  20084. && (other.getBottom() >= y && other.y <= getBottom()))
  20085. {
  20086. const ValueType newY = jmin (y, other.y);
  20087. h = jmax (getBottom(), other.getBottom()) - newY;
  20088. y = newY;
  20089. return true;
  20090. }
  20091. else if (y == other.y && getBottom() == other.getBottom()
  20092. && (other.getRight() >= x && other.x <= getRight()))
  20093. {
  20094. const ValueType newX = jmin (x, other.x);
  20095. w = jmax (getRight(), other.getRight()) - newX;
  20096. x = newX;
  20097. return true;
  20098. }
  20099. return false;
  20100. }
  20101. /** If after removing another rectangle from this one the result is a simple rectangle,
  20102. this will set this object's bounds to be the result, and return true.
  20103. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  20104. or if removing the other one would form a complex region.
  20105. */
  20106. bool reduceIfPartlyContainedIn (const Rectangle& other) noexcept
  20107. {
  20108. int inside = 0;
  20109. const int otherR = other.getRight();
  20110. if (x >= other.x && x < otherR) inside = 1;
  20111. const int otherB = other.getBottom();
  20112. if (y >= other.y && y < otherB) inside |= 2;
  20113. const int r = x + w;
  20114. if (r >= other.x && r < otherR) inside |= 4;
  20115. const int b = y + h;
  20116. if (b >= other.y && b < otherB) inside |= 8;
  20117. switch (inside)
  20118. {
  20119. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  20120. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  20121. case 2 + 4 + 8: w = other.x - x; return true;
  20122. case 1 + 4 + 8: h = other.y - y; return true;
  20123. }
  20124. return false;
  20125. }
  20126. /** Returns the smallest rectangle that can contain the shape created by applying
  20127. a transform to this rectangle.
  20128. This should only be used on floating point rectangles.
  20129. */
  20130. Rectangle transformed (const AffineTransform& transform) const noexcept
  20131. {
  20132. float x1 = x, y1 = y;
  20133. float x2 = x + w, y2 = y;
  20134. float x3 = x, y3 = y + h;
  20135. float x4 = x2, y4 = y3;
  20136. transform.transformPoints (x1, y1, x2, y2);
  20137. transform.transformPoints (x3, y3, x4, y4);
  20138. const float rx = jmin (x1, x2, x3, x4);
  20139. const float ry = jmin (y1, y2, y3, y4);
  20140. return Rectangle (rx, ry,
  20141. jmax (x1, x2, x3, x4) - rx,
  20142. jmax (y1, y2, y3, y4) - ry);
  20143. }
  20144. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  20145. This is only relevent for floating-point rectangles, of course.
  20146. @see toFloat()
  20147. */
  20148. const Rectangle<int> getSmallestIntegerContainer() const noexcept
  20149. {
  20150. const int x1 = (int) std::floor (static_cast<float> (x));
  20151. const int y1 = (int) std::floor (static_cast<float> (y));
  20152. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  20153. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  20154. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  20155. }
  20156. /** Returns the smallest Rectangle that can contain a set of points. */
  20157. static Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) noexcept
  20158. {
  20159. if (numPoints == 0)
  20160. return Rectangle();
  20161. ValueType minX (points[0].getX());
  20162. ValueType maxX (minX);
  20163. ValueType minY (points[0].getY());
  20164. ValueType maxY (minY);
  20165. for (int i = 1; i < numPoints; ++i)
  20166. {
  20167. minX = jmin (minX, points[i].getX());
  20168. maxX = jmax (maxX, points[i].getX());
  20169. minY = jmin (minY, points[i].getY());
  20170. maxY = jmax (maxY, points[i].getY());
  20171. }
  20172. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  20173. }
  20174. /** Casts this rectangle to a Rectangle<float>.
  20175. Obviously this is mainly useful for rectangles that use integer types.
  20176. @see getSmallestIntegerContainer
  20177. */
  20178. const Rectangle<float> toFloat() const noexcept
  20179. {
  20180. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  20181. static_cast<float> (w), static_cast<float> (h));
  20182. }
  20183. /** Static utility to intersect two sets of rectangular co-ordinates.
  20184. Returns false if the two regions didn't overlap.
  20185. @see intersectRectangle
  20186. */
  20187. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  20188. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) noexcept
  20189. {
  20190. const ValueType x = jmax (x1, x2);
  20191. w1 = jmin (x1 + w1, x2 + w2) - x;
  20192. if (w1 > ValueType())
  20193. {
  20194. const ValueType y = jmax (y1, y2);
  20195. h1 = jmin (y1 + h1, y2 + h2) - y;
  20196. if (h1 > ValueType())
  20197. {
  20198. x1 = x; y1 = y;
  20199. return true;
  20200. }
  20201. }
  20202. return false;
  20203. }
  20204. /** Creates a string describing this rectangle.
  20205. The string will be of the form "x y width height", e.g. "100 100 400 200".
  20206. Coupled with the fromString() method, this is very handy for things like
  20207. storing rectangles (particularly component positions) in XML attributes.
  20208. @see fromString
  20209. */
  20210. String toString() const
  20211. {
  20212. String s;
  20213. s.preallocateBytes (32);
  20214. s << x << ' ' << y << ' ' << w << ' ' << h;
  20215. return s;
  20216. }
  20217. /** Parses a string containing a rectangle's details.
  20218. The string should contain 4 integer tokens, in the form "x y width height". They
  20219. can be comma or whitespace separated.
  20220. This method is intended to go with the toString() method, to form an easy way
  20221. of saving/loading rectangles as strings.
  20222. @see toString
  20223. */
  20224. static Rectangle fromString (const String& stringVersion)
  20225. {
  20226. StringArray toks;
  20227. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  20228. return Rectangle (toks[0].trim().getIntValue(),
  20229. toks[1].trim().getIntValue(),
  20230. toks[2].trim().getIntValue(),
  20231. toks[3].trim().getIntValue());
  20232. }
  20233. private:
  20234. friend class RectangleList;
  20235. ValueType x, y, w, h;
  20236. };
  20237. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  20238. /*** End of inlined file: juce_Rectangle.h ***/
  20239. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20240. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20241. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20242. /*** Start of inlined file: juce_Path.h ***/
  20243. #ifndef __JUCE_PATH_JUCEHEADER__
  20244. #define __JUCE_PATH_JUCEHEADER__
  20245. /*** Start of inlined file: juce_Line.h ***/
  20246. #ifndef __JUCE_LINE_JUCEHEADER__
  20247. #define __JUCE_LINE_JUCEHEADER__
  20248. /**
  20249. Represents a line.
  20250. This class contains a bunch of useful methods for various geometric
  20251. tasks.
  20252. The ValueType template parameter should be a primitive type - float or double
  20253. are what it's designed for. Integer types will work in a basic way, but some methods
  20254. that perform mathematical operations may not compile, or they may not produce
  20255. sensible results.
  20256. @see Point, Rectangle, Path, Graphics::drawLine
  20257. */
  20258. template <typename ValueType>
  20259. class Line
  20260. {
  20261. public:
  20262. /** Creates a line, using (0, 0) as its start and end points. */
  20263. Line() noexcept {}
  20264. /** Creates a copy of another line. */
  20265. Line (const Line& other) noexcept
  20266. : start (other.start),
  20267. end (other.end)
  20268. {
  20269. }
  20270. /** Creates a line based on the co-ordinates of its start and end points. */
  20271. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) noexcept
  20272. : start (startX, startY),
  20273. end (endX, endY)
  20274. {
  20275. }
  20276. /** Creates a line from its start and end points. */
  20277. Line (const Point<ValueType>& startPoint,
  20278. const Point<ValueType>& endPoint) noexcept
  20279. : start (startPoint),
  20280. end (endPoint)
  20281. {
  20282. }
  20283. /** Copies a line from another one. */
  20284. Line& operator= (const Line& other) noexcept
  20285. {
  20286. start = other.start;
  20287. end = other.end;
  20288. return *this;
  20289. }
  20290. /** Destructor. */
  20291. ~Line() noexcept {}
  20292. /** Returns the x co-ordinate of the line's start point. */
  20293. inline ValueType getStartX() const noexcept { return start.getX(); }
  20294. /** Returns the y co-ordinate of the line's start point. */
  20295. inline ValueType getStartY() const noexcept { return start.getY(); }
  20296. /** Returns the x co-ordinate of the line's end point. */
  20297. inline ValueType getEndX() const noexcept { return end.getX(); }
  20298. /** Returns the y co-ordinate of the line's end point. */
  20299. inline ValueType getEndY() const noexcept { return end.getY(); }
  20300. /** Returns the line's start point. */
  20301. inline const Point<ValueType>& getStart() const noexcept { return start; }
  20302. /** Returns the line's end point. */
  20303. inline const Point<ValueType>& getEnd() const noexcept { return end; }
  20304. /** Changes this line's start point */
  20305. void setStart (ValueType newStartX, ValueType newStartY) noexcept { start.setXY (newStartX, newStartY); }
  20306. /** Changes this line's end point */
  20307. void setEnd (ValueType newEndX, ValueType newEndY) noexcept { end.setXY (newEndX, newEndY); }
  20308. /** Changes this line's start point */
  20309. void setStart (const Point<ValueType>& newStart) noexcept { start = newStart; }
  20310. /** Changes this line's end point */
  20311. void setEnd (const Point<ValueType>& newEnd) noexcept { end = newEnd; }
  20312. /** Returns a line that is the same as this one, but with the start and end reversed, */
  20313. const Line reversed() const noexcept { return Line (end, start); }
  20314. /** Applies an affine transform to the line's start and end points. */
  20315. void applyTransform (const AffineTransform& transform) noexcept
  20316. {
  20317. start.applyTransform (transform);
  20318. end.applyTransform (transform);
  20319. }
  20320. /** Returns the length of the line. */
  20321. ValueType getLength() const noexcept { return start.getDistanceFrom (end); }
  20322. /** Returns true if the line's start and end x co-ordinates are the same. */
  20323. bool isVertical() const noexcept { return start.getX() == end.getX(); }
  20324. /** Returns true if the line's start and end y co-ordinates are the same. */
  20325. bool isHorizontal() const noexcept { return start.getY() == end.getY(); }
  20326. /** Returns the line's angle.
  20327. This value is the number of radians clockwise from the 3 o'clock direction,
  20328. where the line's start point is considered to be at the centre.
  20329. */
  20330. ValueType getAngle() const noexcept { return start.getAngleToPoint (end); }
  20331. /** Compares two lines. */
  20332. bool operator== (const Line& other) const noexcept { return start == other.start && end == other.end; }
  20333. /** Compares two lines. */
  20334. bool operator!= (const Line& other) const noexcept { return start != other.start || end != other.end; }
  20335. /** Finds the intersection between two lines.
  20336. @param line the other line
  20337. @param intersection the position of the point where the lines meet (or
  20338. where they would meet if they were infinitely long)
  20339. the intersection (if the lines intersect). If the lines
  20340. are parallel, this will just be set to the position
  20341. of one of the line's endpoints.
  20342. @returns true if the line segments intersect; false if they dont. Even if they
  20343. don't intersect, the intersection co-ordinates returned will still
  20344. be valid
  20345. */
  20346. bool intersects (const Line& line, Point<ValueType>& intersection) const noexcept
  20347. {
  20348. return findIntersection (start, end, line.start, line.end, intersection);
  20349. }
  20350. /** Finds the intersection between two lines.
  20351. @param line the line to intersect with
  20352. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  20353. */
  20354. Point<ValueType> getIntersection (const Line& line) const noexcept
  20355. {
  20356. Point<ValueType> p;
  20357. findIntersection (start, end, line.start, line.end, p);
  20358. return p;
  20359. }
  20360. /** Returns the location of the point which is a given distance along this line.
  20361. @param distanceFromStart the distance to move along the line from its
  20362. start point. This value can be negative or longer
  20363. than the line itself
  20364. @see getPointAlongLineProportionally
  20365. */
  20366. Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const noexcept
  20367. {
  20368. return start + (end - start) * (distanceFromStart / getLength());
  20369. }
  20370. /** Returns a point which is a certain distance along and to the side of this line.
  20371. This effectively moves a given distance along the line, then another distance
  20372. perpendicularly to this, and returns the resulting position.
  20373. @param distanceFromStart the distance to move along the line from its
  20374. start point. This value can be negative or longer
  20375. than the line itself
  20376. @param perpendicularDistance how far to move sideways from the line. If you're
  20377. looking along the line from its start towards its
  20378. end, then a positive value here will move to the
  20379. right, negative value move to the left.
  20380. */
  20381. Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  20382. ValueType perpendicularDistance) const noexcept
  20383. {
  20384. const Point<ValueType> delta (end - start);
  20385. const double length = juce_hypot ((double) delta.getX(),
  20386. (double) delta.getY());
  20387. if (length <= 0)
  20388. return start;
  20389. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  20390. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  20391. }
  20392. /** Returns the location of the point which is a given distance along this line
  20393. proportional to the line's length.
  20394. @param proportionOfLength the distance to move along the line from its
  20395. start point, in multiples of the line's length.
  20396. So a value of 0.0 will return the line's start point
  20397. and a value of 1.0 will return its end point. (This value
  20398. can be negative or greater than 1.0).
  20399. @see getPointAlongLine
  20400. */
  20401. Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const noexcept
  20402. {
  20403. return start + (end - start) * proportionOfLength;
  20404. }
  20405. /** Returns the smallest distance between this line segment and a given point.
  20406. So if the point is close to the line, this will return the perpendicular
  20407. distance from the line; if the point is a long way beyond one of the line's
  20408. end-point's, it'll return the straight-line distance to the nearest end-point.
  20409. pointOnLine receives the position of the point that is found.
  20410. @returns the point's distance from the line
  20411. @see getPositionAlongLineOfNearestPoint
  20412. */
  20413. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  20414. Point<ValueType>& pointOnLine) const noexcept
  20415. {
  20416. const Point<ValueType> delta (end - start);
  20417. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  20418. if (length > 0)
  20419. {
  20420. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  20421. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  20422. if (prop >= 0 && prop <= 1.0)
  20423. {
  20424. pointOnLine = start + delta * (ValueType) prop;
  20425. return targetPoint.getDistanceFrom (pointOnLine);
  20426. }
  20427. }
  20428. const float fromStart = targetPoint.getDistanceFrom (start);
  20429. const float fromEnd = targetPoint.getDistanceFrom (end);
  20430. if (fromStart < fromEnd)
  20431. {
  20432. pointOnLine = start;
  20433. return fromStart;
  20434. }
  20435. else
  20436. {
  20437. pointOnLine = end;
  20438. return fromEnd;
  20439. }
  20440. }
  20441. /** Finds the point on this line which is nearest to a given point, and
  20442. returns its position as a proportional position along the line.
  20443. @returns a value 0 to 1.0 which is the distance along this line from the
  20444. line's start to the point which is nearest to the point passed-in. To
  20445. turn this number into a position, use getPointAlongLineProportionally().
  20446. @see getDistanceFromPoint, getPointAlongLineProportionally
  20447. */
  20448. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const noexcept
  20449. {
  20450. const Point<ValueType> delta (end - start);
  20451. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  20452. return length <= 0 ? 0
  20453. : jlimit ((ValueType) 0, (ValueType) 1,
  20454. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  20455. + (point.getY() - start.getY()) * delta.getY()) / length));
  20456. }
  20457. /** Finds the point on this line which is nearest to a given point.
  20458. @see getDistanceFromPoint, findNearestProportionalPositionTo
  20459. */
  20460. Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const noexcept
  20461. {
  20462. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  20463. }
  20464. /** Returns true if the given point lies above this line.
  20465. The return value is true if the point's y coordinate is less than the y
  20466. coordinate of this line at the given x (assuming the line extends infinitely
  20467. in both directions).
  20468. */
  20469. bool isPointAbove (const Point<ValueType>& point) const noexcept
  20470. {
  20471. return start.getX() != end.getX()
  20472. && point.getY() < ((end.getY() - start.getY())
  20473. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  20474. }
  20475. /** Returns a shortened copy of this line.
  20476. This will chop off part of the start of this line by a certain amount, (leaving the
  20477. end-point the same), and return the new line.
  20478. */
  20479. Line withShortenedStart (ValueType distanceToShortenBy) const noexcept
  20480. {
  20481. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  20482. }
  20483. /** Returns a shortened copy of this line.
  20484. This will chop off part of the end of this line by a certain amount, (leaving the
  20485. start-point the same), and return the new line.
  20486. */
  20487. Line withShortenedEnd (ValueType distanceToShortenBy) const noexcept
  20488. {
  20489. const ValueType length = getLength();
  20490. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  20491. }
  20492. private:
  20493. Point<ValueType> start, end;
  20494. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  20495. const Point<ValueType>& p3, const Point<ValueType>& p4,
  20496. Point<ValueType>& intersection) noexcept
  20497. {
  20498. if (p2 == p3)
  20499. {
  20500. intersection = p2;
  20501. return true;
  20502. }
  20503. const Point<ValueType> d1 (p2 - p1);
  20504. const Point<ValueType> d2 (p4 - p3);
  20505. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  20506. if (divisor == 0)
  20507. {
  20508. if (! (d1.isOrigin() || d2.isOrigin()))
  20509. {
  20510. if (d1.getY() == 0 && d2.getY() != 0)
  20511. {
  20512. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  20513. intersection = p1.withX (p3.getX() + along * d2.getX());
  20514. return along >= 0 && along <= (ValueType) 1;
  20515. }
  20516. else if (d2.getY() == 0 && d1.getY() != 0)
  20517. {
  20518. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  20519. intersection = p3.withX (p1.getX() + along * d1.getX());
  20520. return along >= 0 && along <= (ValueType) 1;
  20521. }
  20522. else if (d1.getX() == 0 && d2.getX() != 0)
  20523. {
  20524. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  20525. intersection = p1.withY (p3.getY() + along * d2.getY());
  20526. return along >= 0 && along <= (ValueType) 1;
  20527. }
  20528. else if (d2.getX() == 0 && d1.getX() != 0)
  20529. {
  20530. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  20531. intersection = p3.withY (p1.getY() + along * d1.getY());
  20532. return along >= 0 && along <= (ValueType) 1;
  20533. }
  20534. }
  20535. intersection = (p2 + p3) / (ValueType) 2;
  20536. return false;
  20537. }
  20538. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  20539. intersection = p1 + d1 * along1;
  20540. if (along1 < 0 || along1 > (ValueType) 1)
  20541. return false;
  20542. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  20543. return along2 >= 0 && along2 <= (ValueType) 1;
  20544. }
  20545. };
  20546. #endif // __JUCE_LINE_JUCEHEADER__
  20547. /*** End of inlined file: juce_Line.h ***/
  20548. /*** Start of inlined file: juce_Justification.h ***/
  20549. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  20550. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  20551. /**
  20552. Represents a type of justification to be used when positioning graphical items.
  20553. e.g. it indicates whether something should be placed top-left, top-right,
  20554. centred, etc.
  20555. It is used in various places wherever this kind of information is needed.
  20556. */
  20557. class JUCE_API Justification
  20558. {
  20559. public:
  20560. /** Creates a Justification object using a combination of flags. */
  20561. inline Justification (int flags_) noexcept : flags (flags_) {}
  20562. /** Creates a copy of another Justification object. */
  20563. Justification (const Justification& other) noexcept;
  20564. /** Copies another Justification object. */
  20565. Justification& operator= (const Justification& other) noexcept;
  20566. bool operator== (const Justification& other) const noexcept { return flags == other.flags; }
  20567. bool operator!= (const Justification& other) const noexcept { return flags != other.flags; }
  20568. /** Returns the raw flags that are set for this Justification object. */
  20569. inline int getFlags() const noexcept { return flags; }
  20570. /** Tests a set of flags for this object.
  20571. @returns true if any of the flags passed in are set on this object.
  20572. */
  20573. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  20574. /** Returns just the flags from this object that deal with vertical layout. */
  20575. int getOnlyVerticalFlags() const noexcept;
  20576. /** Returns just the flags from this object that deal with horizontal layout. */
  20577. int getOnlyHorizontalFlags() const noexcept;
  20578. /** Adjusts the position of a rectangle to fit it into a space.
  20579. The (x, y) position of the rectangle will be updated to position it inside the
  20580. given space according to the justification flags.
  20581. */
  20582. template <typename ValueType>
  20583. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  20584. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const noexcept
  20585. {
  20586. x = spaceX;
  20587. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  20588. else if ((flags & right) != 0) x += spaceW - w;
  20589. y = spaceY;
  20590. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  20591. else if ((flags & bottom) != 0) y += spaceH - h;
  20592. }
  20593. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  20594. */
  20595. template <typename ValueType>
  20596. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  20597. const Rectangle<ValueType>& targetSpace) const noexcept
  20598. {
  20599. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  20600. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  20601. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  20602. return areaToAdjust.withPosition (x, y);
  20603. }
  20604. /** Flag values that can be combined and used in the constructor. */
  20605. enum
  20606. {
  20607. /** Indicates that the item should be aligned against the left edge of the available space. */
  20608. left = 1,
  20609. /** Indicates that the item should be aligned against the right edge of the available space. */
  20610. right = 2,
  20611. /** Indicates that the item should be placed in the centre between the left and right
  20612. sides of the available space. */
  20613. horizontallyCentred = 4,
  20614. /** Indicates that the item should be aligned against the top edge of the available space. */
  20615. top = 8,
  20616. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  20617. bottom = 16,
  20618. /** Indicates that the item should be placed in the centre between the top and bottom
  20619. sides of the available space. */
  20620. verticallyCentred = 32,
  20621. /** Indicates that lines of text should be spread out to fill the maximum width
  20622. available, so that both margins are aligned vertically.
  20623. */
  20624. horizontallyJustified = 64,
  20625. /** Indicates that the item should be centred vertically and horizontally.
  20626. This is equivalent to (horizontallyCentred | verticallyCentred)
  20627. */
  20628. centred = 36,
  20629. /** Indicates that the item should be centred vertically but placed on the left hand side.
  20630. This is equivalent to (left | verticallyCentred)
  20631. */
  20632. centredLeft = 33,
  20633. /** Indicates that the item should be centred vertically but placed on the right hand side.
  20634. This is equivalent to (right | verticallyCentred)
  20635. */
  20636. centredRight = 34,
  20637. /** Indicates that the item should be centred horizontally and placed at the top.
  20638. This is equivalent to (horizontallyCentred | top)
  20639. */
  20640. centredTop = 12,
  20641. /** Indicates that the item should be centred horizontally and placed at the bottom.
  20642. This is equivalent to (horizontallyCentred | bottom)
  20643. */
  20644. centredBottom = 20,
  20645. /** Indicates that the item should be placed in the top-left corner.
  20646. This is equivalent to (left | top)
  20647. */
  20648. topLeft = 9,
  20649. /** Indicates that the item should be placed in the top-right corner.
  20650. This is equivalent to (right | top)
  20651. */
  20652. topRight = 10,
  20653. /** Indicates that the item should be placed in the bottom-left corner.
  20654. This is equivalent to (left | bottom)
  20655. */
  20656. bottomLeft = 17,
  20657. /** Indicates that the item should be placed in the bottom-left corner.
  20658. This is equivalent to (right | bottom)
  20659. */
  20660. bottomRight = 18
  20661. };
  20662. private:
  20663. int flags;
  20664. };
  20665. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  20666. /*** End of inlined file: juce_Justification.h ***/
  20667. class Image;
  20668. class InputStream;
  20669. class OutputStream;
  20670. /**
  20671. A path is a sequence of lines and curves that may either form a closed shape
  20672. or be open-ended.
  20673. To use a path, you can create an empty one, then add lines and curves to it
  20674. to create shapes, then it can be rendered by a Graphics context or used
  20675. for geometric operations.
  20676. e.g. @code
  20677. Path myPath;
  20678. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  20679. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  20680. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  20681. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  20682. // add an ellipse as well, which will form a second sub-path within the path..
  20683. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  20684. // double the width of the whole thing..
  20685. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  20686. // and draw it to a graphics context with a 5-pixel thick outline.
  20687. g.strokePath (myPath, PathStrokeType (5.0f));
  20688. @endcode
  20689. A path object can actually contain multiple sub-paths, which may themselves
  20690. be open or closed.
  20691. @see PathFlatteningIterator, PathStrokeType, Graphics
  20692. */
  20693. class JUCE_API Path
  20694. {
  20695. public:
  20696. /** Creates an empty path. */
  20697. Path();
  20698. /** Creates a copy of another path. */
  20699. Path (const Path& other);
  20700. /** Destructor. */
  20701. ~Path();
  20702. /** Copies this path from another one. */
  20703. Path& operator= (const Path& other);
  20704. bool operator== (const Path& other) const noexcept;
  20705. bool operator!= (const Path& other) const noexcept;
  20706. /** Returns true if the path doesn't contain any lines or curves. */
  20707. bool isEmpty() const noexcept;
  20708. /** Returns the smallest rectangle that contains all points within the path.
  20709. */
  20710. Rectangle<float> getBounds() const noexcept;
  20711. /** Returns the smallest rectangle that contains all points within the path
  20712. after it's been transformed with the given tranasform matrix.
  20713. */
  20714. Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const noexcept;
  20715. /** Checks whether a point lies within the path.
  20716. This is only relevent for closed paths (see closeSubPath()), and
  20717. may produce false results if used on a path which has open sub-paths.
  20718. The path's winding rule is taken into account by this method.
  20719. The tolerance parameter is the maximum error allowed when flattening the path,
  20720. so this method could return a false positive when your point is up to this distance
  20721. outside the path's boundary.
  20722. @see closeSubPath, setUsingNonZeroWinding
  20723. */
  20724. bool contains (float x, float y,
  20725. float tolerance = 1.0f) const;
  20726. /** Checks whether a point lies within the path.
  20727. This is only relevent for closed paths (see closeSubPath()), and
  20728. may produce false results if used on a path which has open sub-paths.
  20729. The path's winding rule is taken into account by this method.
  20730. The tolerance parameter is the maximum error allowed when flattening the path,
  20731. so this method could return a false positive when your point is up to this distance
  20732. outside the path's boundary.
  20733. @see closeSubPath, setUsingNonZeroWinding
  20734. */
  20735. bool contains (const Point<float>& point,
  20736. float tolerance = 1.0f) const;
  20737. /** Checks whether a line crosses the path.
  20738. This will return positive if the line crosses any of the paths constituent
  20739. lines or curves. It doesn't take into account whether the line is inside
  20740. or outside the path, or whether the path is open or closed.
  20741. The tolerance parameter is the maximum error allowed when flattening the path,
  20742. so this method could return a false positive when your point is up to this distance
  20743. outside the path's boundary.
  20744. */
  20745. bool intersectsLine (const Line<float>& line,
  20746. float tolerance = 1.0f);
  20747. /** Cuts off parts of a line to keep the parts that are either inside or
  20748. outside this path.
  20749. Note that this isn't smart enough to cope with situations where the
  20750. line would need to be cut into multiple pieces to correctly clip against
  20751. a re-entrant shape.
  20752. @param line the line to clip
  20753. @param keepSectionOutsidePath if true, it's the section outside the path
  20754. that will be kept; if false its the section inside
  20755. the path
  20756. */
  20757. Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  20758. /** Returns the length of the path.
  20759. @see getPointAlongPath
  20760. */
  20761. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  20762. /** Returns a point that is the specified distance along the path.
  20763. If the distance is greater than the total length of the path, this will return the
  20764. end point.
  20765. @see getLength
  20766. */
  20767. Point<float> getPointAlongPath (float distanceFromStart,
  20768. const AffineTransform& transform = AffineTransform::identity) const;
  20769. /** Finds the point along the path which is nearest to a given position.
  20770. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  20771. of the path.
  20772. */
  20773. float getNearestPoint (const Point<float>& targetPoint,
  20774. Point<float>& pointOnPath,
  20775. const AffineTransform& transform = AffineTransform::identity) const;
  20776. /** Removes all lines and curves, resetting the path completely. */
  20777. void clear() noexcept;
  20778. /** Begins a new subpath with a given starting position.
  20779. This will move the path's current position to the co-ordinates passed in and
  20780. make it ready to draw lines or curves starting from this position.
  20781. After adding whatever lines and curves are needed, you can either
  20782. close the current sub-path using closeSubPath() or call startNewSubPath()
  20783. to move to a new sub-path, leaving the old one open-ended.
  20784. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20785. */
  20786. void startNewSubPath (float startX, float startY);
  20787. /** Begins a new subpath with a given starting position.
  20788. This will move the path's current position to the co-ordinates passed in and
  20789. make it ready to draw lines or curves starting from this position.
  20790. After adding whatever lines and curves are needed, you can either
  20791. close the current sub-path using closeSubPath() or call startNewSubPath()
  20792. to move to a new sub-path, leaving the old one open-ended.
  20793. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20794. */
  20795. void startNewSubPath (const Point<float>& start);
  20796. /** Closes a the current sub-path with a line back to its start-point.
  20797. When creating a closed shape such as a triangle, don't use 3 lineTo()
  20798. calls - instead use two lineTo() calls, followed by a closeSubPath()
  20799. to join the final point back to the start.
  20800. This ensures that closes shapes are recognised as such, and this is
  20801. important for tasks like drawing strokes, which needs to know whether to
  20802. draw end-caps or not.
  20803. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  20804. */
  20805. void closeSubPath();
  20806. /** Adds a line from the shape's last position to a new end-point.
  20807. This will connect the end-point of the last line or curve that was added
  20808. to a new point, using a straight line.
  20809. See the class description for an example of how to add lines and curves to a path.
  20810. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20811. */
  20812. void lineTo (float endX, float endY);
  20813. /** Adds a line from the shape's last position to a new end-point.
  20814. This will connect the end-point of the last line or curve that was added
  20815. to a new point, using a straight line.
  20816. See the class description for an example of how to add lines and curves to a path.
  20817. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20818. */
  20819. void lineTo (const Point<float>& end);
  20820. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20821. This will connect the end-point of the last line or curve that was added
  20822. to a new point, using a quadratic spline with one control-point.
  20823. See the class description for an example of how to add lines and curves to a path.
  20824. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20825. */
  20826. void quadraticTo (float controlPointX,
  20827. float controlPointY,
  20828. float endPointX,
  20829. float endPointY);
  20830. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20831. This will connect the end-point of the last line or curve that was added
  20832. to a new point, using a quadratic spline with one control-point.
  20833. See the class description for an example of how to add lines and curves to a path.
  20834. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20835. */
  20836. void quadraticTo (const Point<float>& controlPoint,
  20837. const Point<float>& endPoint);
  20838. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20839. This will connect the end-point of the last line or curve that was added
  20840. to a new point, using a cubic spline with two control-points.
  20841. See the class description for an example of how to add lines and curves to a path.
  20842. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20843. */
  20844. void cubicTo (float controlPoint1X,
  20845. float controlPoint1Y,
  20846. float controlPoint2X,
  20847. float controlPoint2Y,
  20848. float endPointX,
  20849. float endPointY);
  20850. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20851. This will connect the end-point of the last line or curve that was added
  20852. to a new point, using a cubic spline with two control-points.
  20853. See the class description for an example of how to add lines and curves to a path.
  20854. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20855. */
  20856. void cubicTo (const Point<float>& controlPoint1,
  20857. const Point<float>& controlPoint2,
  20858. const Point<float>& endPoint);
  20859. /** Returns the last point that was added to the path by one of the drawing methods.
  20860. */
  20861. Point<float> getCurrentPosition() const;
  20862. /** Adds a rectangle to the path.
  20863. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20864. @see addRoundedRectangle, addTriangle
  20865. */
  20866. void addRectangle (float x, float y, float width, float height);
  20867. /** Adds a rectangle to the path.
  20868. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20869. @see addRoundedRectangle, addTriangle
  20870. */
  20871. template <typename ValueType>
  20872. void addRectangle (const Rectangle<ValueType>& rectangle)
  20873. {
  20874. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20875. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  20876. }
  20877. /** Adds a rectangle with rounded corners to the path.
  20878. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20879. @see addRectangle, addTriangle
  20880. */
  20881. void addRoundedRectangle (float x, float y, float width, float height,
  20882. float cornerSize);
  20883. /** Adds a rectangle with rounded corners to the path.
  20884. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20885. @see addRectangle, addTriangle
  20886. */
  20887. void addRoundedRectangle (float x, float y, float width, float height,
  20888. float cornerSizeX,
  20889. float cornerSizeY);
  20890. /** Adds a rectangle with rounded corners to the path.
  20891. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20892. @see addRectangle, addTriangle
  20893. */
  20894. template <typename ValueType>
  20895. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  20896. {
  20897. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20898. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  20899. cornerSizeX, cornerSizeY);
  20900. }
  20901. /** Adds a rectangle with rounded corners to the path.
  20902. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20903. @see addRectangle, addTriangle
  20904. */
  20905. template <typename ValueType>
  20906. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  20907. {
  20908. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  20909. }
  20910. /** Adds a triangle to the path.
  20911. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  20912. Note that whether the vertices are specified in clockwise or anticlockwise
  20913. order will affect how the triangle is filled when it overlaps other
  20914. shapes (the winding order setting will affect this of course).
  20915. */
  20916. void addTriangle (float x1, float y1,
  20917. float x2, float y2,
  20918. float x3, float y3);
  20919. /** Adds a quadrilateral to the path.
  20920. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  20921. Note that whether the vertices are specified in clockwise or anticlockwise
  20922. order will affect how the quad is filled when it overlaps other
  20923. shapes (the winding order setting will affect this of course).
  20924. */
  20925. void addQuadrilateral (float x1, float y1,
  20926. float x2, float y2,
  20927. float x3, float y3,
  20928. float x4, float y4);
  20929. /** Adds an ellipse to the path.
  20930. The shape is added as a new sub-path. (Any currently open paths will be left open).
  20931. @see addArc
  20932. */
  20933. void addEllipse (float x, float y, float width, float height);
  20934. /** Adds an elliptical arc to the current path.
  20935. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20936. or anti-clockwise according to whether the end angle is greater than the start. This means
  20937. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20938. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20939. @param y the top edge of the rectangle in which the elliptical outline fits
  20940. @param width the width of the rectangle in which the elliptical outline fits
  20941. @param height the height of the rectangle in which the elliptical outline fits
  20942. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20943. top-centre of the ellipse)
  20944. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20945. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20946. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20947. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20948. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20949. it will be added to the current sub-path, continuing from the current postition
  20950. @see addCentredArc, arcTo, addPieSegment, addEllipse
  20951. */
  20952. void addArc (float x, float y, float width, float height,
  20953. float fromRadians,
  20954. float toRadians,
  20955. bool startAsNewSubPath = false);
  20956. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  20957. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20958. or anti-clockwise according to whether the end angle is greater than the start. This means
  20959. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20960. @param centreX the centre x of the ellipse
  20961. @param centreY the centre y of the ellipse
  20962. @param radiusX the horizontal radius of the ellipse
  20963. @param radiusY the vertical radius of the ellipse
  20964. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  20965. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20966. top-centre of the ellipse)
  20967. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20968. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20969. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20970. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20971. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20972. it will be added to the current sub-path, continuing from the current postition
  20973. @see addArc, arcTo
  20974. */
  20975. void addCentredArc (float centreX, float centreY,
  20976. float radiusX, float radiusY,
  20977. float rotationOfEllipse,
  20978. float fromRadians,
  20979. float toRadians,
  20980. bool startAsNewSubPath = false);
  20981. /** Adds a "pie-chart" shape to the path.
  20982. The shape is added as a new sub-path. (Any currently open paths will be
  20983. left open).
  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 x the left-hand edge of the rectangle in which the elliptical outline fits
  20988. @param y the top edge of the rectangle in which the elliptical outline fits
  20989. @param width the width of the rectangle in which the elliptical outline fits
  20990. @param height the height of the rectangle in which the elliptical outline fits
  20991. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20992. top-centre of the ellipse)
  20993. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20994. top-centre of the ellipse)
  20995. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  20996. ellipse at its centre, where this value indicates the inner ellipse's size with
  20997. respect to the outer one.
  20998. @see addArc
  20999. */
  21000. void addPieSegment (float x, float y,
  21001. float width, float height,
  21002. float fromRadians,
  21003. float toRadians,
  21004. float innerCircleProportionalSize);
  21005. /** Adds a line with a specified thickness.
  21006. The line is added as a new closed sub-path. (Any currently open paths will be
  21007. left open).
  21008. @see addArrow
  21009. */
  21010. void addLineSegment (const Line<float>& line, float lineThickness);
  21011. /** Adds a line with an arrowhead on the end.
  21012. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  21013. @see PathStrokeType::createStrokeWithArrowheads
  21014. */
  21015. void addArrow (const Line<float>& line,
  21016. float lineThickness,
  21017. float arrowheadWidth,
  21018. float arrowheadLength);
  21019. /** Adds a polygon shape to the path.
  21020. @see addStar
  21021. */
  21022. void addPolygon (const Point<float>& centre,
  21023. int numberOfSides,
  21024. float radius,
  21025. float startAngle = 0.0f);
  21026. /** Adds a star shape to the path.
  21027. @see addPolygon
  21028. */
  21029. void addStar (const Point<float>& centre,
  21030. int numberOfPoints,
  21031. float innerRadius,
  21032. float outerRadius,
  21033. float startAngle = 0.0f);
  21034. /** Adds a speech-bubble shape to the path.
  21035. @param bodyX the left of the main body area of the bubble
  21036. @param bodyY the top of the main body area of the bubble
  21037. @param bodyW the width of the main body area of the bubble
  21038. @param bodyH the height of the main body area of the bubble
  21039. @param cornerSize the amount by which to round off the corners of the main body rectangle
  21040. @param arrowTipX the x position that the tip of the arrow should connect to
  21041. @param arrowTipY the y position that the tip of the arrow should connect to
  21042. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  21043. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  21044. arrow's base should be - this is a proportional distance between 0 and 1.0
  21045. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  21046. */
  21047. void addBubble (float bodyX, float bodyY,
  21048. float bodyW, float bodyH,
  21049. float cornerSize,
  21050. float arrowTipX,
  21051. float arrowTipY,
  21052. int whichSide,
  21053. float arrowPositionAlongEdgeProportional,
  21054. float arrowWidth);
  21055. /** Adds another path to this one.
  21056. The new path is added as a new sub-path. (Any currently open paths in this
  21057. path will be left open).
  21058. @param pathToAppend the path to add
  21059. */
  21060. void addPath (const Path& pathToAppend);
  21061. /** Adds another path to this one, transforming it on the way in.
  21062. The new path is added as a new sub-path, its points being transformed by the given
  21063. matrix before being added.
  21064. @param pathToAppend the path to add
  21065. @param transformToApply an optional transform to apply to the incoming vertices
  21066. */
  21067. void addPath (const Path& pathToAppend,
  21068. const AffineTransform& transformToApply);
  21069. /** Swaps the contents of this path with another one.
  21070. The internal data of the two paths is swapped over, so this is much faster than
  21071. copying it to a temp variable and back.
  21072. */
  21073. void swapWithPath (Path& other) noexcept;
  21074. /** Applies a 2D transform to all the vertices in the path.
  21075. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  21076. */
  21077. void applyTransform (const AffineTransform& transform) noexcept;
  21078. /** Rescales this path to make it fit neatly into a given space.
  21079. This is effectively a quick way of calling
  21080. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  21081. @param x the x position of the rectangle to fit the path inside
  21082. @param y the y position of the rectangle to fit the path inside
  21083. @param width the width of the rectangle to fit the path inside
  21084. @param height the height of the rectangle to fit the path inside
  21085. @param preserveProportions if true, it will fit the path into the space without altering its
  21086. horizontal/vertical scale ratio; if false, it will distort the
  21087. path to fill the specified ratio both horizontally and vertically
  21088. @see applyTransform, getTransformToScaleToFit
  21089. */
  21090. void scaleToFit (float x, float y, float width, float height,
  21091. bool preserveProportions) noexcept;
  21092. /** Returns a transform that can be used to rescale the path to fit into a given space.
  21093. @param x the x position of the rectangle to fit the path inside
  21094. @param y the y position of the rectangle to fit the path inside
  21095. @param width the width of the rectangle to fit the path inside
  21096. @param height the height of the rectangle to fit the path inside
  21097. @param preserveProportions if true, it will fit the path into the space without altering its
  21098. horizontal/vertical scale ratio; if false, it will distort the
  21099. path to fill the specified ratio both horizontally and vertically
  21100. @param justificationType if the proportions are preseved, the resultant path may be smaller
  21101. than the available rectangle, so this describes how it should be
  21102. positioned within the space.
  21103. @returns an appropriate transformation
  21104. @see applyTransform, scaleToFit
  21105. */
  21106. AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  21107. bool preserveProportions,
  21108. const Justification& justificationType = Justification::centred) const;
  21109. /** Creates a version of this path where all sharp corners have been replaced by curves.
  21110. Wherever two lines meet at an angle, this will replace the corner with a curve
  21111. of the given radius.
  21112. */
  21113. Path createPathWithRoundedCorners (float cornerRadius) const;
  21114. /** Changes the winding-rule to be used when filling the path.
  21115. If set to true (which is the default), then the path uses a non-zero-winding rule
  21116. to determine which points are inside the path. If set to false, it uses an
  21117. alternate-winding rule.
  21118. The winding-rule comes into play when areas of the shape overlap other
  21119. areas, and determines whether the overlapping regions are considered to be
  21120. inside or outside.
  21121. Changing this value just sets a flag - it doesn't affect the contents of the
  21122. path.
  21123. @see isUsingNonZeroWinding
  21124. */
  21125. void setUsingNonZeroWinding (bool isNonZeroWinding) noexcept;
  21126. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  21127. The default for a new path is true.
  21128. @see setUsingNonZeroWinding
  21129. */
  21130. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  21131. /** Iterates the lines and curves that a path contains.
  21132. @see Path, PathFlatteningIterator
  21133. */
  21134. class JUCE_API Iterator
  21135. {
  21136. public:
  21137. Iterator (const Path& path);
  21138. ~Iterator();
  21139. /** Moves onto the next element in the path.
  21140. If this returns false, there are no more elements. If it returns true,
  21141. the elementType variable will be set to the type of the current element,
  21142. and some of the x and y variables will be filled in with values.
  21143. */
  21144. bool next();
  21145. enum PathElementType
  21146. {
  21147. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  21148. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  21149. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  21150. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  21151. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  21152. };
  21153. PathElementType elementType;
  21154. float x1, y1, x2, y2, x3, y3;
  21155. private:
  21156. const Path& path;
  21157. size_t index;
  21158. JUCE_DECLARE_NON_COPYABLE (Iterator);
  21159. };
  21160. /** Loads a stored path from a data stream.
  21161. The data in the stream must have been written using writePathToStream().
  21162. Note that this will append the stored path to whatever is currently in
  21163. this path, so you might need to call clear() beforehand.
  21164. @see loadPathFromData, writePathToStream
  21165. */
  21166. void loadPathFromStream (InputStream& source);
  21167. /** Loads a stored path from a block of data.
  21168. This is similar to loadPathFromStream(), but just reads from a block
  21169. of data. Useful if you're including stored shapes in your code as a
  21170. block of static data.
  21171. @see loadPathFromStream, writePathToStream
  21172. */
  21173. void loadPathFromData (const void* data, int numberOfBytes);
  21174. /** Stores the path by writing it out to a stream.
  21175. After writing out a path, you can reload it using loadPathFromStream().
  21176. @see loadPathFromStream, loadPathFromData
  21177. */
  21178. void writePathToStream (OutputStream& destination) const;
  21179. /** Creates a string containing a textual representation of this path.
  21180. @see restoreFromString
  21181. */
  21182. String toString() const;
  21183. /** Restores this path from a string that was created with the toString() method.
  21184. @see toString()
  21185. */
  21186. void restoreFromString (const String& stringVersion);
  21187. private:
  21188. friend class PathFlatteningIterator;
  21189. friend class Path::Iterator;
  21190. ArrayAllocationBase <float, DummyCriticalSection> data;
  21191. size_t numElements;
  21192. float pathXMin, pathXMax, pathYMin, pathYMax;
  21193. bool useNonZeroWinding;
  21194. static const float lineMarker;
  21195. static const float moveMarker;
  21196. static const float quadMarker;
  21197. static const float cubicMarker;
  21198. static const float closeSubPathMarker;
  21199. JUCE_LEAK_DETECTOR (Path);
  21200. };
  21201. #endif // __JUCE_PATH_JUCEHEADER__
  21202. /*** End of inlined file: juce_Path.h ***/
  21203. /**
  21204. Describes a type of stroke used to render a solid outline along a path.
  21205. A PathStrokeType object can be used directly to create the shape of an outline
  21206. around a path, and is used by Graphics::strokePath to specify the type of
  21207. stroke to draw.
  21208. @see Path, Graphics::strokePath
  21209. */
  21210. class JUCE_API PathStrokeType
  21211. {
  21212. public:
  21213. /** The type of shape to use for the corners between two adjacent line segments. */
  21214. enum JointStyle
  21215. {
  21216. mitered, /**< Indicates that corners should be drawn with sharp joints.
  21217. Note that for angles that curve back on themselves, drawing a
  21218. mitre could require extending the point too far away from the
  21219. path, so a mitre limit is imposed and any corners that exceed it
  21220. are drawn as bevelled instead. */
  21221. curved, /**< Indicates that corners should be drawn as rounded-off. */
  21222. beveled /**< Indicates that corners should be drawn with a line flattening their
  21223. outside edge. */
  21224. };
  21225. /** The type shape to use for the ends of lines. */
  21226. enum EndCapStyle
  21227. {
  21228. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  21229. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  21230. the thickness of the stroke. */
  21231. rounded /**< Ends of lines are rounded-off with a circular shape. */
  21232. };
  21233. /** Creates a stroke type.
  21234. @param strokeThickness the width of the line to use
  21235. @param jointStyle the type of joints to use for corners
  21236. @param endStyle the type of end-caps to use for the ends of open paths.
  21237. */
  21238. PathStrokeType (float strokeThickness,
  21239. JointStyle jointStyle = mitered,
  21240. EndCapStyle endStyle = butt) noexcept;
  21241. /** Createes a copy of another stroke type. */
  21242. PathStrokeType (const PathStrokeType& other) noexcept;
  21243. /** Copies another stroke onto this one. */
  21244. PathStrokeType& operator= (const PathStrokeType& other) noexcept;
  21245. /** Destructor. */
  21246. ~PathStrokeType() noexcept;
  21247. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21248. @param destPath the resultant stroked outline shape will be copied into this path.
  21249. Note that it's ok for the source and destination Paths to be
  21250. the same object, so you can easily turn a path into a stroked version
  21251. of itself.
  21252. @param sourcePath the path to use as the source
  21253. @param transform an optional transform to apply to the points from the source path
  21254. as they are being used
  21255. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21256. a higher resolution, which improves the quality if you'll later want
  21257. to enlarge the stroked path. So for example, if you're planning on drawing
  21258. the stroke at 3x the size that you're creating it, you should set this to 3.
  21259. @see createDashedStroke
  21260. */
  21261. void createStrokedPath (Path& destPath,
  21262. const Path& sourcePath,
  21263. const AffineTransform& transform = AffineTransform::identity,
  21264. float extraAccuracy = 1.0f) const;
  21265. /** Applies this stroke type to a path, creating a dashed line.
  21266. This is similar to createStrokedPath, but uses the array passed in to
  21267. break the stroke up into a series of dashes.
  21268. @param destPath the resultant stroked outline shape will be copied into this path.
  21269. Note that it's ok for the source and destination Paths to be
  21270. the same object, so you can easily turn a path into a stroked version
  21271. of itself.
  21272. @param sourcePath the path to use as the source
  21273. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  21274. a line of length 2, then skip a length of 3, then add a line of length 4,
  21275. skip 5, and keep repeating this pattern.
  21276. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  21277. an even number, otherwise the pattern will get out of step as it
  21278. repeats.
  21279. @param transform an optional transform to apply to the points from the source path
  21280. as they are being used
  21281. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21282. a higher resolution, which improves the quality if you'll later want
  21283. to enlarge the stroked path. So for example, if you're planning on drawing
  21284. the stroke at 3x the size that you're creating it, you should set this to 3.
  21285. */
  21286. void createDashedStroke (Path& destPath,
  21287. const Path& sourcePath,
  21288. const float* dashLengths,
  21289. int numDashLengths,
  21290. const AffineTransform& transform = AffineTransform::identity,
  21291. float extraAccuracy = 1.0f) const;
  21292. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21293. @param destPath the resultant stroked outline shape will be copied into this path.
  21294. Note that it's ok for the source and destination Paths to be
  21295. the same object, so you can easily turn a path into a stroked version
  21296. of itself.
  21297. @param sourcePath the path to use as the source
  21298. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  21299. @param arrowheadStartLength the length of the arrowhead at the start of the path
  21300. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  21301. @param arrowheadEndLength the length of the arrowhead at the end of the path
  21302. @param transform an optional transform to apply to the points from the source path
  21303. as they are being used
  21304. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21305. a higher resolution, which improves the quality if you'll later want
  21306. to enlarge the stroked path. So for example, if you're planning on drawing
  21307. the stroke at 3x the size that you're creating it, you should set this to 3.
  21308. @see createDashedStroke
  21309. */
  21310. void createStrokeWithArrowheads (Path& destPath,
  21311. const Path& sourcePath,
  21312. float arrowheadStartWidth, float arrowheadStartLength,
  21313. float arrowheadEndWidth, float arrowheadEndLength,
  21314. const AffineTransform& transform = AffineTransform::identity,
  21315. float extraAccuracy = 1.0f) const;
  21316. /** Returns the stroke thickness. */
  21317. float getStrokeThickness() const noexcept { return thickness; }
  21318. /** Sets the stroke thickness. */
  21319. void setStrokeThickness (float newThickness) noexcept { thickness = newThickness; }
  21320. /** Returns the joint style. */
  21321. JointStyle getJointStyle() const noexcept { return jointStyle; }
  21322. /** Sets the joint style. */
  21323. void setJointStyle (JointStyle newStyle) noexcept { jointStyle = newStyle; }
  21324. /** Returns the end-cap style. */
  21325. EndCapStyle getEndStyle() const noexcept { return endStyle; }
  21326. /** Sets the end-cap style. */
  21327. void setEndStyle (EndCapStyle newStyle) noexcept { endStyle = newStyle; }
  21328. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21329. bool operator== (const PathStrokeType& other) const noexcept;
  21330. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21331. bool operator!= (const PathStrokeType& other) const noexcept;
  21332. private:
  21333. float thickness;
  21334. JointStyle jointStyle;
  21335. EndCapStyle endStyle;
  21336. JUCE_LEAK_DETECTOR (PathStrokeType);
  21337. };
  21338. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21339. /*** End of inlined file: juce_PathStrokeType.h ***/
  21340. /*** Start of inlined file: juce_Colours.h ***/
  21341. #ifndef __JUCE_COLOURS_JUCEHEADER__
  21342. #define __JUCE_COLOURS_JUCEHEADER__
  21343. /*** Start of inlined file: juce_Colour.h ***/
  21344. #ifndef __JUCE_COLOUR_JUCEHEADER__
  21345. #define __JUCE_COLOUR_JUCEHEADER__
  21346. /*** Start of inlined file: juce_PixelFormats.h ***/
  21347. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  21348. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  21349. #ifndef DOXYGEN
  21350. #if JUCE_MSVC
  21351. #pragma pack (push, 1)
  21352. #define PACKED
  21353. #elif JUCE_GCC
  21354. #define PACKED __attribute__((packed))
  21355. #else
  21356. #define PACKED
  21357. #endif
  21358. #endif
  21359. class PixelRGB;
  21360. class PixelAlpha;
  21361. /**
  21362. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  21363. operations with it.
  21364. This is used internally by the imaging classes.
  21365. @see PixelRGB
  21366. */
  21367. class JUCE_API PixelARGB
  21368. {
  21369. public:
  21370. /** Creates a pixel without defining its colour. */
  21371. PixelARGB() noexcept {}
  21372. ~PixelARGB() noexcept {}
  21373. /** Creates a pixel from a 32-bit argb value.
  21374. */
  21375. PixelARGB (const uint32 argb_) noexcept
  21376. : argb (argb_)
  21377. {
  21378. }
  21379. forcedinline uint32 getARGB() const noexcept { return argb; }
  21380. forcedinline uint32 getUnpremultipliedARGB() const noexcept { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  21381. forcedinline uint32 getRB() const noexcept { return 0x00ff00ff & argb; }
  21382. forcedinline uint32 getAG() const noexcept { return 0x00ff00ff & (argb >> 8); }
  21383. forcedinline uint8 getAlpha() const noexcept { return components.a; }
  21384. forcedinline uint8 getRed() const noexcept { return components.r; }
  21385. forcedinline uint8 getGreen() const noexcept { return components.g; }
  21386. forcedinline uint8 getBlue() const noexcept { return components.b; }
  21387. /** Blends another pixel onto this one.
  21388. This takes into account the opacity of the pixel being overlaid, and blends
  21389. it accordingly.
  21390. */
  21391. forcedinline void blend (const PixelARGB& src) noexcept
  21392. {
  21393. uint32 sargb = src.getARGB();
  21394. const uint32 alpha = 0x100 - (sargb >> 24);
  21395. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21396. sargb += 0xff00ff00 & (getAG() * alpha);
  21397. argb = sargb;
  21398. }
  21399. /** Blends another pixel onto this one.
  21400. This takes into account the opacity of the pixel being overlaid, and blends
  21401. it accordingly.
  21402. */
  21403. forcedinline void blend (const PixelAlpha& src) noexcept;
  21404. /** Blends another pixel onto this one.
  21405. This takes into account the opacity of the pixel being overlaid, and blends
  21406. it accordingly.
  21407. */
  21408. forcedinline void blend (const PixelRGB& src) noexcept;
  21409. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21410. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21411. being used, so this can blend semi-transparently from a PixelRGB argument.
  21412. */
  21413. template <class Pixel>
  21414. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21415. {
  21416. ++extraAlpha;
  21417. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  21418. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  21419. const uint32 alpha = 0x100 - (sargb >> 24);
  21420. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21421. sargb += 0xff00ff00 & (getAG() * alpha);
  21422. argb = sargb;
  21423. }
  21424. /** Blends another pixel with this one, creating a colour that is somewhere
  21425. between the two, as specified by the amount.
  21426. */
  21427. template <class Pixel>
  21428. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21429. {
  21430. uint32 drb = getRB();
  21431. drb += (((src.getRB() - drb) * amount) >> 8);
  21432. drb &= 0x00ff00ff;
  21433. uint32 dag = getAG();
  21434. dag += (((src.getAG() - dag) * amount) >> 8);
  21435. dag &= 0x00ff00ff;
  21436. dag <<= 8;
  21437. dag |= drb;
  21438. argb = dag;
  21439. }
  21440. /** Copies another pixel colour over this one.
  21441. This doesn't blend it - this colour is simply replaced by the other one.
  21442. */
  21443. template <class Pixel>
  21444. forcedinline void set (const Pixel& src) noexcept
  21445. {
  21446. argb = src.getARGB();
  21447. }
  21448. /** Replaces the colour's alpha value with another one. */
  21449. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21450. {
  21451. components.a = newAlpha;
  21452. }
  21453. /** Multiplies the colour's alpha value with another one. */
  21454. forcedinline void multiplyAlpha (int multiplier) noexcept
  21455. {
  21456. ++multiplier;
  21457. argb = ((multiplier * getAG()) & 0xff00ff00)
  21458. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  21459. }
  21460. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21461. {
  21462. multiplyAlpha ((int) (multiplier * 256.0f));
  21463. }
  21464. /** Sets the pixel's colour from individual components. */
  21465. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) noexcept
  21466. {
  21467. components.b = b;
  21468. components.g = g;
  21469. components.r = r;
  21470. components.a = a;
  21471. }
  21472. /** Premultiplies the pixel's RGB values by its alpha. */
  21473. forcedinline void premultiply() noexcept
  21474. {
  21475. const uint32 alpha = components.a;
  21476. if (alpha < 0xff)
  21477. {
  21478. if (alpha == 0)
  21479. {
  21480. components.b = 0;
  21481. components.g = 0;
  21482. components.r = 0;
  21483. }
  21484. else
  21485. {
  21486. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  21487. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  21488. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  21489. }
  21490. }
  21491. }
  21492. /** Unpremultiplies the pixel's RGB values. */
  21493. forcedinline void unpremultiply() noexcept
  21494. {
  21495. const uint32 alpha = components.a;
  21496. if (alpha < 0xff)
  21497. {
  21498. if (alpha == 0)
  21499. {
  21500. components.b = 0;
  21501. components.g = 0;
  21502. components.r = 0;
  21503. }
  21504. else
  21505. {
  21506. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  21507. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  21508. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  21509. }
  21510. }
  21511. }
  21512. forcedinline void desaturate() noexcept
  21513. {
  21514. if (components.a < 0xff && components.a > 0)
  21515. {
  21516. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  21517. components.r = components.g = components.b
  21518. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  21519. }
  21520. else
  21521. {
  21522. components.r = components.g = components.b
  21523. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  21524. }
  21525. }
  21526. /** The indexes of the different components in the byte layout of this type of colour. */
  21527. #if JUCE_BIG_ENDIAN
  21528. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  21529. #else
  21530. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  21531. #endif
  21532. private:
  21533. union
  21534. {
  21535. uint32 argb;
  21536. struct
  21537. {
  21538. #if JUCE_BIG_ENDIAN
  21539. uint8 a : 8, r : 8, g : 8, b : 8;
  21540. #else
  21541. uint8 b, g, r, a;
  21542. #endif
  21543. } PACKED components;
  21544. };
  21545. }
  21546. #ifndef DOXYGEN
  21547. PACKED
  21548. #endif
  21549. ;
  21550. /**
  21551. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  21552. This is used internally by the imaging classes.
  21553. @see PixelARGB
  21554. */
  21555. class JUCE_API PixelRGB
  21556. {
  21557. public:
  21558. /** Creates a pixel without defining its colour. */
  21559. PixelRGB() noexcept {}
  21560. ~PixelRGB() noexcept {}
  21561. /** Creates a pixel from a 32-bit argb value.
  21562. (The argb format is that used by PixelARGB)
  21563. */
  21564. PixelRGB (const uint32 argb) noexcept
  21565. {
  21566. r = (uint8) (argb >> 16);
  21567. g = (uint8) (argb >> 8);
  21568. b = (uint8) (argb);
  21569. }
  21570. forcedinline uint32 getARGB() const noexcept { return 0xff000000 | b | (g << 8) | (r << 16); }
  21571. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return getARGB(); }
  21572. forcedinline uint32 getRB() const noexcept { return b | (uint32) (r << 16); }
  21573. forcedinline uint32 getAG() const noexcept { return 0xff0000 | g; }
  21574. forcedinline uint8 getAlpha() const noexcept { return 0xff; }
  21575. forcedinline uint8 getRed() const noexcept { return r; }
  21576. forcedinline uint8 getGreen() const noexcept { return g; }
  21577. forcedinline uint8 getBlue() const noexcept { return b; }
  21578. /** Blends another pixel onto this one.
  21579. This takes into account the opacity of the pixel being overlaid, and blends
  21580. it accordingly.
  21581. */
  21582. forcedinline void blend (const PixelARGB& src) noexcept
  21583. {
  21584. uint32 sargb = src.getARGB();
  21585. const uint32 alpha = 0x100 - (sargb >> 24);
  21586. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21587. sargb += 0x0000ff00 & (g * alpha);
  21588. r = (uint8) (sargb >> 16);
  21589. g = (uint8) (sargb >> 8);
  21590. b = (uint8) sargb;
  21591. }
  21592. forcedinline void blend (const PixelRGB& src) noexcept
  21593. {
  21594. set (src);
  21595. }
  21596. forcedinline void blend (const PixelAlpha& src) noexcept;
  21597. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21598. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21599. being used, so this can blend semi-transparently from a PixelRGB argument.
  21600. */
  21601. template <class Pixel>
  21602. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21603. {
  21604. ++extraAlpha;
  21605. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  21606. const uint32 sag = extraAlpha * src.getAG();
  21607. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  21608. const uint32 alpha = 0x100 - (sargb >> 24);
  21609. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21610. sargb += 0x0000ff00 & (g * alpha);
  21611. b = (uint8) sargb;
  21612. g = (uint8) (sargb >> 8);
  21613. r = (uint8) (sargb >> 16);
  21614. }
  21615. /** Blends another pixel with this one, creating a colour that is somewhere
  21616. between the two, as specified by the amount.
  21617. */
  21618. template <class Pixel>
  21619. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21620. {
  21621. uint32 drb = getRB();
  21622. drb += (((src.getRB() - drb) * amount) >> 8);
  21623. uint32 dag = getAG();
  21624. dag += (((src.getAG() - dag) * amount) >> 8);
  21625. b = (uint8) drb;
  21626. g = (uint8) dag;
  21627. r = (uint8) (drb >> 16);
  21628. }
  21629. /** Copies another pixel colour over this one.
  21630. This doesn't blend it - this colour is simply replaced by the other one.
  21631. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  21632. is thrown away.
  21633. */
  21634. template <class Pixel>
  21635. forcedinline void set (const Pixel& src) noexcept
  21636. {
  21637. b = src.getBlue();
  21638. g = src.getGreen();
  21639. r = src.getRed();
  21640. }
  21641. /** This method is included for compatibility with the PixelARGB class. */
  21642. forcedinline void setAlpha (const uint8) noexcept {}
  21643. /** Multiplies the colour's alpha value with another one. */
  21644. forcedinline void multiplyAlpha (int) noexcept {}
  21645. /** Sets the pixel's colour from individual components. */
  21646. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) noexcept
  21647. {
  21648. r = r_;
  21649. g = g_;
  21650. b = b_;
  21651. }
  21652. /** Premultiplies the pixel's RGB values by its alpha. */
  21653. forcedinline void premultiply() noexcept {}
  21654. /** Unpremultiplies the pixel's RGB values. */
  21655. forcedinline void unpremultiply() noexcept {}
  21656. forcedinline void desaturate() noexcept
  21657. {
  21658. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  21659. }
  21660. /** The indexes of the different components in the byte layout of this type of colour. */
  21661. #if JUCE_MAC
  21662. enum { indexR = 0, indexG = 1, indexB = 2 };
  21663. #else
  21664. enum { indexR = 2, indexG = 1, indexB = 0 };
  21665. #endif
  21666. private:
  21667. #if JUCE_MAC
  21668. uint8 r, g, b;
  21669. #else
  21670. uint8 b, g, r;
  21671. #endif
  21672. }
  21673. #ifndef DOXYGEN
  21674. PACKED
  21675. #endif
  21676. ;
  21677. forcedinline void PixelARGB::blend (const PixelRGB& src) noexcept
  21678. {
  21679. set (src);
  21680. }
  21681. /**
  21682. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  21683. This is used internally by the imaging classes.
  21684. @see PixelARGB, PixelRGB
  21685. */
  21686. class JUCE_API PixelAlpha
  21687. {
  21688. public:
  21689. /** Creates a pixel without defining its colour. */
  21690. PixelAlpha() noexcept {}
  21691. ~PixelAlpha() noexcept {}
  21692. /** Creates a pixel from a 32-bit argb value.
  21693. (The argb format is that used by PixelARGB)
  21694. */
  21695. PixelAlpha (const uint32 argb) noexcept
  21696. {
  21697. a = (uint8) (argb >> 24);
  21698. }
  21699. forcedinline uint32 getARGB() const noexcept { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  21700. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return (((uint32) a) << 24) | 0xffffff; }
  21701. forcedinline uint32 getRB() const noexcept { return (((uint32) a) << 16) | a; }
  21702. forcedinline uint32 getAG() const noexcept { return (((uint32) a) << 16) | a; }
  21703. forcedinline uint8 getAlpha() const noexcept { return a; }
  21704. forcedinline uint8 getRed() const noexcept { return 0; }
  21705. forcedinline uint8 getGreen() const noexcept { return 0; }
  21706. forcedinline uint8 getBlue() const noexcept { return 0; }
  21707. /** Blends another pixel onto this one.
  21708. This takes into account the opacity of the pixel being overlaid, and blends
  21709. it accordingly.
  21710. */
  21711. template <class Pixel>
  21712. forcedinline void blend (const Pixel& src) noexcept
  21713. {
  21714. const int srcA = src.getAlpha();
  21715. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  21716. }
  21717. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21718. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21719. being used, so this can blend semi-transparently from a PixelRGB argument.
  21720. */
  21721. template <class Pixel>
  21722. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21723. {
  21724. ++extraAlpha;
  21725. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  21726. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  21727. }
  21728. /** Blends another pixel with this one, creating a colour that is somewhere
  21729. between the two, as specified by the amount.
  21730. */
  21731. template <class Pixel>
  21732. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21733. {
  21734. a += ((src,getAlpha() - a) * amount) >> 8;
  21735. }
  21736. /** Copies another pixel colour over this one.
  21737. This doesn't blend it - this colour is simply replaced by the other one.
  21738. */
  21739. template <class Pixel>
  21740. forcedinline void set (const Pixel& src) noexcept
  21741. {
  21742. a = src.getAlpha();
  21743. }
  21744. /** Replaces the colour's alpha value with another one. */
  21745. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21746. {
  21747. a = newAlpha;
  21748. }
  21749. /** Multiplies the colour's alpha value with another one. */
  21750. forcedinline void multiplyAlpha (int multiplier) noexcept
  21751. {
  21752. ++multiplier;
  21753. a = (uint8) ((a * multiplier) >> 8);
  21754. }
  21755. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21756. {
  21757. a = (uint8) (a * multiplier);
  21758. }
  21759. /** Sets the pixel's colour from individual components. */
  21760. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) noexcept
  21761. {
  21762. a = a_;
  21763. }
  21764. /** Premultiplies the pixel's RGB values by its alpha. */
  21765. forcedinline void premultiply() noexcept
  21766. {
  21767. }
  21768. /** Unpremultiplies the pixel's RGB values. */
  21769. forcedinline void unpremultiply() noexcept
  21770. {
  21771. }
  21772. forcedinline void desaturate() noexcept
  21773. {
  21774. }
  21775. /** The indexes of the different components in the byte layout of this type of colour. */
  21776. enum { indexA = 0 };
  21777. private:
  21778. uint8 a : 8;
  21779. }
  21780. #ifndef DOXYGEN
  21781. PACKED
  21782. #endif
  21783. ;
  21784. forcedinline void PixelRGB::blend (const PixelAlpha& src) noexcept
  21785. {
  21786. blend (PixelARGB (src.getARGB()));
  21787. }
  21788. forcedinline void PixelARGB::blend (const PixelAlpha& src) noexcept
  21789. {
  21790. uint32 sargb = src.getARGB();
  21791. const uint32 alpha = 0x100 - (sargb >> 24);
  21792. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21793. sargb += 0xff00ff00 & (getAG() * alpha);
  21794. argb = sargb;
  21795. }
  21796. #if JUCE_MSVC
  21797. #pragma pack (pop)
  21798. #endif
  21799. #undef PACKED
  21800. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21801. /*** End of inlined file: juce_PixelFormats.h ***/
  21802. /**
  21803. Represents a colour, also including a transparency value.
  21804. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21805. */
  21806. class JUCE_API Colour
  21807. {
  21808. public:
  21809. /** Creates a transparent black colour. */
  21810. Colour() noexcept;
  21811. /** Creates a copy of another Colour object. */
  21812. Colour (const Colour& other) noexcept;
  21813. /** Creates a colour from a 32-bit ARGB value.
  21814. The format of this number is:
  21815. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21816. All components in the range 0x00 to 0xff.
  21817. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21818. @see getPixelARGB
  21819. */
  21820. explicit Colour (uint32 argb) noexcept;
  21821. /** Creates an opaque colour using 8-bit red, green and blue values */
  21822. Colour (uint8 red,
  21823. uint8 green,
  21824. uint8 blue) noexcept;
  21825. /** Creates an opaque colour using 8-bit red, green and blue values */
  21826. static Colour fromRGB (uint8 red,
  21827. uint8 green,
  21828. uint8 blue) noexcept;
  21829. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21830. Colour (uint8 red,
  21831. uint8 green,
  21832. uint8 blue,
  21833. uint8 alpha) noexcept;
  21834. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21835. static Colour fromRGBA (uint8 red,
  21836. uint8 green,
  21837. uint8 blue,
  21838. uint8 alpha) noexcept;
  21839. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21840. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21841. Values outside the valid range will be clipped.
  21842. */
  21843. Colour (uint8 red,
  21844. uint8 green,
  21845. uint8 blue,
  21846. float alpha) noexcept;
  21847. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21848. static Colour fromRGBAFloat (uint8 red,
  21849. uint8 green,
  21850. uint8 blue,
  21851. float alpha) noexcept;
  21852. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21853. The floating point values must be between 0.0 and 1.0.
  21854. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21855. Values outside the valid range will be clipped.
  21856. */
  21857. Colour (float hue,
  21858. float saturation,
  21859. float brightness,
  21860. uint8 alpha) noexcept;
  21861. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21862. All values must be between 0.0 and 1.0.
  21863. Numbers outside the valid range will be clipped.
  21864. */
  21865. Colour (float hue,
  21866. float saturation,
  21867. float brightness,
  21868. float alpha) noexcept;
  21869. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21870. The floating point values must be between 0.0 and 1.0.
  21871. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21872. Values outside the valid range will be clipped.
  21873. */
  21874. static Colour fromHSV (float hue,
  21875. float saturation,
  21876. float brightness,
  21877. float alpha) noexcept;
  21878. /** Destructor. */
  21879. ~Colour() noexcept;
  21880. /** Copies another Colour object. */
  21881. Colour& operator= (const Colour& other) noexcept;
  21882. /** Compares two colours. */
  21883. bool operator== (const Colour& other) const noexcept;
  21884. /** Compares two colours. */
  21885. bool operator!= (const Colour& other) const noexcept;
  21886. /** Returns the red component of this colour.
  21887. @returns a value between 0x00 and 0xff.
  21888. */
  21889. uint8 getRed() const noexcept { return argb.getRed(); }
  21890. /** Returns the green component of this colour.
  21891. @returns a value between 0x00 and 0xff.
  21892. */
  21893. uint8 getGreen() const noexcept { return argb.getGreen(); }
  21894. /** Returns the blue component of this colour.
  21895. @returns a value between 0x00 and 0xff.
  21896. */
  21897. uint8 getBlue() const noexcept { return argb.getBlue(); }
  21898. /** Returns the red component of this colour as a floating point value.
  21899. @returns a value between 0.0 and 1.0
  21900. */
  21901. float getFloatRed() const noexcept;
  21902. /** Returns the green component of this colour as a floating point value.
  21903. @returns a value between 0.0 and 1.0
  21904. */
  21905. float getFloatGreen() const noexcept;
  21906. /** Returns the blue component of this colour as a floating point value.
  21907. @returns a value between 0.0 and 1.0
  21908. */
  21909. float getFloatBlue() const noexcept;
  21910. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21911. */
  21912. const PixelARGB getPixelARGB() const noexcept;
  21913. /** Returns a 32-bit integer that represents this colour.
  21914. The format of this number is:
  21915. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21916. */
  21917. uint32 getARGB() const noexcept;
  21918. /** Returns the colour's alpha (opacity).
  21919. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21920. */
  21921. uint8 getAlpha() const noexcept { return argb.getAlpha(); }
  21922. /** Returns the colour's alpha (opacity) as a floating point value.
  21923. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21924. */
  21925. float getFloatAlpha() const noexcept;
  21926. /** Returns true if this colour is completely opaque.
  21927. Equivalent to (getAlpha() == 0xff).
  21928. */
  21929. bool isOpaque() const noexcept;
  21930. /** Returns true if this colour is completely transparent.
  21931. Equivalent to (getAlpha() == 0x00).
  21932. */
  21933. bool isTransparent() const noexcept;
  21934. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21935. Colour withAlpha (uint8 newAlpha) const noexcept;
  21936. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21937. Colour withAlpha (float newAlpha) const noexcept;
  21938. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21939. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21940. */
  21941. Colour withMultipliedAlpha (float alphaMultiplier) const noexcept;
  21942. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21943. If the foreground colour is semi-transparent, it is blended onto this colour
  21944. accordingly.
  21945. */
  21946. Colour overlaidWith (const Colour& foregroundColour) const noexcept;
  21947. /** Returns a colour that lies somewhere between this one and another.
  21948. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21949. is 1.0, the result is 100% of the other colour.
  21950. */
  21951. Colour interpolatedWith (const Colour& other, float proportionOfOther) const noexcept;
  21952. /** Returns the colour's hue component.
  21953. The value returned is in the range 0.0 to 1.0
  21954. */
  21955. float getHue() const noexcept;
  21956. /** Returns the colour's saturation component.
  21957. The value returned is in the range 0.0 to 1.0
  21958. */
  21959. float getSaturation() const noexcept;
  21960. /** Returns the colour's brightness component.
  21961. The value returned is in the range 0.0 to 1.0
  21962. */
  21963. float getBrightness() const noexcept;
  21964. /** Returns the colour's hue, saturation and brightness components all at once.
  21965. The values returned are in the range 0.0 to 1.0
  21966. */
  21967. void getHSB (float& hue,
  21968. float& saturation,
  21969. float& brightness) const noexcept;
  21970. /** Returns a copy of this colour with a different hue. */
  21971. Colour withHue (float newHue) const noexcept;
  21972. /** Returns a copy of this colour with a different saturation. */
  21973. Colour withSaturation (float newSaturation) const noexcept;
  21974. /** Returns a copy of this colour with a different brightness.
  21975. @see brighter, darker, withMultipliedBrightness
  21976. */
  21977. Colour withBrightness (float newBrightness) const noexcept;
  21978. /** Returns a copy of this colour with it hue rotated.
  21979. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21980. @see brighter, darker, withMultipliedBrightness
  21981. */
  21982. Colour withRotatedHue (float amountToRotate) const noexcept;
  21983. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21984. The new colour's saturation is (this->getSaturation() * multiplier)
  21985. (the result is clipped to legal limits).
  21986. */
  21987. Colour withMultipliedSaturation (float multiplier) const noexcept;
  21988. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21989. The new colour's saturation is (this->getBrightness() * multiplier)
  21990. (the result is clipped to legal limits).
  21991. */
  21992. Colour withMultipliedBrightness (float amount) const noexcept;
  21993. /** Returns a brighter version of this colour.
  21994. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21995. unchanged, and higher values make it brighter
  21996. @see withMultipliedBrightness
  21997. */
  21998. Colour brighter (float amountBrighter = 0.4f) const noexcept;
  21999. /** Returns a darker version of this colour.
  22000. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  22001. unchanged, and higher values make it darker
  22002. @see withMultipliedBrightness
  22003. */
  22004. Colour darker (float amountDarker = 0.4f) const noexcept;
  22005. /** Returns a colour that will be clearly visible against this colour.
  22006. The amount parameter indicates how contrasting the new colour should
  22007. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  22008. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  22009. return white; Colours::white.contrasting (1.0f) will return black, etc.
  22010. */
  22011. Colour contrasting (float amount = 1.0f) const noexcept;
  22012. /** Returns a colour that contrasts against two colours.
  22013. Looks for a colour that contrasts with both of the colours passed-in.
  22014. Handy for things like choosing a highlight colour in text editors, etc.
  22015. */
  22016. static Colour contrasting (const Colour& colour1,
  22017. const Colour& colour2) noexcept;
  22018. /** Returns an opaque shade of grey.
  22019. @param brightness the level of grey to return - 0 is black, 1.0 is white
  22020. */
  22021. static Colour greyLevel (float brightness) noexcept;
  22022. /** Returns a stringified version of this colour.
  22023. The string can be turned back into a colour using the fromString() method.
  22024. */
  22025. String toString() const;
  22026. /** Reads the colour from a string that was created with toString().
  22027. */
  22028. static Colour fromString (const String& encodedColourString);
  22029. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  22030. String toDisplayString (bool includeAlphaValue) const;
  22031. private:
  22032. PixelARGB argb;
  22033. };
  22034. #endif // __JUCE_COLOUR_JUCEHEADER__
  22035. /*** End of inlined file: juce_Colour.h ***/
  22036. /**
  22037. Contains a set of predefined named colours (mostly standard HTML colours)
  22038. @see Colour, Colours::greyLevel
  22039. */
  22040. class Colours
  22041. {
  22042. public:
  22043. static JUCE_API const Colour
  22044. transparentBlack, /**< ARGB = 0x00000000 */
  22045. transparentWhite, /**< ARGB = 0x00ffffff */
  22046. black, /**< ARGB = 0xff000000 */
  22047. white, /**< ARGB = 0xffffffff */
  22048. blue, /**< ARGB = 0xff0000ff */
  22049. grey, /**< ARGB = 0xff808080 */
  22050. green, /**< ARGB = 0xff008000 */
  22051. red, /**< ARGB = 0xffff0000 */
  22052. yellow, /**< ARGB = 0xffffff00 */
  22053. aliceblue, antiquewhite, aqua, aquamarine,
  22054. azure, beige, bisque, blanchedalmond,
  22055. blueviolet, brown, burlywood, cadetblue,
  22056. chartreuse, chocolate, coral, cornflowerblue,
  22057. cornsilk, crimson, cyan, darkblue,
  22058. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  22059. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  22060. darkorchid, darkred, darksalmon, darkseagreen,
  22061. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  22062. deeppink, deepskyblue, dimgrey, dodgerblue,
  22063. firebrick, floralwhite, forestgreen, fuchsia,
  22064. gainsboro, gold, goldenrod, greenyellow,
  22065. honeydew, hotpink, indianred, indigo,
  22066. ivory, khaki, lavender, lavenderblush,
  22067. lemonchiffon, lightblue, lightcoral, lightcyan,
  22068. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  22069. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  22070. lightsteelblue, lightyellow, lime, limegreen,
  22071. linen, magenta, maroon, mediumaquamarine,
  22072. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  22073. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  22074. midnightblue, mintcream, mistyrose, navajowhite,
  22075. navy, oldlace, olive, olivedrab,
  22076. orange, orangered, orchid, palegoldenrod,
  22077. palegreen, paleturquoise, palevioletred, papayawhip,
  22078. peachpuff, peru, pink, plum,
  22079. powderblue, purple, rosybrown, royalblue,
  22080. saddlebrown, salmon, sandybrown, seagreen,
  22081. seashell, sienna, silver, skyblue,
  22082. slateblue, slategrey, snow, springgreen,
  22083. steelblue, tan, teal, thistle,
  22084. tomato, turquoise, violet, wheat,
  22085. whitesmoke, yellowgreen;
  22086. /** Attempts to look up a string in the list of known colour names, and return
  22087. the appropriate colour.
  22088. A non-case-sensitive search is made of the list of predefined colours, and
  22089. if a match is found, that colour is returned. If no match is found, the
  22090. colour passed in as the defaultColour parameter is returned.
  22091. */
  22092. static JUCE_API const Colour findColourForName (const String& colourName,
  22093. const Colour& defaultColour);
  22094. private:
  22095. // this isn't a class you should ever instantiate - it's just here for the
  22096. // static values in it.
  22097. Colours();
  22098. JUCE_DECLARE_NON_COPYABLE (Colours);
  22099. };
  22100. #endif // __JUCE_COLOURS_JUCEHEADER__
  22101. /*** End of inlined file: juce_Colours.h ***/
  22102. /*** Start of inlined file: juce_ColourGradient.h ***/
  22103. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  22104. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  22105. /**
  22106. Describes the layout and colours that should be used to paint a colour gradient.
  22107. @see Graphics::setGradientFill
  22108. */
  22109. class JUCE_API ColourGradient
  22110. {
  22111. public:
  22112. /** Creates a gradient object.
  22113. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  22114. colour2 should be. In between them there's a gradient.
  22115. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  22116. its centre.
  22117. The alpha transparencies of the colours are used, so note that
  22118. if you blend from transparent to a solid colour, the RGB of the transparent
  22119. colour will become visible in parts of the gradient. e.g. blending
  22120. from Colour::transparentBlack to Colours::white will produce a
  22121. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  22122. will be white all the way across.
  22123. @see ColourGradient
  22124. */
  22125. ColourGradient (const Colour& colour1, float x1, float y1,
  22126. const Colour& colour2, float x2, float y2,
  22127. bool isRadial);
  22128. /** Creates an uninitialised gradient.
  22129. If you use this constructor instead of the other one, be sure to set all the
  22130. object's public member variables before using it!
  22131. */
  22132. ColourGradient() noexcept;
  22133. /** Destructor */
  22134. ~ColourGradient();
  22135. /** Removes any colours that have been added.
  22136. This will also remove any start and end colours, so the gradient won't work. You'll
  22137. need to add more colours with addColour().
  22138. */
  22139. void clearColours();
  22140. /** Adds a colour at a point along the length of the gradient.
  22141. This allows the gradient to go through a spectrum of colours, instead of just a
  22142. start and end colour.
  22143. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  22144. of the distance along the line between the two points
  22145. at which the colour should occur.
  22146. @param colour the colour that should be used at this point
  22147. @returns the index at which the new point was added
  22148. */
  22149. int addColour (double proportionAlongGradient,
  22150. const Colour& colour);
  22151. /** Removes one of the colours from the gradient. */
  22152. void removeColour (int index);
  22153. /** Multiplies the alpha value of all the colours by the given scale factor */
  22154. void multiplyOpacity (float multiplier) noexcept;
  22155. /** Returns the number of colour-stops that have been added. */
  22156. int getNumColours() const noexcept;
  22157. /** Returns the position along the length of the gradient of the colour with this index.
  22158. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  22159. */
  22160. double getColourPosition (int index) const noexcept;
  22161. /** Returns the colour that was added with a given index.
  22162. The index is from 0 to getNumColours() - 1.
  22163. */
  22164. const Colour getColour (int index) const noexcept;
  22165. /** Changes the colour at a given index.
  22166. The index is from 0 to getNumColours() - 1.
  22167. */
  22168. void setColour (int index, const Colour& newColour) noexcept;
  22169. /** Returns the an interpolated colour at any position along the gradient.
  22170. @param position the position along the gradient, between 0 and 1
  22171. */
  22172. Colour getColourAtPosition (double position) const noexcept;
  22173. /** Creates a set of interpolated premultiplied ARGB values.
  22174. This will resize the HeapBlock, fill it with the colours, and will return the number of
  22175. colours that it added.
  22176. */
  22177. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  22178. /** Returns true if all colours are opaque. */
  22179. bool isOpaque() const noexcept;
  22180. /** Returns true if all colours are completely transparent. */
  22181. bool isInvisible() const noexcept;
  22182. Point<float> point1, point2;
  22183. /** If true, the gradient should be filled circularly, centred around
  22184. point1, with point2 defining a point on the circumference.
  22185. If false, the gradient is linear between the two points.
  22186. */
  22187. bool isRadial;
  22188. bool operator== (const ColourGradient& other) const noexcept;
  22189. bool operator!= (const ColourGradient& other) const noexcept;
  22190. private:
  22191. struct ColourPoint
  22192. {
  22193. ColourPoint() noexcept {}
  22194. ColourPoint (const double position_, const Colour& colour_) noexcept
  22195. : position (position_), colour (colour_)
  22196. {}
  22197. bool operator== (const ColourPoint& other) const noexcept;
  22198. bool operator!= (const ColourPoint& other) const noexcept;
  22199. double position;
  22200. Colour colour;
  22201. };
  22202. Array <ColourPoint> colours;
  22203. JUCE_LEAK_DETECTOR (ColourGradient);
  22204. };
  22205. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  22206. /*** End of inlined file: juce_ColourGradient.h ***/
  22207. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  22208. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22209. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22210. /**
  22211. Defines the method used to postion some kind of rectangular object within
  22212. a rectangular viewport.
  22213. Although similar to Justification, this is more specific, and has some extra
  22214. options.
  22215. */
  22216. class JUCE_API RectanglePlacement
  22217. {
  22218. public:
  22219. /** Creates a RectanglePlacement object using a combination of flags. */
  22220. inline RectanglePlacement (int flags_) noexcept : flags (flags_) {}
  22221. /** Creates a copy of another RectanglePlacement object. */
  22222. RectanglePlacement (const RectanglePlacement& other) noexcept;
  22223. /** Copies another RectanglePlacement object. */
  22224. RectanglePlacement& operator= (const RectanglePlacement& other) noexcept;
  22225. bool operator== (const RectanglePlacement& other) const noexcept;
  22226. bool operator!= (const RectanglePlacement& other) const noexcept;
  22227. /** Flag values that can be combined and used in the constructor. */
  22228. enum
  22229. {
  22230. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  22231. xLeft = 1,
  22232. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  22233. xRight = 2,
  22234. /** Indicates that the source should be placed in the centre between the left and right
  22235. sides of the available space. */
  22236. xMid = 4,
  22237. /** Indicates that the source's top edge should be aligned with the top edge of the
  22238. destination rectangle. */
  22239. yTop = 8,
  22240. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  22241. destination rectangle. */
  22242. yBottom = 16,
  22243. /** Indicates that the source should be placed in the centre between the top and bottom
  22244. sides of the available space. */
  22245. yMid = 32,
  22246. /** If this flag is set, then the source rectangle will be resized to completely fill
  22247. the destination rectangle, and all other flags are ignored.
  22248. */
  22249. stretchToFit = 64,
  22250. /** If this flag is set, then the source rectangle will be resized so that it is the
  22251. minimum size to completely fill the destination rectangle, without changing its
  22252. aspect ratio. This means that some of the source rectangle may fall outside
  22253. the destination.
  22254. If this flag is not set, the source will be given the maximum size at which none
  22255. of it falls outside the destination rectangle.
  22256. */
  22257. fillDestination = 128,
  22258. /** Indicates that the source rectangle can be reduced in size if required, but should
  22259. never be made larger than its original size.
  22260. */
  22261. onlyReduceInSize = 256,
  22262. /** Indicates that the source rectangle can be enlarged if required, but should
  22263. never be made smaller than its original size.
  22264. */
  22265. onlyIncreaseInSize = 512,
  22266. /** Indicates that the source rectangle's size should be left unchanged.
  22267. */
  22268. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  22269. /** A shorthand value that is equivalent to (xMid | yMid). */
  22270. centred = 4 + 32
  22271. };
  22272. /** Returns the raw flags that are set for this object. */
  22273. inline int getFlags() const noexcept { return flags; }
  22274. /** Tests a set of flags for this object.
  22275. @returns true if any of the flags passed in are set on this object.
  22276. */
  22277. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  22278. /** Adjusts the position and size of a rectangle to fit it into a space.
  22279. The source rectangle co-ordinates will be adjusted so that they fit into
  22280. the destination rectangle based on this object's flags.
  22281. */
  22282. void applyTo (double& sourceX,
  22283. double& sourceY,
  22284. double& sourceW,
  22285. double& sourceH,
  22286. double destinationX,
  22287. double destinationY,
  22288. double destinationW,
  22289. double destinationH) const noexcept;
  22290. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22291. into the destination rectangle using the current flags.
  22292. */
  22293. template <typename ValueType>
  22294. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  22295. const Rectangle<ValueType>& destination) const noexcept
  22296. {
  22297. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  22298. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  22299. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  22300. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  22301. static_cast <ValueType> (w), static_cast <ValueType> (h));
  22302. }
  22303. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22304. into the destination rectangle using the current flags.
  22305. */
  22306. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  22307. const Rectangle<float>& destination) const noexcept;
  22308. private:
  22309. int flags;
  22310. };
  22311. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22312. /*** End of inlined file: juce_RectanglePlacement.h ***/
  22313. class LowLevelGraphicsContext;
  22314. class Image;
  22315. class FillType;
  22316. class RectangleList;
  22317. /**
  22318. A graphics context, used for drawing a component or image.
  22319. When a Component needs painting, a Graphics context is passed to its
  22320. Component::paint() method, and this you then call methods within this
  22321. object to actually draw the component's content.
  22322. A Graphics can also be created from an image, to allow drawing directly onto
  22323. that image.
  22324. @see Component::paint
  22325. */
  22326. class JUCE_API Graphics
  22327. {
  22328. public:
  22329. /** Creates a Graphics object to draw directly onto the given image.
  22330. The graphics object that is created will be set up to draw onto the image,
  22331. with the context's clipping area being the entire size of the image, and its
  22332. origin being the image's origin. To draw into a subsection of an image, use the
  22333. reduceClipRegion() and setOrigin() methods.
  22334. Obviously you shouldn't delete the image before this context is deleted.
  22335. */
  22336. explicit Graphics (const Image& imageToDrawOnto);
  22337. /** Destructor. */
  22338. ~Graphics();
  22339. /** Changes the current drawing colour.
  22340. This sets the colour that will now be used for drawing operations - it also
  22341. sets the opacity to that of the colour passed-in.
  22342. If a brush is being used when this method is called, the brush will be deselected,
  22343. and any subsequent drawing will be done with a solid colour brush instead.
  22344. @see setOpacity
  22345. */
  22346. void setColour (const Colour& newColour);
  22347. /** Changes the opacity to use with the current colour.
  22348. If a solid colour is being used for drawing, this changes its opacity
  22349. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  22350. If a gradient is being used, this will have no effect on it.
  22351. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  22352. */
  22353. void setOpacity (float newOpacity);
  22354. /** Sets the context to use a gradient for its fill pattern.
  22355. */
  22356. void setGradientFill (const ColourGradient& gradient);
  22357. /** Sets the context to use a tiled image pattern for filling.
  22358. Make sure that you don't delete this image while it's still being used by
  22359. this context!
  22360. */
  22361. void setTiledImageFill (const Image& imageToUse,
  22362. int anchorX, int anchorY,
  22363. float opacity);
  22364. /** Changes the current fill settings.
  22365. @see setColour, setGradientFill, setTiledImageFill
  22366. */
  22367. void setFillType (const FillType& newFill);
  22368. /** Changes the font to use for subsequent text-drawing functions.
  22369. Note there's also a setFont (float, int) method to quickly change the size and
  22370. style of the current font.
  22371. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  22372. */
  22373. void setFont (const Font& newFont);
  22374. /** Changes the size and style of the currently-selected font.
  22375. This is a convenient shortcut that changes the context's current font to a
  22376. different size or style. The typeface won't be changed.
  22377. @see Font
  22378. */
  22379. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  22380. /** Returns the currently selected font. */
  22381. Font getCurrentFont() const;
  22382. /** Draws a one-line text string.
  22383. This will use the current colour (or brush) to fill the text. The font is the last
  22384. one specified by setFont().
  22385. @param text the string to draw
  22386. @param startX the position to draw the left-hand edge of the text
  22387. @param baselineY the position of the text's baseline
  22388. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  22389. */
  22390. void drawSingleLineText (const String& text,
  22391. int startX, int baselineY) const;
  22392. /** Draws text across multiple lines.
  22393. This will break the text onto a new line where there's a new-line or
  22394. carriage-return character, or at a word-boundary when the text becomes wider
  22395. than the size specified by the maximumLineWidth parameter.
  22396. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  22397. */
  22398. void drawMultiLineText (const String& text,
  22399. int startX, int baselineY,
  22400. int maximumLineWidth) const;
  22401. /** Renders a string of text as a vector path.
  22402. This allows a string to be transformed with an arbitrary AffineTransform and
  22403. rendered using the current colour/brush. It's much slower than the normal text methods
  22404. but more accurate.
  22405. @see setFont
  22406. */
  22407. void drawTextAsPath (const String& text,
  22408. const AffineTransform& transform) const;
  22409. /** Draws a line of text within a specified rectangle.
  22410. The text will be positioned within the rectangle based on the justification
  22411. flags passed-in. If the string is too long to fit inside the rectangle, it will
  22412. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  22413. flag is true).
  22414. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  22415. */
  22416. void drawText (const String& text,
  22417. int x, int y, int width, int height,
  22418. const Justification& justificationType,
  22419. bool useEllipsesIfTooBig) const;
  22420. /** Tries to draw a text string inside a given space.
  22421. This does its best to make the given text readable within the specified rectangle,
  22422. so it useful for labelling things.
  22423. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  22424. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  22425. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  22426. it's been truncated.
  22427. A Justification parameter lets you specify how the text is laid out within the rectangle,
  22428. both horizontally and vertically.
  22429. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  22430. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  22431. can set this value to 1.0f.
  22432. @see GlyphArrangement::addFittedText
  22433. */
  22434. void drawFittedText (const String& text,
  22435. int x, int y, int width, int height,
  22436. const Justification& justificationFlags,
  22437. int maximumNumberOfLines,
  22438. float minimumHorizontalScale = 0.7f) const;
  22439. /** Fills the context's entire clip region with the current colour or brush.
  22440. (See also the fillAll (const Colour&) method which is a quick way of filling
  22441. it with a given colour).
  22442. */
  22443. void fillAll() const;
  22444. /** Fills the context's entire clip region with a given colour.
  22445. This leaves the context's current colour and brush unchanged, it just
  22446. uses the specified colour temporarily.
  22447. */
  22448. void fillAll (const Colour& colourToUse) const;
  22449. /** Fills a rectangle with the current colour or brush.
  22450. @see drawRect, fillRoundedRectangle
  22451. */
  22452. void fillRect (int x, int y, int width, int height) const;
  22453. /** Fills a rectangle with the current colour or brush. */
  22454. void fillRect (const Rectangle<int>& rectangle) const;
  22455. /** Fills a rectangle with the current colour or brush.
  22456. This uses sub-pixel positioning so is slower than the fillRect method which
  22457. takes integer co-ordinates.
  22458. */
  22459. void fillRect (float x, float y, float width, float height) const;
  22460. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22461. @see drawRoundedRectangle, Path::addRoundedRectangle
  22462. */
  22463. void fillRoundedRectangle (float x, float y, float width, float height,
  22464. float cornerSize) const;
  22465. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22466. @see drawRoundedRectangle, Path::addRoundedRectangle
  22467. */
  22468. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  22469. float cornerSize) const;
  22470. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  22471. */
  22472. void fillCheckerBoard (const Rectangle<int>& area,
  22473. int checkWidth, int checkHeight,
  22474. const Colour& colour1, const Colour& colour2) const;
  22475. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22476. The lines are drawn inside the given rectangle, and greater line thicknesses
  22477. extend inwards.
  22478. @see fillRect
  22479. */
  22480. void drawRect (int x, int y, int width, int height,
  22481. int lineThickness = 1) const;
  22482. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22483. The lines are drawn inside the given rectangle, and greater line thicknesses
  22484. extend inwards.
  22485. @see fillRect
  22486. */
  22487. void drawRect (float x, float y, float width, float height,
  22488. float lineThickness = 1.0f) const;
  22489. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22490. The lines are drawn inside the given rectangle, and greater line thicknesses
  22491. extend inwards.
  22492. @see fillRect
  22493. */
  22494. void drawRect (const Rectangle<int>& rectangle,
  22495. int lineThickness = 1) const;
  22496. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22497. @see fillRoundedRectangle, Path::addRoundedRectangle
  22498. */
  22499. void drawRoundedRectangle (float x, float y, float width, float height,
  22500. float cornerSize, float lineThickness) const;
  22501. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22502. @see fillRoundedRectangle, Path::addRoundedRectangle
  22503. */
  22504. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  22505. float cornerSize, float lineThickness) const;
  22506. /** Draws a 3D raised (or indented) bevel using two colours.
  22507. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  22508. extend inwards.
  22509. The top-left colour is used for the top- and left-hand edges of the
  22510. bevel; the bottom-right colour is used for the bottom- and right-hand
  22511. edges.
  22512. If useGradient is true, then the bevel fades out to make it look more curved
  22513. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  22514. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  22515. the centre edges are sharp and it fades towards the outside.
  22516. */
  22517. void drawBevel (int x, int y, int width, int height,
  22518. int bevelThickness,
  22519. const Colour& topLeftColour = Colours::white,
  22520. const Colour& bottomRightColour = Colours::black,
  22521. bool useGradient = true,
  22522. bool sharpEdgeOnOutside = true) const;
  22523. /** Draws a pixel using the current colour or brush.
  22524. */
  22525. void setPixel (int x, int y) const;
  22526. /** Fills an ellipse with the current colour or brush.
  22527. The ellipse is drawn to fit inside the given rectangle.
  22528. @see drawEllipse, Path::addEllipse
  22529. */
  22530. void fillEllipse (float x, float y, float width, float height) const;
  22531. /** Draws an elliptical stroke using the current colour or brush.
  22532. @see fillEllipse, Path::addEllipse
  22533. */
  22534. void drawEllipse (float x, float y, float width, float height,
  22535. float lineThickness) const;
  22536. /** Draws a line between two points.
  22537. The line is 1 pixel wide and drawn with the current colour or brush.
  22538. */
  22539. void drawLine (float startX, float startY, float endX, float endY) const;
  22540. /** Draws a line between two points with a given thickness.
  22541. @see Path::addLineSegment
  22542. */
  22543. void drawLine (float startX, float startY, float endX, float endY,
  22544. float lineThickness) const;
  22545. /** Draws a line between two points.
  22546. The line is 1 pixel wide and drawn with the current colour or brush.
  22547. */
  22548. void drawLine (const Line<float>& line) const;
  22549. /** Draws a line between two points with a given thickness.
  22550. @see Path::addLineSegment
  22551. */
  22552. void drawLine (const Line<float>& line, float lineThickness) const;
  22553. /** Draws a dashed line using a custom set of dash-lengths.
  22554. @param line the line to draw
  22555. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  22556. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  22557. draw 6 pixels, skip 7 pixels, and then repeat.
  22558. @param numDashLengths the number of elements in the array (this must be an even number).
  22559. @param lineThickness the thickness of the line to draw
  22560. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  22561. @see PathStrokeType::createDashedStroke
  22562. */
  22563. void drawDashedLine (const Line<float>& line,
  22564. const float* dashLengths, int numDashLengths,
  22565. float lineThickness = 1.0f,
  22566. int dashIndexToStartFrom = 0) const;
  22567. /** Draws a vertical line of pixels at a given x position.
  22568. The x position is an integer, but the top and bottom of the line can be sub-pixel
  22569. positions, and these will be anti-aliased if necessary.
  22570. The bottom parameter must be greater than or equal to the top parameter.
  22571. */
  22572. void drawVerticalLine (int x, float top, float bottom) const;
  22573. /** Draws a horizontal line of pixels at a given y position.
  22574. The y position is an integer, but the left and right ends of the line can be sub-pixel
  22575. positions, and these will be anti-aliased if necessary.
  22576. The right parameter must be greater than or equal to the left parameter.
  22577. */
  22578. void drawHorizontalLine (int y, float left, float right) const;
  22579. /** Fills a path using the currently selected colour or brush.
  22580. */
  22581. void fillPath (const Path& path,
  22582. const AffineTransform& transform = AffineTransform::identity) const;
  22583. /** Draws a path's outline using the currently selected colour or brush.
  22584. */
  22585. void strokePath (const Path& path,
  22586. const PathStrokeType& strokeType,
  22587. const AffineTransform& transform = AffineTransform::identity) const;
  22588. /** Draws a line with an arrowhead at its end.
  22589. @param line the line to draw
  22590. @param lineThickness the thickness of the line
  22591. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  22592. @param arrowheadLength the length of the arrow head (along the length of the line)
  22593. */
  22594. void drawArrow (const Line<float>& line,
  22595. float lineThickness,
  22596. float arrowheadWidth,
  22597. float arrowheadLength) const;
  22598. /** Types of rendering quality that can be specified when drawing images.
  22599. @see blendImage, Graphics::setImageResamplingQuality
  22600. */
  22601. enum ResamplingQuality
  22602. {
  22603. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  22604. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  22605. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  22606. };
  22607. /** Changes the quality that will be used when resampling images.
  22608. By default a Graphics object will be set to mediumRenderingQuality.
  22609. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  22610. */
  22611. void setImageResamplingQuality (const ResamplingQuality newQuality);
  22612. /** Draws an image.
  22613. This will draw the whole of an image, positioning its top-left corner at the
  22614. given co-ordinates, and keeping its size the same. This is the simplest image
  22615. drawing method - the others give more control over the scaling and clipping
  22616. of the images.
  22617. Images are composited using the context's current opacity, so if you
  22618. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22619. (or setColour() with an opaque colour) before drawing images.
  22620. */
  22621. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  22622. bool fillAlphaChannelWithCurrentBrush = false) const;
  22623. /** Draws part of an image, rescaling it to fit in a given target region.
  22624. The specified area of the source image is rescaled and drawn to fill the
  22625. specifed destination rectangle.
  22626. Images are composited using the context's current opacity, so if you
  22627. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22628. (or setColour() with an opaque colour) before drawing images.
  22629. @param imageToDraw the image to overlay
  22630. @param destX the left of the destination rectangle
  22631. @param destY the top of the destination rectangle
  22632. @param destWidth the width of the destination rectangle
  22633. @param destHeight the height of the destination rectangle
  22634. @param sourceX the left of the rectangle to copy from the source image
  22635. @param sourceY the top of the rectangle to copy from the source image
  22636. @param sourceWidth the width of the rectangle to copy from the source image
  22637. @param sourceHeight the height of the rectangle to copy from the source image
  22638. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  22639. the source image's alpha channel is used as a mask with
  22640. which to fill the destination using the current colour
  22641. or brush. (If the source is has no alpha channel, then
  22642. it will just fill the target with a solid rectangle)
  22643. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  22644. */
  22645. void drawImage (const Image& imageToDraw,
  22646. int destX, int destY, int destWidth, int destHeight,
  22647. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  22648. bool fillAlphaChannelWithCurrentBrush = false) const;
  22649. /** Draws an image, having applied an affine transform to it.
  22650. This lets you throw the image around in some wacky ways, rotate it, shear,
  22651. scale it, etc.
  22652. Images are composited using the context's current opacity, so if you
  22653. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22654. (or setColour() with an opaque colour) before drawing images.
  22655. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  22656. are ignored and it is filled with the current brush, masked by its alpha channel.
  22657. If you want to render only a subsection of an image, use Image::getClippedImage() to
  22658. create the section that you need.
  22659. @see setImageResamplingQuality, drawImage
  22660. */
  22661. void drawImageTransformed (const Image& imageToDraw,
  22662. const AffineTransform& transform,
  22663. bool fillAlphaChannelWithCurrentBrush = false) const;
  22664. /** Draws an image to fit within a designated rectangle.
  22665. If the image is too big or too small for the space, it will be rescaled
  22666. to fit as nicely as it can do without affecting its aspect ratio. It will
  22667. then be placed within the target rectangle according to the justification flags
  22668. specified.
  22669. @param imageToDraw the source image to draw
  22670. @param destX top-left of the target rectangle to fit it into
  22671. @param destY top-left of the target rectangle to fit it into
  22672. @param destWidth size of the target rectangle to fit the image into
  22673. @param destHeight size of the target rectangle to fit the image into
  22674. @param placementWithinTarget this specifies how the image should be positioned
  22675. within the target rectangle - see the RectanglePlacement
  22676. class for more details about this.
  22677. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  22678. alpha channel will be used as a mask with which to
  22679. draw with the current brush or colour. This is
  22680. similar to fillAlphaMap(), and see also drawImage()
  22681. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  22682. */
  22683. void drawImageWithin (const Image& imageToDraw,
  22684. int destX, int destY, int destWidth, int destHeight,
  22685. const RectanglePlacement& placementWithinTarget,
  22686. bool fillAlphaChannelWithCurrentBrush = false) const;
  22687. /** Returns the position of the bounding box for the current clipping region.
  22688. @see getClipRegion, clipRegionIntersects
  22689. */
  22690. const Rectangle<int> getClipBounds() const;
  22691. /** Checks whether a rectangle overlaps the context's clipping region.
  22692. If this returns false, no part of the given area can be drawn onto, so this
  22693. method can be used to optimise a component's paint() method, by letting it
  22694. avoid drawing complex objects that aren't within the region being repainted.
  22695. */
  22696. bool clipRegionIntersects (const Rectangle<int>& area) const;
  22697. /** Intersects the current clipping region with another region.
  22698. @returns true if the resulting clipping region is non-zero in size
  22699. @see setOrigin, clipRegionIntersects
  22700. */
  22701. bool reduceClipRegion (int x, int y, int width, int height);
  22702. /** Intersects the current clipping region with another region.
  22703. @returns true if the resulting clipping region is non-zero in size
  22704. @see setOrigin, clipRegionIntersects
  22705. */
  22706. bool reduceClipRegion (const Rectangle<int>& area);
  22707. /** Intersects the current clipping region with a rectangle list region.
  22708. @returns true if the resulting clipping region is non-zero in size
  22709. @see setOrigin, clipRegionIntersects
  22710. */
  22711. bool reduceClipRegion (const RectangleList& clipRegion);
  22712. /** Intersects the current clipping region with a path.
  22713. @returns true if the resulting clipping region is non-zero in size
  22714. @see reduceClipRegion
  22715. */
  22716. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  22717. /** Intersects the current clipping region with an image's alpha-channel.
  22718. The current clipping path is intersected with the area covered by this image's
  22719. alpha-channel, after the image has been transformed by the specified matrix.
  22720. @param image the image whose alpha-channel should be used. If the image doesn't
  22721. have an alpha-channel, it is treated as entirely opaque.
  22722. @param transform a matrix to apply to the image
  22723. @returns true if the resulting clipping region is non-zero in size
  22724. @see reduceClipRegion
  22725. */
  22726. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  22727. /** Excludes a rectangle to stop it being drawn into. */
  22728. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  22729. /** Returns true if no drawing can be done because the clip region is zero. */
  22730. bool isClipEmpty() const;
  22731. /** Saves the current graphics state on an internal stack.
  22732. To restore the state, use restoreState().
  22733. @see ScopedSaveState
  22734. */
  22735. void saveState();
  22736. /** Restores a graphics state that was previously saved with saveState().
  22737. @see ScopedSaveState
  22738. */
  22739. void restoreState();
  22740. /** Uses RAII to save and restore the state of a graphics context.
  22741. On construction, this calls Graphics::saveState(), and on destruction it calls
  22742. Graphics::restoreState() on the Graphics object that you supply.
  22743. */
  22744. class ScopedSaveState
  22745. {
  22746. public:
  22747. ScopedSaveState (Graphics& g);
  22748. ~ScopedSaveState();
  22749. private:
  22750. Graphics& context;
  22751. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  22752. };
  22753. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  22754. context with the given opacity.
  22755. The context uses an internal stack of temporary image layers to do this. When you've
  22756. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  22757. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  22758. by a corresponding call to endTransparencyLayer()!
  22759. This call also saves the current state, and endTransparencyLayer() restores it.
  22760. */
  22761. void beginTransparencyLayer (float layerOpacity);
  22762. /** Completes a drawing operation to a temporary semi-transparent buffer.
  22763. See beginTransparencyLayer() for more details.
  22764. */
  22765. void endTransparencyLayer();
  22766. /** Moves the position of the context's origin.
  22767. This changes the position that the context considers to be (0, 0) to
  22768. the specified position.
  22769. So if you call setOrigin (100, 100), then the position that was previously
  22770. referred to as (100, 100) will subsequently be considered to be (0, 0).
  22771. @see reduceClipRegion, addTransform
  22772. */
  22773. void setOrigin (int newOriginX, int newOriginY);
  22774. /** Adds a transformation which will be performed on all the graphics operations that
  22775. the context subsequently performs.
  22776. After calling this, all the coordinates that are passed into the context will be
  22777. transformed by this matrix.
  22778. @see setOrigin
  22779. */
  22780. void addTransform (const AffineTransform& transform);
  22781. /** Resets the current colour, brush, and font to default settings. */
  22782. void resetToDefaultState();
  22783. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22784. bool isVectorDevice() const;
  22785. /** Create a graphics that uses a given low-level renderer.
  22786. For internal use only.
  22787. NB. The context will NOT be deleted by this object when it is deleted.
  22788. */
  22789. Graphics (LowLevelGraphicsContext* internalContext) noexcept;
  22790. /** @internal */
  22791. LowLevelGraphicsContext* getInternalContext() const noexcept { return context; }
  22792. private:
  22793. LowLevelGraphicsContext* const context;
  22794. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22795. bool saveStatePending;
  22796. void saveStateIfPending();
  22797. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22798. };
  22799. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22800. /*** End of inlined file: juce_Graphics.h ***/
  22801. /**
  22802. A graphical effect filter that can be applied to components.
  22803. An ImageEffectFilter can be applied to the image that a component
  22804. paints before it hits the screen.
  22805. This is used for adding effects like shadows, blurs, etc.
  22806. @see Component::setComponentEffect
  22807. */
  22808. class JUCE_API ImageEffectFilter
  22809. {
  22810. public:
  22811. /** Overridden to render the effect.
  22812. The implementation of this method must use the image that is passed in
  22813. as its source, and should render its output to the graphics context passed in.
  22814. @param sourceImage the image that the source component has just rendered with
  22815. its paint() method. The image may or may not have an alpha
  22816. channel, depending on whether the component is opaque.
  22817. @param destContext the graphics context to use to draw the resultant image.
  22818. @param alpha the alpha with which to draw the resultant image to the
  22819. target context
  22820. */
  22821. virtual void applyEffect (Image& sourceImage,
  22822. Graphics& destContext,
  22823. float alpha) = 0;
  22824. /** Destructor. */
  22825. virtual ~ImageEffectFilter() {}
  22826. };
  22827. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22828. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22829. /*** Start of inlined file: juce_Image.h ***/
  22830. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22831. #define __JUCE_IMAGE_JUCEHEADER__
  22832. /**
  22833. Holds a fixed-size bitmap.
  22834. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22835. To draw into an image, create a Graphics object for it.
  22836. e.g. @code
  22837. // create a transparent 500x500 image..
  22838. Image myImage (Image::RGB, 500, 500, true);
  22839. Graphics g (myImage);
  22840. g.setColour (Colours::red);
  22841. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22842. @endcode
  22843. Other useful ways to create an image are with the ImageCache class, or the
  22844. ImageFileFormat, which provides a way to load common image files.
  22845. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22846. */
  22847. class JUCE_API Image
  22848. {
  22849. public:
  22850. /**
  22851. */
  22852. enum PixelFormat
  22853. {
  22854. UnknownFormat,
  22855. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22856. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22857. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22858. };
  22859. /**
  22860. */
  22861. enum ImageType
  22862. {
  22863. SoftwareImage = 0,
  22864. NativeImage
  22865. };
  22866. /** Creates a null image. */
  22867. Image();
  22868. /** Creates an image with a specified size and format.
  22869. @param format the number of colour channels in the image
  22870. @param imageWidth the desired width of the image, in pixels - this value must be
  22871. greater than zero (otherwise a width of 1 will be used)
  22872. @param imageHeight the desired width of the image, in pixels - this value must be
  22873. greater than zero (otherwise a height of 1 will be used)
  22874. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22875. or transparent black (if it's ARGB). If false, the image may contain
  22876. junk initially, so you need to make sure you overwrite it thoroughly.
  22877. @param type the type of image - this lets you specify whether you want a purely
  22878. memory-based image, or one that may be managed by the OS if possible.
  22879. */
  22880. Image (PixelFormat format,
  22881. int imageWidth,
  22882. int imageHeight,
  22883. bool clearImage,
  22884. ImageType type = NativeImage);
  22885. /** Creates a shared reference to another image.
  22886. This won't create a duplicate of the image - when Image objects are copied, they simply
  22887. point to the same shared image data. To make sure that an Image object has its own unique,
  22888. unshared internal data, call duplicateIfShared().
  22889. */
  22890. Image (const Image& other);
  22891. /** Makes this image refer to the same underlying image as another object.
  22892. This won't create a duplicate of the image - when Image objects are copied, they simply
  22893. point to the same shared image data. To make sure that an Image object has its own unique,
  22894. unshared internal data, call duplicateIfShared().
  22895. */
  22896. Image& operator= (const Image&);
  22897. /** Destructor. */
  22898. ~Image();
  22899. /** Returns true if the two images are referring to the same internal, shared image. */
  22900. bool operator== (const Image& other) const noexcept { return image == other.image; }
  22901. /** Returns true if the two images are not referring to the same internal, shared image. */
  22902. bool operator!= (const Image& other) const noexcept { return image != other.image; }
  22903. /** Returns true if this image isn't null.
  22904. If you create an Image with the default constructor, it has no size or content, and is null
  22905. until you reassign it to an Image which contains some actual data.
  22906. The isNull() method is the opposite of isValid().
  22907. @see isNull
  22908. */
  22909. inline bool isValid() const noexcept { return image != nullptr; }
  22910. /** Returns true if this image is not valid.
  22911. If you create an Image with the default constructor, it has no size or content, and is null
  22912. until you reassign it to an Image which contains some actual data.
  22913. The isNull() method is the opposite of isValid().
  22914. @see isValid
  22915. */
  22916. inline bool isNull() const noexcept { return image == nullptr; }
  22917. /** A null Image object that can be used when you need to return an invalid image.
  22918. This object is the equivalient to an Image created with the default constructor.
  22919. */
  22920. static const Image null;
  22921. /** Returns the image's width (in pixels). */
  22922. int getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  22923. /** Returns the image's height (in pixels). */
  22924. int getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  22925. /** Returns a rectangle with the same size as this image.
  22926. The rectangle's origin is always (0, 0).
  22927. */
  22928. const Rectangle<int> getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22929. /** Returns the image's pixel format. */
  22930. PixelFormat getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->format; }
  22931. /** True if the image's format is ARGB. */
  22932. bool isARGB() const noexcept { return getFormat() == ARGB; }
  22933. /** True if the image's format is RGB. */
  22934. bool isRGB() const noexcept { return getFormat() == RGB; }
  22935. /** True if the image's format is a single-channel alpha map. */
  22936. bool isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  22937. /** True if the image contains an alpha-channel. */
  22938. bool hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  22939. /** Clears a section of the image with a given colour.
  22940. This won't do any alpha-blending - it just sets all pixels in the image to
  22941. the given colour (which may be non-opaque if the image has an alpha channel).
  22942. */
  22943. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22944. /** Returns a rescaled version of this image.
  22945. A new image is returned which is a copy of this one, rescaled to the given size.
  22946. Note that if the new size is identical to the existing image, this will just return
  22947. a reference to the original image, and won't actually create a duplicate.
  22948. */
  22949. Image rescaled (int newWidth, int newHeight,
  22950. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22951. /** Returns a version of this image with a different image format.
  22952. A new image is returned which has been converted to the specified format.
  22953. Note that if the new format is no different to the current one, this will just return
  22954. a reference to the original image, and won't actually create a copy.
  22955. */
  22956. Image convertedToFormat (PixelFormat newFormat) const;
  22957. /** Makes sure that no other Image objects share the same underlying data as this one.
  22958. If no other Image objects refer to the same shared data as this one, this method has no
  22959. effect. But if there are other references to the data, this will create a new copy of
  22960. the data internally.
  22961. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22962. affect any other code that may be sharing the same data.
  22963. @see getReferenceCount
  22964. */
  22965. void duplicateIfShared();
  22966. /** Returns an image which refers to a subsection of this image.
  22967. This will not make a copy of the original - the new image will keep a reference to it, so that
  22968. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22969. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22970. you use operator= to make the original Image object refer to something else, the subsection image
  22971. won't pick up this change, it'll remain pointing at the original.
  22972. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22973. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22974. */
  22975. Image getClippedImage (const Rectangle<int>& area) const;
  22976. /** Returns the colour of one of the pixels in the image.
  22977. If the co-ordinates given are beyond the image's boundaries, this will
  22978. return Colours::transparentBlack.
  22979. @see setPixelAt, Image::BitmapData::getPixelColour
  22980. */
  22981. const Colour getPixelAt (int x, int y) const;
  22982. /** Sets the colour of one of the image's pixels.
  22983. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22984. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22985. with the given one. The colour's opacity will be ignored if this image doesn't have
  22986. an alpha-channel.
  22987. @see getPixelAt, Image::BitmapData::setPixelColour
  22988. */
  22989. void setPixelAt (int x, int y, const Colour& colour);
  22990. /** Changes the opacity of a pixel.
  22991. This only has an effect if the image has an alpha channel and if the
  22992. given co-ordinates are inside the image's boundary.
  22993. The multiplier must be in the range 0 to 1.0, and the current alpha
  22994. at the given co-ordinates will be multiplied by this value.
  22995. @see setPixelAt
  22996. */
  22997. void multiplyAlphaAt (int x, int y, float multiplier);
  22998. /** Changes the overall opacity of the image.
  22999. This will multiply the alpha value of each pixel in the image by the given
  23000. amount (limiting the resulting alpha values between 0 and 255). This allows
  23001. you to make an image more or less transparent.
  23002. If the image doesn't have an alpha channel, this won't have any effect.
  23003. */
  23004. void multiplyAllAlphas (float amountToMultiplyBy);
  23005. /** Changes all the colours to be shades of grey, based on their current luminosity.
  23006. */
  23007. void desaturate();
  23008. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  23009. You should only use this class as a last resort - messing about with the internals of
  23010. an image is only recommended for people who really know what they're doing!
  23011. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  23012. hanging around while the image is being used elsewhere.
  23013. Depending on the way the image class is implemented, this may create a temporary buffer
  23014. which is copied back to the image when the object is deleted, or it may just get a pointer
  23015. directly into the image's raw data.
  23016. You can use the stride and data values in this class directly, but don't alter them!
  23017. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  23018. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  23019. */
  23020. class BitmapData
  23021. {
  23022. public:
  23023. enum ReadWriteMode
  23024. {
  23025. readOnly,
  23026. writeOnly,
  23027. readWrite
  23028. };
  23029. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  23030. BitmapData (const Image& image, int x, int y, int w, int h);
  23031. BitmapData (const Image& image, ReadWriteMode mode);
  23032. ~BitmapData();
  23033. /** Returns a pointer to the start of a line in the image.
  23034. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  23035. sure it's not out-of-range.
  23036. */
  23037. inline uint8* getLinePointer (int y) const noexcept { return data + y * lineStride; }
  23038. /** Returns a pointer to a pixel in the image.
  23039. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  23040. not out-of-range.
  23041. */
  23042. inline uint8* getPixelPointer (int x, int y) const noexcept { return data + y * lineStride + x * pixelStride; }
  23043. /** Returns the colour of a given pixel.
  23044. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  23045. repsonsibility to make sure they're within the image's size.
  23046. */
  23047. const Colour getPixelColour (int x, int y) const noexcept;
  23048. /** Sets the colour of a given pixel.
  23049. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  23050. repsonsibility to make sure they're within the image's size.
  23051. */
  23052. void setPixelColour (int x, int y, const Colour& colour) const noexcept;
  23053. uint8* data;
  23054. PixelFormat pixelFormat;
  23055. int lineStride, pixelStride, width, height;
  23056. /** Used internally by custom image types to manage pixel data lifetime. */
  23057. class BitmapDataReleaser
  23058. {
  23059. protected:
  23060. BitmapDataReleaser() {}
  23061. public:
  23062. virtual ~BitmapDataReleaser() {}
  23063. };
  23064. ScopedPointer<BitmapDataReleaser> dataReleaser;
  23065. private:
  23066. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  23067. };
  23068. /** Copies some pixel values to a rectangle of the image.
  23069. The format of the pixel data must match that of the image itself, and the
  23070. rectangle supplied must be within the image's bounds.
  23071. */
  23072. void setPixelData (int destX, int destY, int destW, int destH,
  23073. const uint8* sourcePixelData, int sourceLineStride);
  23074. /** Copies a section of the image to somewhere else within itself. */
  23075. void moveImageSection (int destX, int destY,
  23076. int sourceX, int sourceY,
  23077. int width, int height);
  23078. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  23079. of the image.
  23080. @param result the list that will have the area added to it
  23081. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  23082. above this level will be considered opaque
  23083. */
  23084. void createSolidAreaMask (RectangleList& result,
  23085. float alphaThreshold = 0.5f) const;
  23086. /** Returns a NamedValueSet that is attached to the image and which can be used for
  23087. associating custom values with it.
  23088. If this is a null image, this will return a null pointer.
  23089. */
  23090. NamedValueSet* getProperties() const;
  23091. /** Creates a context suitable for drawing onto this image.
  23092. Don't call this method directly! It's used internally by the Graphics class.
  23093. */
  23094. LowLevelGraphicsContext* createLowLevelContext() const;
  23095. /** Returns the number of Image objects which are currently referring to the same internal
  23096. shared image data.
  23097. @see duplicateIfShared
  23098. */
  23099. int getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getReferenceCount(); }
  23100. /** This is a base class for task-specific types of image.
  23101. Don't use this class directly! It's used internally by the Image class.
  23102. */
  23103. class SharedImage : public ReferenceCountedObject
  23104. {
  23105. public:
  23106. SharedImage (PixelFormat format, int width, int height);
  23107. ~SharedImage();
  23108. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  23109. virtual SharedImage* clone() = 0;
  23110. virtual ImageType getType() const = 0;
  23111. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  23112. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  23113. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  23114. const PixelFormat getPixelFormat() const noexcept { return format; }
  23115. int getWidth() const noexcept { return width; }
  23116. int getHeight() const noexcept { return height; }
  23117. protected:
  23118. friend class Image;
  23119. friend class BitmapData;
  23120. const PixelFormat format;
  23121. const int width, height;
  23122. NamedValueSet userData;
  23123. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  23124. };
  23125. /** @internal */
  23126. SharedImage* getSharedImage() const noexcept { return image; }
  23127. /** @internal */
  23128. explicit Image (SharedImage* instance);
  23129. private:
  23130. friend class SharedImage;
  23131. friend class BitmapData;
  23132. ReferenceCountedObjectPtr<SharedImage> image;
  23133. JUCE_LEAK_DETECTOR (Image);
  23134. };
  23135. #endif // __JUCE_IMAGE_JUCEHEADER__
  23136. /*** End of inlined file: juce_Image.h ***/
  23137. /*** Start of inlined file: juce_RectangleList.h ***/
  23138. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  23139. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  23140. /**
  23141. Maintains a set of rectangles as a complex region.
  23142. This class allows a set of rectangles to be treated as a solid shape, and can
  23143. add and remove rectangular sections of it, and simplify overlapping or
  23144. adjacent rectangles.
  23145. @see Rectangle
  23146. */
  23147. class JUCE_API RectangleList
  23148. {
  23149. public:
  23150. /** Creates an empty RectangleList */
  23151. RectangleList() noexcept;
  23152. /** Creates a copy of another list */
  23153. RectangleList (const RectangleList& other);
  23154. /** Creates a list containing just one rectangle. */
  23155. RectangleList (const Rectangle<int>& rect);
  23156. /** Copies this list from another one. */
  23157. RectangleList& operator= (const RectangleList& other);
  23158. /** Destructor. */
  23159. ~RectangleList();
  23160. /** Returns true if the region is empty. */
  23161. bool isEmpty() const noexcept;
  23162. /** Returns the number of rectangles in the list. */
  23163. int getNumRectangles() const noexcept { return rects.size(); }
  23164. /** Returns one of the rectangles at a particular index.
  23165. @returns the rectangle at the index, or an empty rectangle if the
  23166. index is out-of-range.
  23167. */
  23168. Rectangle<int> getRectangle (int index) const noexcept;
  23169. /** Removes all rectangles to leave an empty region. */
  23170. void clear();
  23171. /** Merges a new rectangle into the list.
  23172. The rectangle being added will first be clipped to remove any parts of it
  23173. that overlap existing rectangles in the list.
  23174. */
  23175. void add (int x, int y, int width, int height);
  23176. /** Merges a new rectangle into the list.
  23177. The rectangle being added will first be clipped to remove any parts of it
  23178. that overlap existing rectangles in the list, and adjacent rectangles will be
  23179. merged into it.
  23180. */
  23181. void add (const Rectangle<int>& rect);
  23182. /** Dumbly adds a rectangle to the list without checking for overlaps.
  23183. This simply adds the rectangle to the end, it doesn't merge it or remove
  23184. any overlapping bits.
  23185. */
  23186. void addWithoutMerging (const Rectangle<int>& rect);
  23187. /** Merges another rectangle list into this one.
  23188. Any overlaps between the two lists will be clipped, so that the result is
  23189. the union of both lists.
  23190. */
  23191. void add (const RectangleList& other);
  23192. /** Removes a rectangular region from the list.
  23193. Any rectangles in the list which overlap this will be clipped and subdivided
  23194. if necessary.
  23195. */
  23196. void subtract (const Rectangle<int>& rect);
  23197. /** Removes all areas in another RectangleList from this one.
  23198. Any rectangles in the list which overlap this will be clipped and subdivided
  23199. if necessary.
  23200. @returns true if the resulting list is non-empty.
  23201. */
  23202. bool subtract (const RectangleList& otherList);
  23203. /** Removes any areas of the region that lie outside a given rectangle.
  23204. Any rectangles in the list which overlap this will be clipped and subdivided
  23205. if necessary.
  23206. Returns true if the resulting region is not empty, false if it is empty.
  23207. @see getIntersectionWith
  23208. */
  23209. bool clipTo (const Rectangle<int>& rect);
  23210. /** Removes any areas of the region that lie outside a given rectangle list.
  23211. Any rectangles in this object which overlap the specified list will be clipped
  23212. and subdivided if necessary.
  23213. Returns true if the resulting region is not empty, false if it is empty.
  23214. @see getIntersectionWith
  23215. */
  23216. bool clipTo (const RectangleList& other);
  23217. /** Creates a region which is the result of clipping this one to a given rectangle.
  23218. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  23219. resulting region into the list whose reference is passed-in.
  23220. Returns true if the resulting region is not empty, false if it is empty.
  23221. @see clipTo
  23222. */
  23223. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  23224. /** Swaps the contents of this and another list.
  23225. This swaps their internal pointers, so is hugely faster than using copy-by-value
  23226. to swap them.
  23227. */
  23228. void swapWith (RectangleList& otherList) noexcept;
  23229. /** Checks whether the region contains a given point.
  23230. @returns true if the point lies within one of the rectangles in the list
  23231. */
  23232. bool containsPoint (int x, int y) const noexcept;
  23233. /** Checks whether the region contains the whole of a given rectangle.
  23234. @returns true all parts of the rectangle passed in lie within the region
  23235. defined by this object
  23236. @see intersectsRectangle, containsPoint
  23237. */
  23238. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  23239. /** Checks whether the region contains any part of a given rectangle.
  23240. @returns true if any part of the rectangle passed in lies within the region
  23241. defined by this object
  23242. @see containsRectangle
  23243. */
  23244. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const noexcept;
  23245. /** Checks whether this region intersects any part of another one.
  23246. @see intersectsRectangle
  23247. */
  23248. bool intersects (const RectangleList& other) const noexcept;
  23249. /** Returns the smallest rectangle that can enclose the whole of this region. */
  23250. Rectangle<int> getBounds() const noexcept;
  23251. /** Optimises the list into a minimum number of constituent rectangles.
  23252. This will try to combine any adjacent rectangles into larger ones where
  23253. possible, to simplify lists that might have been fragmented by repeated
  23254. add/subtract calls.
  23255. */
  23256. void consolidate();
  23257. /** Adds an x and y value to all the co-ordinates. */
  23258. void offsetAll (int dx, int dy) noexcept;
  23259. /** Creates a Path object to represent this region. */
  23260. Path toPath() const;
  23261. /** An iterator for accessing all the rectangles in a RectangleList. */
  23262. class JUCE_API Iterator
  23263. {
  23264. public:
  23265. Iterator (const RectangleList& list) noexcept;
  23266. ~Iterator();
  23267. /** Advances to the next rectangle, and returns true if it's not finished.
  23268. Call this before using getRectangle() to find the rectangle that was returned.
  23269. */
  23270. bool next() noexcept;
  23271. /** Returns the current rectangle. */
  23272. const Rectangle<int>* getRectangle() const noexcept { return current; }
  23273. private:
  23274. const Rectangle<int>* current;
  23275. const RectangleList& owner;
  23276. int index;
  23277. JUCE_DECLARE_NON_COPYABLE (Iterator);
  23278. };
  23279. private:
  23280. friend class Iterator;
  23281. Array <Rectangle<int> > rects;
  23282. JUCE_LEAK_DETECTOR (RectangleList);
  23283. };
  23284. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  23285. /*** End of inlined file: juce_RectangleList.h ***/
  23286. /*** Start of inlined file: juce_BorderSize.h ***/
  23287. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  23288. #define __JUCE_BORDERSIZE_JUCEHEADER__
  23289. /**
  23290. Specifies a set of gaps to be left around the sides of a rectangle.
  23291. This is basically the size of the spaces at the top, bottom, left and right of
  23292. a rectangle. It's used by various component classes to specify borders.
  23293. @see Rectangle
  23294. */
  23295. template <typename ValueType>
  23296. class BorderSize
  23297. {
  23298. public:
  23299. /** Creates a null border.
  23300. All sizes are left as 0.
  23301. */
  23302. BorderSize() noexcept
  23303. : top(), left(), bottom(), right()
  23304. {
  23305. }
  23306. /** Creates a copy of another border. */
  23307. BorderSize (const BorderSize& other) noexcept
  23308. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  23309. {
  23310. }
  23311. /** Creates a border with the given gaps. */
  23312. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) noexcept
  23313. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  23314. {
  23315. }
  23316. /** Creates a border with the given gap on all sides. */
  23317. explicit BorderSize (ValueType allGaps) noexcept
  23318. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  23319. {
  23320. }
  23321. /** Returns the gap that should be left at the top of the region. */
  23322. ValueType getTop() const noexcept { return top; }
  23323. /** Returns the gap that should be left at the top of the region. */
  23324. ValueType getLeft() const noexcept { return left; }
  23325. /** Returns the gap that should be left at the top of the region. */
  23326. ValueType getBottom() const noexcept { return bottom; }
  23327. /** Returns the gap that should be left at the top of the region. */
  23328. ValueType getRight() const noexcept { return right; }
  23329. /** Returns the sum of the top and bottom gaps. */
  23330. ValueType getTopAndBottom() const noexcept { return top + bottom; }
  23331. /** Returns the sum of the left and right gaps. */
  23332. ValueType getLeftAndRight() const noexcept { return left + right; }
  23333. /** Returns true if this border has no thickness along any edge. */
  23334. bool isEmpty() const noexcept { return left + right + top + bottom == ValueType(); }
  23335. /** Changes the top gap. */
  23336. void setTop (ValueType newTopGap) noexcept { top = newTopGap; }
  23337. /** Changes the left gap. */
  23338. void setLeft (ValueType newLeftGap) noexcept { left = newLeftGap; }
  23339. /** Changes the bottom gap. */
  23340. void setBottom (ValueType newBottomGap) noexcept { bottom = newBottomGap; }
  23341. /** Changes the right gap. */
  23342. void setRight (ValueType newRightGap) noexcept { right = newRightGap; }
  23343. /** Returns a rectangle with these borders removed from it. */
  23344. Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const noexcept
  23345. {
  23346. return Rectangle<ValueType> (original.getX() + left,
  23347. original.getY() + top,
  23348. original.getWidth() - (left + right),
  23349. original.getHeight() - (top + bottom));
  23350. }
  23351. /** Removes this border from a given rectangle. */
  23352. void subtractFrom (Rectangle<ValueType>& rectangle) const noexcept
  23353. {
  23354. rectangle = subtractedFrom (rectangle);
  23355. }
  23356. /** Returns a rectangle with these borders added around it. */
  23357. Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const noexcept
  23358. {
  23359. return Rectangle<ValueType> (original.getX() - left,
  23360. original.getY() - top,
  23361. original.getWidth() + (left + right),
  23362. original.getHeight() + (top + bottom));
  23363. }
  23364. /** Adds this border around a given rectangle. */
  23365. void addTo (Rectangle<ValueType>& rectangle) const noexcept
  23366. {
  23367. rectangle = addedTo (rectangle);
  23368. }
  23369. bool operator== (const BorderSize& other) const noexcept
  23370. {
  23371. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  23372. }
  23373. bool operator!= (const BorderSize& other) const noexcept
  23374. {
  23375. return ! operator== (other);
  23376. }
  23377. private:
  23378. ValueType top, left, bottom, right;
  23379. JUCE_LEAK_DETECTOR (BorderSize);
  23380. };
  23381. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  23382. /*** End of inlined file: juce_BorderSize.h ***/
  23383. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  23384. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23385. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23386. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  23387. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23388. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23389. /**
  23390. Classes derived from this will be automatically deleted when the application exits.
  23391. After JUCEApplication::shutdown() has been called, any objects derived from
  23392. DeletedAtShutdown which are still in existence will be deleted in the reverse
  23393. order to that in which they were created.
  23394. So if you've got a singleton and don't want to have to explicitly delete it, just
  23395. inherit from this and it'll be taken care of.
  23396. */
  23397. class JUCE_API DeletedAtShutdown
  23398. {
  23399. protected:
  23400. /** Creates a DeletedAtShutdown object. */
  23401. DeletedAtShutdown();
  23402. /** Destructor.
  23403. It's ok to delete these objects explicitly - it's only the ones left
  23404. dangling at the end that will be deleted automatically.
  23405. */
  23406. virtual ~DeletedAtShutdown();
  23407. public:
  23408. /** Deletes all extant objects.
  23409. This shouldn't be used by applications, as it's called automatically
  23410. in the shutdown code of the JUCEApplication class.
  23411. */
  23412. static void deleteAll();
  23413. private:
  23414. static Array <DeletedAtShutdown*>& getObjects();
  23415. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  23416. };
  23417. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23418. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  23419. /**
  23420. Manages the system's stack of modal components.
  23421. Normally you'll just use the Component methods to invoke modal states in components,
  23422. and won't have to deal with this class directly, but this is the singleton object that's
  23423. used internally to manage the stack.
  23424. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  23425. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  23426. */
  23427. class JUCE_API ModalComponentManager : public AsyncUpdater,
  23428. public DeletedAtShutdown
  23429. {
  23430. public:
  23431. /** Receives callbacks when a modal component is dismissed.
  23432. You can register a callback using Component::enterModalState() or
  23433. ModalComponentManager::attachCallback().
  23434. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  23435. @see ModalCallbackFunction
  23436. */
  23437. class Callback
  23438. {
  23439. public:
  23440. /** */
  23441. Callback() {}
  23442. /** Destructor. */
  23443. virtual ~Callback() {}
  23444. /** Called to indicate that a modal component has been dismissed.
  23445. You can register a callback using Component::enterModalState() or
  23446. ModalComponentManager::attachCallback().
  23447. The returnValue parameter is the value that was passed to Component::exitModalState()
  23448. when the component was dismissed.
  23449. The callback object will be deleted shortly after this method is called.
  23450. */
  23451. virtual void modalStateFinished (int returnValue) = 0;
  23452. };
  23453. /** Returns the number of components currently being shown modally.
  23454. @see getModalComponent
  23455. */
  23456. int getNumModalComponents() const;
  23457. /** Returns one of the components being shown modally.
  23458. An index of 0 is the most recently-shown, topmost component.
  23459. */
  23460. Component* getModalComponent (int index) const;
  23461. /** Returns true if the specified component is in a modal state. */
  23462. bool isModal (Component* component) const;
  23463. /** Returns true if the specified component is currently the topmost modal component. */
  23464. bool isFrontModalComponent (Component* component) const;
  23465. /** Adds a new callback that will be called when the specified modal component is dismissed.
  23466. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  23467. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  23468. called.
  23469. Each component can have any number of callbacks associated with it, and this one is added
  23470. to that list.
  23471. The object that is passed in will be deleted by the manager when it's no longer needed. If
  23472. the given component is not currently modal, the callback object is deleted immediately and
  23473. no action is taken.
  23474. */
  23475. void attachCallback (Component* component, Callback* callback);
  23476. /** Brings any modal components to the front. */
  23477. void bringModalComponentsToFront (bool topOneShouldGrabFocus = true);
  23478. #if JUCE_MODAL_LOOPS_PERMITTED
  23479. /** Runs the event loop until the currently topmost modal component is dismissed, and
  23480. returns the exit code for that component.
  23481. */
  23482. int runEventLoopForCurrentComponent();
  23483. #endif
  23484. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  23485. protected:
  23486. /** Creates a ModalComponentManager.
  23487. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  23488. */
  23489. ModalComponentManager();
  23490. /** Destructor. */
  23491. ~ModalComponentManager();
  23492. /** @internal */
  23493. void handleAsyncUpdate();
  23494. private:
  23495. class ModalItem;
  23496. class ReturnValueRetriever;
  23497. friend class Component;
  23498. friend class OwnedArray <ModalItem>;
  23499. OwnedArray <ModalItem> stack;
  23500. void startModal (Component* component);
  23501. void endModal (Component* component, int returnValue);
  23502. void endModal (Component* component);
  23503. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  23504. };
  23505. /**
  23506. This class provides some handy utility methods for creating ModalComponentManager::Callback
  23507. objects that will invoke a static function with some parameters when a modal component is dismissed.
  23508. */
  23509. class ModalCallbackFunction
  23510. {
  23511. public:
  23512. /** This is a utility function to create a ModalComponentManager::Callback that will
  23513. call a static function with a parameter.
  23514. The function that you supply must take two parameters - the first being an int, which is
  23515. the result code that was used when the modal component was dismissed, and the second
  23516. can be a custom type. Note that this custom value will be copied and stored, so it must
  23517. be a primitive type or a class that provides copy-by-value semantics.
  23518. E.g. @code
  23519. static void myCallbackFunction (int modalResult, double customValue)
  23520. {
  23521. if (modalResult == 1)
  23522. doSomethingWith (customValue);
  23523. }
  23524. Component* someKindOfComp;
  23525. ...
  23526. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  23527. @endcode
  23528. @see ModalComponentManager::Callback
  23529. */
  23530. template <typename ParamType>
  23531. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  23532. ParamType parameterValue)
  23533. {
  23534. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  23535. }
  23536. /** This is a utility function to create a ModalComponentManager::Callback that will
  23537. call a static function with two custom parameters.
  23538. The function that you supply must take three parameters - the first being an int, which is
  23539. the result code that was used when the modal component was dismissed, and the next two are
  23540. your custom types. Note that these custom values will be copied and stored, so they must
  23541. be primitive types or classes that provide copy-by-value semantics.
  23542. E.g. @code
  23543. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  23544. {
  23545. if (modalResult == 1)
  23546. doSomethingWith (customValue1, customValue2);
  23547. }
  23548. Component* someKindOfComp;
  23549. ...
  23550. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  23551. @endcode
  23552. @see ModalComponentManager::Callback
  23553. */
  23554. template <typename ParamType1, typename ParamType2>
  23555. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  23556. ParamType1 parameterValue1,
  23557. ParamType2 parameterValue2)
  23558. {
  23559. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  23560. }
  23561. /** This is a utility function to create a ModalComponentManager::Callback that will
  23562. call a static function with a component.
  23563. The function that you supply must take two parameters - the first being an int, which is
  23564. the result code that was used when the modal component was dismissed, and the second
  23565. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  23566. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  23567. E.g. @code
  23568. static void myCallbackFunction (int modalResult, Slider* mySlider)
  23569. {
  23570. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23571. mySlider->setValue (0.0);
  23572. }
  23573. Component* someKindOfComp;
  23574. Slider* mySlider;
  23575. ...
  23576. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  23577. @endcode
  23578. @see ModalComponentManager::Callback
  23579. */
  23580. template <class ComponentType>
  23581. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  23582. ComponentType* component)
  23583. {
  23584. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  23585. }
  23586. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  23587. The function that you supply must take three parameters - the first being an int, which is
  23588. the result code that was used when the modal component was dismissed, the second being a Component
  23589. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  23590. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  23591. invoked, the pointer that is passed into the function will be null.
  23592. E.g. @code
  23593. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  23594. {
  23595. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23596. mySlider->setName (customParam);
  23597. }
  23598. Component* someKindOfComp;
  23599. Slider* mySlider;
  23600. ...
  23601. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  23602. @endcode
  23603. @see ModalComponentManager::Callback
  23604. */
  23605. template <class ComponentType, typename ParamType>
  23606. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  23607. ComponentType* component,
  23608. ParamType param)
  23609. {
  23610. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  23611. }
  23612. private:
  23613. template <typename ParamType>
  23614. class FunctionCaller1 : public ModalComponentManager::Callback
  23615. {
  23616. public:
  23617. typedef void (*FunctionType) (int, ParamType);
  23618. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  23619. : function (function_), param (param_) {}
  23620. void modalStateFinished (int returnValue) { function (returnValue, param); }
  23621. private:
  23622. const FunctionType function;
  23623. ParamType param;
  23624. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  23625. };
  23626. template <typename ParamType1, typename ParamType2>
  23627. class FunctionCaller2 : public ModalComponentManager::Callback
  23628. {
  23629. public:
  23630. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  23631. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  23632. : function (function_), param1 (param1_), param2 (param2_) {}
  23633. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  23634. private:
  23635. const FunctionType function;
  23636. ParamType1 param1;
  23637. ParamType2 param2;
  23638. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  23639. };
  23640. template <typename ComponentType>
  23641. class ComponentCaller1 : public ModalComponentManager::Callback
  23642. {
  23643. public:
  23644. typedef void (*FunctionType) (int, ComponentType*);
  23645. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  23646. : function (function_), comp (comp_) {}
  23647. void modalStateFinished (int returnValue)
  23648. {
  23649. function (returnValue, static_cast <ComponentType*> (comp.get()));
  23650. }
  23651. private:
  23652. const FunctionType function;
  23653. WeakReference<Component> comp;
  23654. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  23655. };
  23656. template <typename ComponentType, typename ParamType1>
  23657. class ComponentCaller2 : public ModalComponentManager::Callback
  23658. {
  23659. public:
  23660. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  23661. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  23662. : function (function_), comp (comp_), param1 (param1_) {}
  23663. void modalStateFinished (int returnValue)
  23664. {
  23665. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  23666. }
  23667. private:
  23668. const FunctionType function;
  23669. WeakReference<Component> comp;
  23670. ParamType1 param1;
  23671. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  23672. };
  23673. ModalCallbackFunction();
  23674. ~ModalCallbackFunction();
  23675. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  23676. };
  23677. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23678. /*** End of inlined file: juce_ModalComponentManager.h ***/
  23679. class LookAndFeel;
  23680. class MouseInputSource;
  23681. class MouseInputSourceInternal;
  23682. class ComponentPeer;
  23683. class MarkerList;
  23684. class RelativeRectangle;
  23685. /**
  23686. The base class for all JUCE user-interface objects.
  23687. */
  23688. class JUCE_API Component : public MouseListener
  23689. {
  23690. public:
  23691. /** Creates a component.
  23692. To get it to actually appear, you'll also need to:
  23693. - Either add it to a parent component or use the addToDesktop() method to
  23694. make it a desktop window
  23695. - Set its size and position to something sensible
  23696. - Use setVisible() to make it visible
  23697. And for it to serve any useful purpose, you'll need to write a
  23698. subclass of Component or use one of the other types of component from
  23699. the library.
  23700. */
  23701. Component();
  23702. /** Destructor.
  23703. Note that when a component is deleted, any child components it contains are NOT
  23704. automatically deleted. It's your responsibilty to manage their lifespan - you
  23705. may want to use helper methods like deleteAllChildren(), or less haphazard
  23706. approaches like using ScopedPointers or normal object aggregation to manage them.
  23707. If the component being deleted is currently the child of another one, then during
  23708. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  23709. callback. Any ComponentListener objects that have registered with it will also have their
  23710. ComponentListener::componentBeingDeleted() methods called.
  23711. */
  23712. virtual ~Component();
  23713. /** Creates a component, setting its name at the same time.
  23714. @see getName, setName
  23715. */
  23716. explicit Component (const String& componentName);
  23717. /** Returns the name of this component.
  23718. @see setName
  23719. */
  23720. const String& getName() const noexcept { return componentName; }
  23721. /** Sets the name of this component.
  23722. When the name changes, all registered ComponentListeners will receive a
  23723. ComponentListener::componentNameChanged() callback.
  23724. @see getName
  23725. */
  23726. virtual void setName (const String& newName);
  23727. /** Returns the ID string that was set by setComponentID().
  23728. @see setComponentID
  23729. */
  23730. const String& getComponentID() const noexcept { return componentID; }
  23731. /** Sets the component's ID string.
  23732. You can retrieve the ID using getComponentID().
  23733. @see getComponentID
  23734. */
  23735. void setComponentID (const String& newID);
  23736. /** Makes the component visible or invisible.
  23737. This method will show or hide the component.
  23738. Note that components default to being non-visible when first created.
  23739. Also note that visible components won't be seen unless all their parent components
  23740. are also visible.
  23741. This method will call visibilityChanged() and also componentVisibilityChanged()
  23742. for any component listeners that are interested in this component.
  23743. @param shouldBeVisible whether to show or hide the component
  23744. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  23745. */
  23746. virtual void setVisible (bool shouldBeVisible);
  23747. /** Tests whether the component is visible or not.
  23748. this doesn't necessarily tell you whether this comp is actually on the screen
  23749. because this depends on whether all the parent components are also visible - use
  23750. isShowing() to find this out.
  23751. @see isShowing, setVisible
  23752. */
  23753. bool isVisible() const noexcept { return flags.visibleFlag; }
  23754. /** Called when this component's visiblility changes.
  23755. @see setVisible, isVisible
  23756. */
  23757. virtual void visibilityChanged();
  23758. /** Tests whether this component and all its parents are visible.
  23759. @returns true only if this component and all its parents are visible.
  23760. @see isVisible
  23761. */
  23762. bool isShowing() const;
  23763. /** Makes this component appear as a window on the desktop.
  23764. Note that before calling this, you should make sure that the component's opacity is
  23765. set correctly using setOpaque(). If the component is non-opaque, the windowing
  23766. system will try to create a special transparent window for it, which will generally take
  23767. a lot more CPU to operate (and might not even be possible on some platforms).
  23768. If the component is inside a parent component at the time this method is called, it
  23769. will be first be removed from that parent. Likewise if a component on the desktop
  23770. is subsequently added to another component, it'll be removed from the desktop.
  23771. @param windowStyleFlags a combination of the flags specified in the
  23772. ComponentPeer::StyleFlags enum, which define the
  23773. window's characteristics.
  23774. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  23775. in which the juce component should place itself. On Windows,
  23776. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  23777. supported on all platforms, and best left as 0 unless you know
  23778. what you're doing
  23779. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23780. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23781. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23782. */
  23783. virtual void addToDesktop (int windowStyleFlags,
  23784. void* nativeWindowToAttachTo = nullptr);
  23785. /** If the component is currently showing on the desktop, this will hide it.
  23786. You can also use setVisible() to hide a desktop window temporarily, but
  23787. removeFromDesktop() will free any system resources that are being used up.
  23788. @see addToDesktop, isOnDesktop
  23789. */
  23790. void removeFromDesktop();
  23791. /** Returns true if this component is currently showing on the desktop.
  23792. @see addToDesktop, removeFromDesktop
  23793. */
  23794. bool isOnDesktop() const noexcept;
  23795. /** Returns the heavyweight window that contains this component.
  23796. If this component is itself on the desktop, this will return the window
  23797. object that it is using. Otherwise, it will return the window of
  23798. its top-level parent component.
  23799. This may return 0 if there isn't a desktop component.
  23800. @see addToDesktop, isOnDesktop
  23801. */
  23802. ComponentPeer* getPeer() const;
  23803. /** For components on the desktop, this is called if the system wants to close the window.
  23804. This is a signal that either the user or the system wants the window to close. The
  23805. default implementation of this method will trigger an assertion to warn you that your
  23806. component should do something about it, but you can override this to ignore the event
  23807. if you want.
  23808. */
  23809. virtual void userTriedToCloseWindow();
  23810. /** Called for a desktop component which has just been minimised or un-minimised.
  23811. This will only be called for components on the desktop.
  23812. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23813. */
  23814. virtual void minimisationStateChanged (bool isNowMinimised);
  23815. /** Brings the component to the front of its siblings.
  23816. If some of the component's siblings have had their 'always-on-top' flag set,
  23817. then they will still be kept in front of this one (unless of course this
  23818. one is also 'always-on-top').
  23819. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23820. to the component (see grabKeyboardFocus() for more details)
  23821. @see toBack, toBehind, setAlwaysOnTop
  23822. */
  23823. void toFront (bool shouldAlsoGainFocus);
  23824. /** Changes this component's z-order to be at the back of all its siblings.
  23825. If the component is set to be 'always-on-top', it will only be moved to the
  23826. back of the other other 'always-on-top' components.
  23827. @see toFront, toBehind, setAlwaysOnTop
  23828. */
  23829. void toBack();
  23830. /** Changes this component's z-order so that it's just behind another component.
  23831. @see toFront, toBack
  23832. */
  23833. void toBehind (Component* other);
  23834. /** Sets whether the component should always be kept at the front of its siblings.
  23835. @see isAlwaysOnTop
  23836. */
  23837. void setAlwaysOnTop (bool shouldStayOnTop);
  23838. /** Returns true if this component is set to always stay in front of its siblings.
  23839. @see setAlwaysOnTop
  23840. */
  23841. bool isAlwaysOnTop() const noexcept;
  23842. /** Returns the x coordinate of the component's left edge.
  23843. This is a distance in pixels from the left edge of the component's parent.
  23844. Note that if you've used setTransform() to apply a transform, then the component's
  23845. bounds will no longer be a direct reflection of the position at which it appears within
  23846. its parent, as the transform will be applied to its bounding box.
  23847. */
  23848. inline int getX() const noexcept { return bounds.getX(); }
  23849. /** Returns the y coordinate of the top of this component.
  23850. This is a distance in pixels from the top edge of the component's parent.
  23851. Note that if you've used setTransform() to apply a transform, then the component's
  23852. bounds will no longer be a direct reflection of the position at which it appears within
  23853. its parent, as the transform will be applied to its bounding box.
  23854. */
  23855. inline int getY() const noexcept { return bounds.getY(); }
  23856. /** Returns the component's width in pixels. */
  23857. inline int getWidth() const noexcept { return bounds.getWidth(); }
  23858. /** Returns the component's height in pixels. */
  23859. inline int getHeight() const noexcept { return bounds.getHeight(); }
  23860. /** Returns the x coordinate of the component's right-hand edge.
  23861. This is a distance in pixels from the left edge of the component's parent.
  23862. Note that if you've used setTransform() to apply a transform, then the component's
  23863. bounds will no longer be a direct reflection of the position at which it appears within
  23864. its parent, as the transform will be applied to its bounding box.
  23865. */
  23866. int getRight() const noexcept { return bounds.getRight(); }
  23867. /** Returns the component's top-left position as a Point. */
  23868. Point<int> getPosition() const noexcept { return bounds.getPosition(); }
  23869. /** Returns the y coordinate of the bottom edge of this component.
  23870. This is a distance in pixels from the top 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. int getBottom() const noexcept { return bounds.getBottom(); }
  23876. /** Returns this component's bounding box.
  23877. The rectangle returned is relative to the top-left 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. const Rectangle<int>& getBounds() const noexcept { return bounds; }
  23883. /** Returns the component's bounds, relative to its own origin.
  23884. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23885. return a rectangle with position (0, 0), and the same size as this component.
  23886. */
  23887. Rectangle<int> getLocalBounds() const noexcept;
  23888. /** Returns the area of this component's parent which this component covers.
  23889. The returned area is relative to the parent's coordinate space.
  23890. If the component has an affine transform specified, then the resulting area will be
  23891. the smallest rectangle that fully covers the component's transformed bounding box.
  23892. If this component has no parent, the return value will simply be the same as getBounds().
  23893. */
  23894. Rectangle<int> getBoundsInParent() const noexcept;
  23895. /** Returns the region of this component that's not obscured by other, opaque components.
  23896. The RectangleList that is returned represents the area of this component
  23897. which isn't covered by opaque child components.
  23898. If includeSiblings is true, it will also take into account any siblings
  23899. that may be overlapping the component.
  23900. */
  23901. void getVisibleArea (RectangleList& result,
  23902. bool includeSiblings) const;
  23903. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23904. @see getX, localPointToGlobal
  23905. */
  23906. int getScreenX() const;
  23907. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23908. @see getY, localPointToGlobal
  23909. */
  23910. int getScreenY() const;
  23911. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23912. @see getScreenBounds
  23913. */
  23914. Point<int> getScreenPosition() const;
  23915. /** Returns the bounds of this component, relative to the screen's top-left.
  23916. @see getScreenPosition
  23917. */
  23918. Rectangle<int> getScreenBounds() const;
  23919. /** Converts a point to be relative to this component's coordinate space.
  23920. This takes a point relative to a different component, and returns its position relative to this
  23921. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23922. screen coordinate.
  23923. */
  23924. Point<int> getLocalPoint (const Component* sourceComponent,
  23925. const Point<int>& pointRelativeToSourceComponent) const;
  23926. /** Converts a rectangle to be relative to this component's coordinate space.
  23927. This takes a rectangle that is relative to a different component, and returns its position relative
  23928. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23929. a screen coordinate.
  23930. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23931. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23932. the smallest rectangle that fully contains the transformed area.
  23933. */
  23934. Rectangle<int> getLocalArea (const Component* sourceComponent,
  23935. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23936. /** Converts a point relative to this component's top-left into a screen coordinate.
  23937. @see getLocalPoint, localAreaToGlobal
  23938. */
  23939. Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23940. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23941. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23942. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23943. the smallest rectangle that fully contains the transformed area.
  23944. @see getLocalPoint, localPointToGlobal
  23945. */
  23946. Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23947. /** Moves the component to a new position.
  23948. Changes the component's top-left position (without changing its size).
  23949. The position is relative to the top-left of the component's parent.
  23950. If the component actually moves, this method will make a synchronous call to moved().
  23951. Note that if you've used setTransform() to apply a transform, then the component's
  23952. bounds will no longer be a direct reflection of the position at which it appears within
  23953. its parent, as the transform will be applied to whatever bounds you set for it.
  23954. @see setBounds, ComponentListener::componentMovedOrResized
  23955. */
  23956. void setTopLeftPosition (int x, int y);
  23957. /** Moves the component to a new position.
  23958. Changes the position of the component's top-right corner (keeping it the same size).
  23959. The position is relative to the top-left of the component's parent.
  23960. If the component actually moves, this method will make a synchronous call to moved().
  23961. Note that if you've used setTransform() to apply a transform, then the component's
  23962. bounds will no longer be a direct reflection of the position at which it appears within
  23963. its parent, as the transform will be applied to whatever bounds you set for it.
  23964. */
  23965. void setTopRightPosition (int x, int y);
  23966. /** Changes the size of the component.
  23967. A synchronous call to resized() will be occur if the size actually changes.
  23968. Note that if you've used setTransform() to apply a transform, then the component's
  23969. bounds will no longer be a direct reflection of the position at which it appears within
  23970. its parent, as the transform will be applied to whatever bounds you set for it.
  23971. */
  23972. void setSize (int newWidth, int newHeight);
  23973. /** Changes the component's position and size.
  23974. The coordinates are relative to the top-left of the component's parent, or relative
  23975. to the origin of the screen is the component is on the desktop.
  23976. If this method changes the component's top-left position, it will make a synchronous
  23977. call to moved(). If it changes the size, it will also make a call to resized().
  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 setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23982. */
  23983. void setBounds (int x, int y, int width, int height);
  23984. /** Changes the component's position and size.
  23985. The coordinates are relative to the top-left of the component's parent, or relative
  23986. to the origin of the screen is the component is on the desktop.
  23987. If this method changes the component's top-left position, it will make a synchronous
  23988. call to moved(). If it changes the size, it will also make a call to resized().
  23989. Note that if you've used setTransform() to apply a transform, then the component's
  23990. bounds will no longer be a direct reflection of the position at which it appears within
  23991. its parent, as the transform will be applied to whatever bounds you set for it.
  23992. @see setBounds
  23993. */
  23994. void setBounds (const Rectangle<int>& newBounds);
  23995. /** Changes the component's position and size.
  23996. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23997. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23998. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23999. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  24000. for more details.
  24001. When using relative expressions, the following symbols are available:
  24002. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  24003. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  24004. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  24005. the identifier of one of this component's siblings. A component's identifier is set with
  24006. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  24007. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  24008. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  24009. any other component, these values are relative to their component's parent, so "parent.right" won't be
  24010. very useful for positioning a component because it refers to a position with the parent's parent.. but
  24011. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  24012. component which remains 1 pixel away from its parent's bottom-right, you could use
  24013. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  24014. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  24015. used, the parent component must implement its Component::getMarkers() method, and return at least one
  24016. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  24017. marker called "foobar", you'd set it to "foobar + 10".
  24018. See the Expression class for details about the operators that are supported, but for example
  24019. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  24020. you could express it as:
  24021. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  24022. @endcode
  24023. ..or an alternative way to achieve the same thing:
  24024. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  24025. @endcode
  24026. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  24027. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  24028. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  24029. @endcode
  24030. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  24031. be thrown!
  24032. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  24033. */
  24034. void setBounds (const RelativeRectangle& newBounds);
  24035. /** Sets the component's bounds with an expression.
  24036. The string is parsed as a RelativeRectangle expression - see the notes for
  24037. Component::setBounds (const RelativeRectangle&) for more information. This method is
  24038. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  24039. */
  24040. void setBounds (const String& newBoundsExpression);
  24041. /** Changes the component's position and size in terms of fractions of its parent's size.
  24042. The values are factors of the parent's size, so for example
  24043. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  24044. width and height of the parent, with its top-left position 20% of
  24045. the way across and down the parent.
  24046. @see setBounds
  24047. */
  24048. void setBoundsRelative (float proportionalX, float proportionalY,
  24049. float proportionalWidth, float proportionalHeight);
  24050. /** Changes the component's position and size based on the amount of space to leave around it.
  24051. This will position the component within its parent, leaving the specified number of
  24052. pixels around each edge.
  24053. @see setBounds
  24054. */
  24055. void setBoundsInset (const BorderSize<int>& borders);
  24056. /** Positions the component within a given rectangle, keeping its proportions
  24057. unchanged.
  24058. If onlyReduceInSize is false, the component will be resized to fill as much of the
  24059. rectangle as possible without changing its aspect ratio (the component's
  24060. current size is used to determine its aspect ratio, so a zero-size component
  24061. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  24062. too big to fit inside the rectangle.
  24063. It will then be positioned within the rectangle according to the justification flags
  24064. specified.
  24065. @see setBounds
  24066. */
  24067. void setBoundsToFit (int x, int y, int width, int height,
  24068. const Justification& justification,
  24069. bool onlyReduceInSize);
  24070. /** Changes the position of the component's centre.
  24071. Leaves the component's size unchanged, but sets the position of its centre
  24072. relative to its parent's top-left.
  24073. @see setBounds
  24074. */
  24075. void setCentrePosition (int x, int y);
  24076. /** Changes the position of the component's centre.
  24077. Leaves the position unchanged, but positions its centre relative to its
  24078. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  24079. its parent.
  24080. */
  24081. void setCentreRelative (float x, float y);
  24082. /** Changes the component's size and centres it within its parent.
  24083. After changing the size, the component will be moved so that it's
  24084. centred within its parent. If the component is on the desktop (or has no
  24085. parent component), then it'll be centred within the main monitor area.
  24086. */
  24087. void centreWithSize (int width, int height);
  24088. /** Sets a transform matrix to be applied to this component.
  24089. If you set a transform for a component, the component's position will be warped by it, relative to
  24090. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  24091. longer reflect the actual area within the parent that the component covers, as the bounds will be
  24092. transformed and the component will probably end up actually appearing somewhere else within its parent.
  24093. When using transforms you need to be extremely careful when converting coordinates between the
  24094. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  24095. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  24096. convert it between different components (but I'm sure you would never have done that anyway...).
  24097. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  24098. put a component on the desktop.
  24099. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  24100. */
  24101. void setTransform (const AffineTransform& transform);
  24102. /** Returns the transform that is currently being applied to this component.
  24103. For more details about transforms, see setTransform().
  24104. @see setTransform
  24105. */
  24106. AffineTransform getTransform() const;
  24107. /** Returns true if a non-identity transform is being applied to this component.
  24108. For more details about transforms, see setTransform().
  24109. @see setTransform
  24110. */
  24111. bool isTransformed() const noexcept;
  24112. /** Returns a proportion of the component's width.
  24113. This is a handy equivalent of (getWidth() * proportion).
  24114. */
  24115. int proportionOfWidth (float proportion) const noexcept;
  24116. /** Returns a proportion of the component's height.
  24117. This is a handy equivalent of (getHeight() * proportion).
  24118. */
  24119. int proportionOfHeight (float proportion) const noexcept;
  24120. /** Returns the width of the component's parent.
  24121. If the component has no parent (i.e. if it's on the desktop), this will return
  24122. the width of the screen.
  24123. */
  24124. int getParentWidth() const noexcept;
  24125. /** Returns the height of the component's parent.
  24126. If the component has no parent (i.e. if it's on the desktop), this will return
  24127. the height of the screen.
  24128. */
  24129. int getParentHeight() const noexcept;
  24130. /** Returns the screen coordinates of the monitor that contains this component.
  24131. If there's only one monitor, this will return its size - if there are multiple
  24132. monitors, it will return the area of the monitor that contains the component's
  24133. centre.
  24134. */
  24135. Rectangle<int> getParentMonitorArea() const;
  24136. /** Returns the number of child components that this component contains.
  24137. @see getChildComponent, getIndexOfChildComponent
  24138. */
  24139. int getNumChildComponents() const noexcept;
  24140. /** Returns one of this component's child components, by it index.
  24141. The component with index 0 is at the back of the z-order, the one at the
  24142. front will have index (getNumChildComponents() - 1).
  24143. If the index is out-of-range, this will return a null pointer.
  24144. @see getNumChildComponents, getIndexOfChildComponent
  24145. */
  24146. Component* getChildComponent (int index) const noexcept;
  24147. /** Returns the index of this component in the list of child components.
  24148. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  24149. values are further towards the front.
  24150. Returns -1 if the component passed-in is not a child of this component.
  24151. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  24152. */
  24153. int getIndexOfChildComponent (const Component* child) const noexcept;
  24154. /** Adds a child component to this one.
  24155. Adding a child component does not mean that the component will own or delete the child - it's
  24156. your responsibility to delete the component. Note that it's safe to delete a component
  24157. without first removing it from its parent - doing so will automatically remove it and
  24158. send out the appropriate notifications before the deletion completes.
  24159. If the child is already a child of this component, then no action will be taken, and its
  24160. z-order will be left unchanged.
  24161. @param child the new component to add. If the component passed-in is already
  24162. the child of another component, it'll first be removed from it current parent.
  24163. @param zOrder The index in the child-list at which this component should be inserted.
  24164. A value of -1 will insert it in front of the others, 0 is the back.
  24165. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  24166. */
  24167. void addChildComponent (Component* child, int zOrder = -1);
  24168. /** Adds a child component to this one, and also makes the child visible if it isn't.
  24169. Quite a useful function, this is just the same as calling setVisible (true) on the child
  24170. and then addChildComponent(). See addChildComponent() for more details.
  24171. */
  24172. void addAndMakeVisible (Component* child, int zOrder = -1);
  24173. /** Removes one of this component's child-components.
  24174. If the child passed-in isn't actually a child of this component (either because
  24175. it's invalid or is the child of a different parent), then no action is taken.
  24176. Note that removing a child will not delete it! But it's ok to delete a component
  24177. without first removing it - doing so will automatically remove it and send out the
  24178. appropriate notifications before the deletion completes.
  24179. @see addChildComponent, ComponentListener::componentChildrenChanged
  24180. */
  24181. void removeChildComponent (Component* childToRemove);
  24182. /** Removes one of this component's child-components by index.
  24183. This will return a pointer to the component that was removed, or null if
  24184. the index was out-of-range.
  24185. Note that removing a child will not delete it! But it's ok to delete a component
  24186. without first removing it - doing so will automatically remove it and send out the
  24187. appropriate notifications before the deletion completes.
  24188. @see addChildComponent, ComponentListener::componentChildrenChanged
  24189. */
  24190. Component* removeChildComponent (int childIndexToRemove);
  24191. /** Removes all this component's children.
  24192. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  24193. */
  24194. void removeAllChildren();
  24195. /** Removes all this component's children, and deletes them.
  24196. @see removeAllChildren
  24197. */
  24198. void deleteAllChildren();
  24199. /** Returns the component which this component is inside.
  24200. If this is the highest-level component or hasn't yet been added to
  24201. a parent, this will return null.
  24202. */
  24203. Component* getParentComponent() const noexcept { return parentComponent; }
  24204. /** Searches the parent components for a component of a specified class.
  24205. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  24206. component that can be dynamically cast to a MyComp, or will return 0 if none
  24207. of the parents are suitable.
  24208. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  24209. */
  24210. template <class TargetClass>
  24211. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = nullptr) const
  24212. {
  24213. (void) dummyParameter;
  24214. Component* p = parentComponent;
  24215. while (p != nullptr)
  24216. {
  24217. TargetClass* target = dynamic_cast <TargetClass*> (p);
  24218. if (target != nullptr)
  24219. return target;
  24220. p = p->parentComponent;
  24221. }
  24222. return nullptr;
  24223. }
  24224. /** Returns the highest-level component which contains this one or its parents.
  24225. This will search upwards in the parent-hierarchy from this component, until it
  24226. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  24227. not yet added to a parent), and will return that.
  24228. */
  24229. Component* getTopLevelComponent() const noexcept;
  24230. /** Checks whether a component is anywhere inside this component or its children.
  24231. This will recursively check through this component's children to see if the
  24232. given component is anywhere inside.
  24233. */
  24234. bool isParentOf (const Component* possibleChild) const noexcept;
  24235. /** Called to indicate that the component's parents have changed.
  24236. When a component is added or removed from its parent, this method will
  24237. be called on all of its children (recursively - so all children of its
  24238. children will also be called as well).
  24239. Subclasses can override this if they need to react to this in some way.
  24240. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  24241. */
  24242. virtual void parentHierarchyChanged();
  24243. /** Subclasses can use this callback to be told when children are added or removed.
  24244. @see parentHierarchyChanged
  24245. */
  24246. virtual void childrenChanged();
  24247. /** Tests whether a given point inside the component.
  24248. Overriding this method allows you to create components which only intercept
  24249. mouse-clicks within a user-defined area.
  24250. This is called to find out whether a particular x, y coordinate is
  24251. considered to be inside the component or not, and is used by methods such
  24252. as contains() and getComponentAt() to work out which component
  24253. the mouse is clicked on.
  24254. Components with custom shapes will probably want to override it to perform
  24255. some more complex hit-testing.
  24256. The default implementation of this method returns either true or false,
  24257. depending on the value that was set by calling setInterceptsMouseClicks() (true
  24258. is the default return value).
  24259. Note that the hit-test region is not related to the opacity with which
  24260. areas of a component are painted.
  24261. Applications should never call hitTest() directly - instead use the
  24262. contains() method, because this will also test for occlusion by the
  24263. component's parent.
  24264. Note that for components on the desktop, this method will be ignored, because it's
  24265. not always possible to implement this behaviour on all platforms.
  24266. @param x the x coordinate to test, relative to the left hand edge of this
  24267. component. This value is guaranteed to be greater than or equal to
  24268. zero, and less than the component's width
  24269. @param y the y coordinate to test, relative to the top edge of this
  24270. component. This value is guaranteed to be greater than or equal to
  24271. zero, and less than the component's height
  24272. @returns true if the click is considered to be inside the component
  24273. @see setInterceptsMouseClicks, contains
  24274. */
  24275. virtual bool hitTest (int x, int y);
  24276. /** Changes the default return value for the hitTest() method.
  24277. Setting this to false is an easy way to make a component pass its mouse-clicks
  24278. through to the components behind it.
  24279. When a component is created, the default setting for this is true.
  24280. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  24281. return false (or true for child components if allowClicksOnChildComponents
  24282. is true)
  24283. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  24284. components can be clicked on as normal but clicks on this component pass
  24285. straight through; if this is false and allowClicksOnThisComponent
  24286. is false, then neither this component nor any child components can
  24287. be clicked on
  24288. @see hitTest, getInterceptsMouseClicks
  24289. */
  24290. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  24291. bool allowClicksOnChildComponents) noexcept;
  24292. /** Retrieves the current state of the mouse-click interception flags.
  24293. On return, the two parameters are set to the state used in the last call to
  24294. setInterceptsMouseClicks().
  24295. @see setInterceptsMouseClicks
  24296. */
  24297. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  24298. bool& allowsClicksOnChildComponents) const noexcept;
  24299. /** Returns true if a given point lies within this component or one of its children.
  24300. Never override this method! Use hitTest to create custom hit regions.
  24301. @param localPoint the coordinate to test, relative to this component's top-left.
  24302. @returns true if the point is within the component's hit-test area, but only if
  24303. that part of the component isn't clipped by its parent component. Note
  24304. that this won't take into account any overlapping sibling components
  24305. which might be in the way - for that, see reallyContains()
  24306. @see hitTest, reallyContains, getComponentAt
  24307. */
  24308. bool contains (const Point<int>& localPoint);
  24309. /** Returns true if a given point lies in this component, taking any overlapping
  24310. siblings into account.
  24311. @param localPoint the coordinate to test, relative to this component's top-left.
  24312. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  24313. this determines whether that is counted as a hit.
  24314. @see contains, getComponentAt
  24315. */
  24316. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  24317. /** Returns the component at a certain point within this one.
  24318. @param x the x coordinate to test, relative to this component's left edge.
  24319. @param y the y coordinate to test, relative to this component's top edge.
  24320. @returns the component that is at this position - which may be 0, this component,
  24321. or one of its children. Note that overlapping siblings that might actually
  24322. be in the way are not taken into account by this method - to account for these,
  24323. instead call getComponentAt on the top-level parent of this component.
  24324. @see hitTest, contains, reallyContains
  24325. */
  24326. Component* getComponentAt (int x, int y);
  24327. /** Returns the component at a certain point within this one.
  24328. @param position the coordinate to test, relative to this component's top-left.
  24329. @returns the component that is at this position - which may be 0, this component,
  24330. or one of its children. Note that overlapping siblings that might actually
  24331. be in the way are not taken into account by this method - to account for these,
  24332. instead call getComponentAt on the top-level parent of this component.
  24333. @see hitTest, contains, reallyContains
  24334. */
  24335. Component* getComponentAt (const Point<int>& position);
  24336. /** Marks the whole component as needing to be redrawn.
  24337. Calling this will not do any repainting immediately, but will mark the component
  24338. as 'dirty'. At some point in the near future the operating system will send a paint
  24339. message, which will redraw all the dirty regions of all components.
  24340. There's no guarantee about how soon after calling repaint() the redraw will actually
  24341. happen, and other queued events may be delivered before a redraw is done.
  24342. If the setBufferedToImage() method has been used to cause this component
  24343. to use a buffer, the repaint() call will invalidate the component's buffer.
  24344. To redraw just a subsection of the component rather than the whole thing,
  24345. use the repaint (int, int, int, int) method.
  24346. @see paint
  24347. */
  24348. void repaint();
  24349. /** Marks a subsection of this component as needing to be redrawn.
  24350. Calling this will not do any repainting immediately, but will mark the given region
  24351. of the component as 'dirty'. At some point in the near future the operating system
  24352. will send a paint message, which will redraw all the dirty regions of all components.
  24353. There's no guarantee about how soon after calling repaint() the redraw will actually
  24354. happen, and other queued events may be delivered before a redraw is done.
  24355. The region that is passed in will be clipped to keep it within the bounds of this
  24356. component.
  24357. @see repaint()
  24358. */
  24359. void repaint (int x, int y, int width, int height);
  24360. /** Marks a subsection of this component as needing to be redrawn.
  24361. Calling this will not do any repainting immediately, but will mark the given region
  24362. of the component as 'dirty'. At some point in the near future the operating system
  24363. will send a paint message, which will redraw all the dirty regions of all components.
  24364. There's no guarantee about how soon after calling repaint() the redraw will actually
  24365. happen, and other queued events may be delivered before a redraw is done.
  24366. The region that is passed in will be clipped to keep it within the bounds of this
  24367. component.
  24368. @see repaint()
  24369. */
  24370. void repaint (const Rectangle<int>& area);
  24371. /** Makes the component use an internal buffer to optimise its redrawing.
  24372. Setting this flag to true will cause the component to allocate an
  24373. internal buffer into which it paints itself, so that when asked to
  24374. redraw itself, it can use this buffer rather than actually calling the
  24375. paint() method.
  24376. The buffer is kept until the repaint() method is called directly on
  24377. this component (or until it is resized), when the image is invalidated
  24378. and then redrawn the next time the component is painted.
  24379. Note that only the drawing that happens within the component's paint()
  24380. method is drawn into the buffer, it's child components are not buffered, and
  24381. nor is the paintOverChildren() method.
  24382. @see repaint, paint, createComponentSnapshot
  24383. */
  24384. void setBufferedToImage (bool shouldBeBuffered);
  24385. /** Generates a snapshot of part of this component.
  24386. This will return a new Image, the size of the rectangle specified,
  24387. containing a snapshot of the specified area of the component and all
  24388. its children.
  24389. The image may or may not have an alpha-channel, depending on whether the
  24390. image is opaque or not.
  24391. If the clipImageToComponentBounds parameter is true and the area is greater than
  24392. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  24393. then parts of the component beyond its bounds can be drawn.
  24394. @see paintEntireComponent
  24395. */
  24396. Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  24397. bool clipImageToComponentBounds = true);
  24398. /** Draws this component and all its subcomponents onto the specified graphics
  24399. context.
  24400. You should very rarely have to use this method, it's simply there in case you need
  24401. to draw a component with a custom graphics context for some reason, e.g. for
  24402. creating a snapshot of the component.
  24403. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  24404. on its children in order to render the entire tree.
  24405. The graphics context may be left in an undefined state after this method returns,
  24406. so you may need to reset it if you're going to use it again.
  24407. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  24408. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  24409. an alpha of 1.0 will be used.
  24410. */
  24411. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  24412. /** This allows you to indicate that this component doesn't require its graphics
  24413. context to be clipped when it is being painted.
  24414. Most people will never need to use this setting, but in situations where you have a very large
  24415. number of simple components being rendered, and where they are guaranteed never to do any drawing
  24416. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  24417. the graphics context that gets passed to the component's paint() callback.
  24418. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  24419. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  24420. artifacts. Your component also can't have any child components that may be placed beyond its
  24421. bounds.
  24422. */
  24423. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept;
  24424. /** Adds an effect filter to alter the component's appearance.
  24425. When a component has an effect filter set, then this is applied to the
  24426. results of its paint() method. There are a few preset effects, such as
  24427. a drop-shadow or glow, but they can be user-defined as well.
  24428. The effect that is passed in will not be deleted by the component - the
  24429. caller must take care of deleting it.
  24430. To remove an effect from a component, pass a null pointer in as the parameter.
  24431. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  24432. */
  24433. void setComponentEffect (ImageEffectFilter* newEffect);
  24434. /** Returns the current component effect.
  24435. @see setComponentEffect
  24436. */
  24437. ImageEffectFilter* getComponentEffect() const noexcept { return effect; }
  24438. /** Finds the appropriate look-and-feel to use for this component.
  24439. If the component hasn't had a look-and-feel explicitly set, this will
  24440. return the parent's look-and-feel, or just the default one if there's no
  24441. parent.
  24442. @see setLookAndFeel, lookAndFeelChanged
  24443. */
  24444. LookAndFeel& getLookAndFeel() const noexcept;
  24445. /** Sets the look and feel to use for this component.
  24446. This will also change the look and feel for any child components that haven't
  24447. had their look set explicitly.
  24448. The object passed in will not be deleted by the component, so it's the caller's
  24449. responsibility to manage it. It may be used at any time until this component
  24450. has been deleted.
  24451. Calling this method will also invoke the sendLookAndFeelChange() method.
  24452. @see getLookAndFeel, lookAndFeelChanged
  24453. */
  24454. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  24455. /** Called to let the component react to a change in the look-and-feel setting.
  24456. When the look-and-feel is changed for a component, this will be called in
  24457. all its child components, recursively.
  24458. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  24459. an application uses a LookAndFeel class that might have changed internally.
  24460. @see sendLookAndFeelChange, getLookAndFeel
  24461. */
  24462. virtual void lookAndFeelChanged();
  24463. /** Calls the lookAndFeelChanged() method in this component and all its children.
  24464. This will recurse through the children and their children, calling lookAndFeelChanged()
  24465. on them all.
  24466. @see lookAndFeelChanged
  24467. */
  24468. void sendLookAndFeelChange();
  24469. /** Indicates whether any parts of the component might be transparent.
  24470. Components that always paint all of their contents with solid colour and
  24471. thus completely cover any components behind them should use this method
  24472. to tell the repaint system that they are opaque.
  24473. This information is used to optimise drawing, because it means that
  24474. objects underneath opaque windows don't need to be painted.
  24475. By default, components are considered transparent, unless this is used to
  24476. make it otherwise.
  24477. @see isOpaque, getVisibleArea
  24478. */
  24479. void setOpaque (bool shouldBeOpaque);
  24480. /** Returns true if no parts of this component are transparent.
  24481. @returns the value that was set by setOpaque, (the default being false)
  24482. @see setOpaque
  24483. */
  24484. bool isOpaque() const noexcept;
  24485. /** Indicates whether the component should be brought to the front when clicked.
  24486. Setting this flag to true will cause the component to be brought to the front
  24487. when the mouse is clicked somewhere inside it or its child components.
  24488. Note that a top-level desktop window might still be brought to the front by the
  24489. operating system when it's clicked, depending on how the OS works.
  24490. By default this is set to false.
  24491. @see setMouseClickGrabsKeyboardFocus
  24492. */
  24493. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept;
  24494. /** Indicates whether the component should be brought to the front when clicked-on.
  24495. @see setBroughtToFrontOnMouseClick
  24496. */
  24497. bool isBroughtToFrontOnMouseClick() const noexcept;
  24498. // Keyboard focus methods
  24499. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  24500. By default components aren't actually interested in gaining the
  24501. focus, but this method can be used to turn this on.
  24502. See the grabKeyboardFocus() method for details about the way a component
  24503. is chosen to receive the focus.
  24504. @see grabKeyboardFocus, getWantsKeyboardFocus
  24505. */
  24506. void setWantsKeyboardFocus (bool wantsFocus) noexcept;
  24507. /** Returns true if the component is interested in getting keyboard focus.
  24508. This returns the flag set by setWantsKeyboardFocus(). The default
  24509. setting is false.
  24510. @see setWantsKeyboardFocus
  24511. */
  24512. bool getWantsKeyboardFocus() const noexcept;
  24513. /** Chooses whether a click on this component automatically grabs the focus.
  24514. By default this is set to true, but you might want a component which can
  24515. be focused, but where you don't want the user to be able to affect it directly
  24516. by clicking.
  24517. */
  24518. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  24519. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  24520. See setMouseClickGrabsKeyboardFocus() for more info.
  24521. */
  24522. bool getMouseClickGrabsKeyboardFocus() const noexcept;
  24523. /** Tries to give keyboard focus to this component.
  24524. When the user clicks on a component or its grabKeyboardFocus()
  24525. method is called, the following procedure is used to work out which
  24526. component should get it:
  24527. - if the component that was clicked on actually wants focus (as indicated
  24528. by calling getWantsKeyboardFocus), it gets it.
  24529. - if the component itself doesn't want focus, it will try to pass it
  24530. on to whichever of its children is the default component, as determined by
  24531. KeyboardFocusTraverser::getDefaultComponent()
  24532. - if none of its children want focus at all, it will pass it up to its
  24533. parent instead, unless it's a top-level component without a parent,
  24534. in which case it just takes the focus itself.
  24535. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  24536. getCurrentlyFocusedComponent, focusGained, focusLost,
  24537. keyPressed, keyStateChanged
  24538. */
  24539. void grabKeyboardFocus();
  24540. /** Returns true if this component currently has the keyboard focus.
  24541. @param trueIfChildIsFocused if this is true, then the method returns true if
  24542. either this component or any of its children (recursively)
  24543. have the focus. If false, the method only returns true if
  24544. this component has the focus.
  24545. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  24546. focusGained, focusLost
  24547. */
  24548. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  24549. /** Returns the component that currently has the keyboard focus.
  24550. @returns the focused component, or null if nothing is focused.
  24551. */
  24552. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() noexcept;
  24553. /** Tries to move the keyboard focus to one of this component's siblings.
  24554. This will try to move focus to either the next or previous component. (This
  24555. is the method that is used when shifting focus by pressing the tab key).
  24556. Components for which getWantsKeyboardFocus() returns false are not looked at.
  24557. @param moveToNext if true, the focus will move forwards; if false, it will
  24558. move backwards
  24559. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  24560. */
  24561. void moveKeyboardFocusToSibling (bool moveToNext);
  24562. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  24563. which focus should be passed from this component.
  24564. The default implementation of this method will return a default
  24565. KeyboardFocusTraverser if this component is a focus container (as determined
  24566. by the setFocusContainer() method). If the component isn't a focus
  24567. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  24568. If you overrride this to return a custom KeyboardFocusTraverser, then
  24569. this component and all its sub-components will use the new object to
  24570. make their focusing decisions.
  24571. The method should return a new object, which the caller is required to
  24572. delete when no longer needed.
  24573. */
  24574. virtual KeyboardFocusTraverser* createFocusTraverser();
  24575. /** Returns the focus order of this component, if one has been specified.
  24576. By default components don't have a focus order - in that case, this
  24577. will return 0. Lower numbers indicate that the component will be
  24578. earlier in the focus traversal order.
  24579. To change the order, call setExplicitFocusOrder().
  24580. The focus order may be used by the KeyboardFocusTraverser class as part of
  24581. its algorithm for deciding the order in which components should be traversed.
  24582. See the KeyboardFocusTraverser class for more details on this.
  24583. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  24584. */
  24585. int getExplicitFocusOrder() const;
  24586. /** Sets the index used in determining the order in which focusable components
  24587. should be traversed.
  24588. A value of 0 or less is taken to mean that no explicit order is wanted, and
  24589. that traversal should use other factors, like the component's position.
  24590. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  24591. */
  24592. void setExplicitFocusOrder (int newFocusOrderIndex);
  24593. /** Indicates whether this component is a parent for components that can have
  24594. their focus traversed.
  24595. This flag is used by the default implementation of the createFocusTraverser()
  24596. method, which uses the flag to find the first parent component (of the currently
  24597. focused one) which wants to be a focus container.
  24598. So using this method to set the flag to 'true' causes this component to
  24599. act as the top level within which focus is passed around.
  24600. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  24601. */
  24602. void setFocusContainer (bool shouldBeFocusContainer) noexcept;
  24603. /** Returns true if this component has been marked as a focus container.
  24604. See setFocusContainer() for more details.
  24605. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  24606. */
  24607. bool isFocusContainer() const noexcept;
  24608. /** Returns true if the component (and all its parents) are enabled.
  24609. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  24610. what difference this makes to the component depends on the type. E.g. buttons
  24611. and sliders will choose to draw themselves differently, etc.
  24612. Note that if one of this component's parents is disabled, this will always
  24613. return false, even if this component itself is enabled.
  24614. @see setEnabled, enablementChanged
  24615. */
  24616. bool isEnabled() const noexcept;
  24617. /** Enables or disables this component.
  24618. Disabling a component will also cause all of its child components to become
  24619. disabled.
  24620. Similarly, enabling a component which is inside a disabled parent
  24621. component won't make any difference until the parent is re-enabled.
  24622. @see isEnabled, enablementChanged
  24623. */
  24624. void setEnabled (bool shouldBeEnabled);
  24625. /** Callback to indicate that this component has been enabled or disabled.
  24626. This can be triggered by one of the component's parent components
  24627. being enabled or disabled, as well as changes to the component itself.
  24628. The default implementation of this method does nothing; your class may
  24629. wish to repaint itself or something when this happens.
  24630. @see setEnabled, isEnabled
  24631. */
  24632. virtual void enablementChanged();
  24633. /** Changes the transparency of this component.
  24634. When painted, the entire component and all its children will be rendered
  24635. with this as the overall opacity level, where 0 is completely invisible, and
  24636. 1.0 is fully opaque (i.e. normal).
  24637. @see getAlpha
  24638. */
  24639. void setAlpha (float newAlpha);
  24640. /** Returns the component's current transparancy level.
  24641. See setAlpha() for more details.
  24642. */
  24643. float getAlpha() const;
  24644. /** Changes the mouse cursor shape to use when the mouse is over this component.
  24645. Note that the cursor set by this method can be overridden by the getMouseCursor
  24646. method.
  24647. @see MouseCursor
  24648. */
  24649. void setMouseCursor (const MouseCursor& cursorType);
  24650. /** Returns the mouse cursor shape to use when the mouse is over this component.
  24651. The default implementation will return the cursor that was set by setCursor()
  24652. but can be overridden for more specialised purposes, e.g. returning different
  24653. cursors depending on the mouse position.
  24654. @see MouseCursor
  24655. */
  24656. virtual const MouseCursor getMouseCursor();
  24657. /** Forces the current mouse cursor to be updated.
  24658. If you're overriding the getMouseCursor() method to control which cursor is
  24659. displayed, then this will only be checked each time the user moves the mouse. So
  24660. if you want to force the system to check that the cursor being displayed is
  24661. up-to-date (even if the mouse is just sitting there), call this method.
  24662. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  24663. calling this).
  24664. */
  24665. void updateMouseCursor() const;
  24666. /** Components can override this method to draw their content.
  24667. The paint() method gets called when a region of a component needs redrawing,
  24668. either because the component's repaint() method has been called, or because
  24669. something has happened on the screen that means a section of a window needs
  24670. to be redrawn.
  24671. Any child components will draw themselves over whatever this method draws. If
  24672. you need to paint over the top of your child components, you can also implement
  24673. the paintOverChildren() method to do this.
  24674. If you want to cause a component to redraw itself, this is done asynchronously -
  24675. calling the repaint() method marks a region of the component as "dirty", and the
  24676. paint() method will automatically be called sometime later, by the message thread,
  24677. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  24678. you never redraw something synchronously.
  24679. You should never need to call this method directly - to take a snapshot of the
  24680. component you could use createComponentSnapshot() or paintEntireComponent().
  24681. @param g the graphics context that must be used to do the drawing operations.
  24682. @see repaint, paintOverChildren, Graphics
  24683. */
  24684. virtual void paint (Graphics& g);
  24685. /** Components can override this method to draw over the top of their children.
  24686. For most drawing operations, it's better to use the normal paint() method,
  24687. but if you need to overlay something on top of the children, this can be
  24688. used.
  24689. @see paint, Graphics
  24690. */
  24691. virtual void paintOverChildren (Graphics& g);
  24692. /** Called when the mouse moves inside this component.
  24693. If the mouse button isn't pressed and the mouse moves over a component,
  24694. this will be called to let the component react to this.
  24695. A component will always get a mouseEnter callback before a mouseMove.
  24696. @param e details about the position and status of the mouse event
  24697. @see mouseEnter, mouseExit, mouseDrag, contains
  24698. */
  24699. virtual void mouseMove (const MouseEvent& e);
  24700. /** Called when the mouse first enters this component.
  24701. If the mouse button isn't pressed and the mouse moves into a component,
  24702. this will be called to let the component react to this.
  24703. When the mouse button is pressed and held down while being moved in
  24704. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  24705. mouseDrag messages are sent to the component that the mouse was originally
  24706. clicked on, until the button is released.
  24707. If you're writing a component that needs to repaint itself when the mouse
  24708. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24709. method.
  24710. @param e details about the position and status of the mouse event
  24711. @see mouseExit, mouseDrag, mouseMove, contains
  24712. */
  24713. virtual void mouseEnter (const MouseEvent& e);
  24714. /** Called when the mouse moves out of this component.
  24715. This will be called when the mouse moves off the edge of this
  24716. component.
  24717. If the mouse button was pressed, and it was then dragged off the
  24718. edge of the component and released, then this callback will happen
  24719. when the button is released, after the mouseUp callback.
  24720. If you're writing a component that needs to repaint itself when the mouse
  24721. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24722. method.
  24723. @param e details about the position and status of the mouse event
  24724. @see mouseEnter, mouseDrag, mouseMove, contains
  24725. */
  24726. virtual void mouseExit (const MouseEvent& e);
  24727. /** Called when a mouse button is pressed while it's over this component.
  24728. The MouseEvent object passed in contains lots of methods for finding out
  24729. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24730. were held down at the time.
  24731. Once a button is held down, the mouseDrag method will be called when the
  24732. mouse moves, until the button is released.
  24733. @param e details about the position and status of the mouse event
  24734. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  24735. */
  24736. virtual void mouseDown (const MouseEvent& e);
  24737. /** Called when the mouse is moved while a button is held down.
  24738. When a mouse button is pressed inside a component, that component
  24739. receives mouseDrag callbacks each time the mouse moves, even if the
  24740. mouse strays outside the component's bounds.
  24741. If you want to be able to drag things off the edge of a component
  24742. and have the component scroll when you get to the edges, the
  24743. beginDragAutoRepeat() method might be useful.
  24744. @param e details about the position and status of the mouse event
  24745. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  24746. */
  24747. virtual void mouseDrag (const MouseEvent& e);
  24748. /** Called when a mouse button is released.
  24749. A mouseUp callback is sent to the component in which a button was pressed
  24750. even if the mouse is actually over a different component when the
  24751. button is released.
  24752. The MouseEvent object passed in contains lots of methods for finding out
  24753. which buttons were down just before they were released.
  24754. @param e details about the position and status of the mouse event
  24755. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  24756. */
  24757. virtual void mouseUp (const MouseEvent& e);
  24758. /** Called when a mouse button has been double-clicked in this component.
  24759. The MouseEvent object passed in contains lots of methods for finding out
  24760. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24761. were held down at the time.
  24762. For altering the time limit used to detect double-clicks,
  24763. see MouseEvent::setDoubleClickTimeout.
  24764. @param e details about the position and status of the mouse event
  24765. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  24766. MouseEvent::getDoubleClickTimeout
  24767. */
  24768. virtual void mouseDoubleClick (const MouseEvent& e);
  24769. /** Called when the mouse-wheel is moved.
  24770. This callback is sent to the component that the mouse is over when the
  24771. wheel is moved.
  24772. If not overridden, the component will forward this message to its parent, so
  24773. that parent components can collect mouse-wheel messages that happen to
  24774. child components which aren't interested in them.
  24775. @param e details about the position and status of the mouse event
  24776. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  24777. value means the wheel has been pushed to the right, negative means it
  24778. was pushed to the left
  24779. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24780. value means the wheel has been pushed upwards, negative means it
  24781. was pushed downwards
  24782. */
  24783. virtual void mouseWheelMove (const MouseEvent& e,
  24784. float wheelIncrementX,
  24785. float wheelIncrementY);
  24786. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24787. current mouse-drag operation.
  24788. This allows you to make sure that mouseDrag() events are sent continuously, even
  24789. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24790. components when the mouse is near an edge.
  24791. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24792. minimum interval between consecutive mouse drag callbacks. The callbacks
  24793. will continue until the mouse is released, and then the interval will be reset,
  24794. so you need to make sure it's called every time you begin a drag event.
  24795. Passing an interval of 0 or less will cancel the auto-repeat.
  24796. @see mouseDrag, Desktop::beginDragAutoRepeat
  24797. */
  24798. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24799. /** Causes automatic repaints when the mouse enters or exits this component.
  24800. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24801. on the component, it will trigger a repaint.
  24802. This is handy for things like buttons that need to draw themselves differently when
  24803. the mouse moves over them, and it avoids having to override all the different mouse
  24804. callbacks and call repaint().
  24805. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24806. */
  24807. void setRepaintsOnMouseActivity (bool shouldRepaint) noexcept;
  24808. /** Registers a listener to be told when mouse events occur in this component.
  24809. If you need to get informed about mouse events in a component but can't or
  24810. don't want to override its methods, you can attach any number of listeners
  24811. to the component, and these will get told about the events in addition to
  24812. the component's own callbacks being called.
  24813. Note that a MouseListener can also be attached to more than one component.
  24814. @param newListener the listener to register
  24815. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24816. for events that happen to any child component
  24817. within this component, including deeply-nested
  24818. child components. If false, it will only be
  24819. told about events that this component handles.
  24820. @see MouseListener, removeMouseListener
  24821. */
  24822. void addMouseListener (MouseListener* newListener,
  24823. bool wantsEventsForAllNestedChildComponents);
  24824. /** Deregisters a mouse listener.
  24825. @see addMouseListener, MouseListener
  24826. */
  24827. void removeMouseListener (MouseListener* listenerToRemove);
  24828. /** Adds a listener that wants to hear about keypresses that this component receives.
  24829. The listeners that are registered with a component are called by its keyPressed() or
  24830. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24831. If you add an object as a key listener, be careful to remove it when the object
  24832. is deleted, or the component will be left with a dangling pointer.
  24833. @see keyPressed, keyStateChanged, removeKeyListener
  24834. */
  24835. void addKeyListener (KeyListener* newListener);
  24836. /** Removes a previously-registered key listener.
  24837. @see addKeyListener
  24838. */
  24839. void removeKeyListener (KeyListener* listenerToRemove);
  24840. /** Called when a key is pressed.
  24841. When a key is pressed, the component that has the keyboard focus will have this
  24842. method called. Remember that a component will only be given the focus if its
  24843. setWantsKeyboardFocus() method has been used to enable this.
  24844. If your implementation returns true, the event will be consumed and not passed
  24845. on to any other listeners. If it returns false, the key will be passed to any
  24846. KeyListeners that have been registered with this component. As soon as one of these
  24847. returns true, the process will stop, but if they all return false, the event will
  24848. be passed upwards to this component's parent, and so on.
  24849. The default implementation of this method does nothing and returns false.
  24850. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24851. */
  24852. virtual bool keyPressed (const KeyPress& key);
  24853. /** Called when a key is pressed or released.
  24854. Whenever a key on the keyboard is pressed or released (including modifier keys
  24855. like shift and ctrl), this method will be called on the component that currently
  24856. has the keyboard focus. Remember that a component will only be given the focus if
  24857. its setWantsKeyboardFocus() method has been used to enable this.
  24858. If your implementation returns true, the event will be consumed and not passed
  24859. on to any other listeners. If it returns false, then any KeyListeners that have
  24860. been registered with this component will have their keyStateChanged methods called.
  24861. As soon as one of these returns true, the process will stop, but if they all return
  24862. false, the event will be passed upwards to this component's parent, and so on.
  24863. The default implementation of this method does nothing and returns false.
  24864. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24865. method.
  24866. @param isKeyDown true if a key has been pressed; false if it has been released
  24867. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24868. */
  24869. virtual bool keyStateChanged (bool isKeyDown);
  24870. /** Called when a modifier key is pressed or released.
  24871. Whenever the shift, control, alt or command keys are pressed or released,
  24872. this method will be called on the component that currently has the keyboard focus.
  24873. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24874. method has been used to enable this.
  24875. The default implementation of this method actually calls its parent's modifierKeysChanged
  24876. method, so that focused components which aren't interested in this will give their
  24877. parents a chance to act on the event instead.
  24878. @see keyStateChanged, ModifierKeys
  24879. */
  24880. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24881. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24882. enum FocusChangeType
  24883. {
  24884. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24885. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24886. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24887. };
  24888. /** Called to indicate that this component has just acquired the keyboard focus.
  24889. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24890. */
  24891. virtual void focusGained (FocusChangeType cause);
  24892. /** Called to indicate that this component has just lost the keyboard focus.
  24893. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24894. */
  24895. virtual void focusLost (FocusChangeType cause);
  24896. /** Called to indicate that one of this component's children has been focused or unfocused.
  24897. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24898. changed. It happens when focus moves from one of this component's children (at any depth)
  24899. to a component that isn't contained in this one, (or vice-versa).
  24900. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24901. */
  24902. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24903. /** Returns true if the mouse is currently over this component.
  24904. If the mouse isn't over the component, this will return false, even if the
  24905. mouse is currently being dragged - so you can use this in your mouseDrag
  24906. method to find out whether it's really over the component or not.
  24907. Note that when the mouse button is being held down, then the only component
  24908. for which this method will return true is the one that was originally
  24909. clicked on.
  24910. If includeChildren is true, then this will also return true if the mouse is over
  24911. any of the component's children (recursively) as well as the component itself.
  24912. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24913. */
  24914. bool isMouseOver (bool includeChildren = false) const;
  24915. /** Returns true if the mouse button is currently held down in this component.
  24916. Note that this is a test to see whether the mouse is being pressed in this
  24917. component, so it'll return false if called on component A when the mouse
  24918. is actually being dragged in component B.
  24919. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24920. */
  24921. bool isMouseButtonDown() const noexcept;
  24922. /** True if the mouse is over this component, or if it's being dragged in this component.
  24923. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24924. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24925. */
  24926. bool isMouseOverOrDragging() const noexcept;
  24927. /** Returns true if a mouse button is currently down.
  24928. Unlike isMouseButtonDown, this will test the current state of the
  24929. buttons without regard to which component (if any) it has been
  24930. pressed in.
  24931. @see isMouseButtonDown, ModifierKeys
  24932. */
  24933. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() noexcept;
  24934. /** Returns the mouse's current position, relative to this component.
  24935. The return value is relative to the component's top-left corner.
  24936. */
  24937. Point<int> getMouseXYRelative() const;
  24938. /** Called when this component's size has been changed.
  24939. A component can implement this method to do things such as laying out its
  24940. child components when its width or height changes.
  24941. The method is called synchronously as a result of the setBounds or setSize
  24942. methods, so repeatedly changing a components size will repeatedly call its
  24943. resized method (unlike things like repainting, where multiple calls to repaint
  24944. are coalesced together).
  24945. If the component is a top-level window on the desktop, its size could also
  24946. be changed by operating-system factors beyond the application's control.
  24947. @see moved, setSize
  24948. */
  24949. virtual void resized();
  24950. /** Called when this component's position has been changed.
  24951. This is called when the position relative to its parent changes, not when
  24952. its absolute position on the screen changes (so it won't be called for
  24953. all child components when a parent component is moved).
  24954. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24955. or any of the other repositioning methods, and like resized(), it will be
  24956. called each time those methods are called.
  24957. If the component is a top-level window on the desktop, its position could also
  24958. be changed by operating-system factors beyond the application's control.
  24959. @see resized, setBounds
  24960. */
  24961. virtual void moved();
  24962. /** Called when one of this component's children is moved or resized.
  24963. If the parent wants to know about changes to its immediate children (not
  24964. to children of its children), this is the method to override.
  24965. @see moved, resized, parentSizeChanged
  24966. */
  24967. virtual void childBoundsChanged (Component* child);
  24968. /** Called when this component's immediate parent has been resized.
  24969. If the component is a top-level window, this indicates that the screen size
  24970. has changed.
  24971. @see childBoundsChanged, moved, resized
  24972. */
  24973. virtual void parentSizeChanged();
  24974. /** Called when this component has been moved to the front of its siblings.
  24975. The component may have been brought to the front by the toFront() method, or
  24976. by the operating system if it's a top-level window.
  24977. @see toFront
  24978. */
  24979. virtual void broughtToFront();
  24980. /** Adds a listener to be told about changes to the component hierarchy or position.
  24981. Component listeners get called when this component's size, position or children
  24982. change - see the ComponentListener class for more details.
  24983. @param newListener the listener to register - if this is already registered, it
  24984. will be ignored.
  24985. @see ComponentListener, removeComponentListener
  24986. */
  24987. void addComponentListener (ComponentListener* newListener);
  24988. /** Removes a component listener.
  24989. @see addComponentListener
  24990. */
  24991. void removeComponentListener (ComponentListener* listenerToRemove);
  24992. /** Dispatches a numbered message to this component.
  24993. This is a quick and cheap way of allowing simple asynchronous messages to
  24994. be sent to components. It's also safe, because if the component that you
  24995. send the message to is a null or dangling pointer, this won't cause an error.
  24996. The command ID is later delivered to the component's handleCommandMessage() method by
  24997. the application's message queue.
  24998. @see handleCommandMessage
  24999. */
  25000. void postCommandMessage (int commandId);
  25001. /** Called to handle a command that was sent by postCommandMessage().
  25002. This is called by the message thread when a command message arrives, and
  25003. the component can override this method to process it in any way it needs to.
  25004. @see postCommandMessage
  25005. */
  25006. virtual void handleCommandMessage (int commandId);
  25007. /** Runs a component modally, waiting until the loop terminates.
  25008. This method first makes the component visible, brings it to the front and
  25009. gives it the keyboard focus.
  25010. It then runs a loop, dispatching messages from the system message queue, but
  25011. blocking all mouse or keyboard messages from reaching any components other
  25012. than this one and its children.
  25013. This loop continues until the component's exitModalState() method is called (or
  25014. the component is deleted), and then this method returns, returning the value
  25015. passed into exitModalState().
  25016. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  25017. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  25018. */
  25019. #if JUCE_MODAL_LOOPS_PERMITTED
  25020. int runModalLoop();
  25021. #endif
  25022. /** Puts the component into a modal state.
  25023. This makes the component modal, so that messages are blocked from reaching
  25024. any components other than this one and its children, but unlike runModalLoop(),
  25025. this method returns immediately.
  25026. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  25027. get the focus, which is usually what you'll want it to do. If not, it will leave
  25028. the focus unchanged.
  25029. The callback is an optional object which will receive a callback when the modal
  25030. component loses its modal status, either by being hidden or when exitModalState()
  25031. is called. If you pass an object in here, the system will take care of deleting it
  25032. later, after making the callback
  25033. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  25034. deleted and then the callback will be called. (This will safely handle the situation
  25035. where the component is deleted before its exitModalState() method is called).
  25036. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  25037. */
  25038. void enterModalState (bool takeKeyboardFocus = true,
  25039. ModalComponentManager::Callback* callback = nullptr,
  25040. bool deleteWhenDismissed = false);
  25041. /** Ends a component's modal state.
  25042. If this component is currently modal, this will turn of its modalness, and return
  25043. a value to the runModalLoop() method that might have be running its modal loop.
  25044. @see runModalLoop, enterModalState, isCurrentlyModal
  25045. */
  25046. void exitModalState (int returnValue);
  25047. /** Returns true if this component is the modal one.
  25048. It's possible to have nested modal components, e.g. a pop-up dialog box
  25049. that launches another pop-up, but this will only return true for
  25050. the one at the top of the stack.
  25051. @see getCurrentlyModalComponent
  25052. */
  25053. bool isCurrentlyModal() const noexcept;
  25054. /** Returns the number of components that are currently in a modal state.
  25055. @see getCurrentlyModalComponent
  25056. */
  25057. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() noexcept;
  25058. /** Returns one of the components that are currently modal.
  25059. The index specifies which of the possible modal components to return. The order
  25060. of the components in this list is the reverse of the order in which they became
  25061. modal - so the component at index 0 is always the active component, and the others
  25062. are progressively earlier ones that are themselves now blocked by later ones.
  25063. @returns the modal component, or null if no components are modal (or if the
  25064. index is out of range)
  25065. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  25066. */
  25067. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) noexcept;
  25068. /** Checks whether there's a modal component somewhere that's stopping this one
  25069. from receiving messages.
  25070. If there is a modal component, its canModalEventBeSentToComponent() method
  25071. will be called to see if it will still allow this component to receive events.
  25072. @see runModalLoop, getCurrentlyModalComponent
  25073. */
  25074. bool isCurrentlyBlockedByAnotherModalComponent() const;
  25075. /** When a component is modal, this callback allows it to choose which other
  25076. components can still receive events.
  25077. When a modal component is active and the user clicks on a non-modal component,
  25078. this method is called on the modal component, and if it returns true, the
  25079. event is allowed to reach its target. If it returns false, the event is blocked
  25080. and the inputAttemptWhenModal() callback is made.
  25081. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  25082. implementation just returns false in all cases.
  25083. */
  25084. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  25085. /** Called when the user tries to click on a component that is blocked by another
  25086. modal component.
  25087. When a component is modal and the user clicks on one of the other components,
  25088. the modal component will receive this callback.
  25089. The default implementation of this method will play a beep, and bring the currently
  25090. modal component to the front, but it can be overridden to do other tasks.
  25091. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  25092. */
  25093. virtual void inputAttemptWhenModal();
  25094. /** Returns the set of properties that belong to this component.
  25095. Each component has a NamedValueSet object which you can use to attach arbitrary
  25096. items of data to it.
  25097. */
  25098. NamedValueSet& getProperties() noexcept { return properties; }
  25099. /** Returns the set of properties that belong to this component.
  25100. Each component has a NamedValueSet object which you can use to attach arbitrary
  25101. items of data to it.
  25102. */
  25103. const NamedValueSet& getProperties() const noexcept { return properties; }
  25104. /** Looks for a colour that has been registered with the given colour ID number.
  25105. If a colour has been set for this ID number using setColour(), then it is
  25106. returned. If none has been set, the method will try calling the component's
  25107. LookAndFeel class's findColour() method. If none has been registered with the
  25108. look-and-feel either, it will just return black.
  25109. The colour IDs for various purposes are stored as enums in the components that
  25110. they are relevent to - for an example, see Slider::ColourIds,
  25111. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  25112. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  25113. */
  25114. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  25115. /** Registers a colour to be used for a particular purpose.
  25116. Changing a colour will cause a synchronous callback to the colourChanged()
  25117. method, which your component can override if it needs to do something when
  25118. colours are altered.
  25119. For more details about colour IDs, see the comments for findColour().
  25120. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  25121. */
  25122. void setColour (int colourId, const Colour& colour);
  25123. /** If a colour has been set with setColour(), this will remove it.
  25124. This allows you to make a colour revert to its default state.
  25125. */
  25126. void removeColour (int colourId);
  25127. /** Returns true if the specified colour ID has been explicitly set for this
  25128. component using the setColour() method.
  25129. */
  25130. bool isColourSpecified (int colourId) const;
  25131. /** This looks for any colours that have been specified for this component,
  25132. and copies them to the specified target component.
  25133. */
  25134. void copyAllExplicitColoursTo (Component& target) const;
  25135. /** This method is called when a colour is changed by the setColour() method.
  25136. @see setColour, findColour
  25137. */
  25138. virtual void colourChanged();
  25139. /** Components can implement this method to provide a MarkerList.
  25140. The default implementation of this method returns 0, but you can override it to
  25141. return a pointer to the component's marker list. If xAxis is true, it should
  25142. return the X marker list; if false, it should return the Y markers.
  25143. */
  25144. virtual MarkerList* getMarkers (bool xAxis);
  25145. /** Returns the underlying native window handle for this component.
  25146. This is platform-dependent and strictly for power-users only!
  25147. */
  25148. void* getWindowHandle() const;
  25149. /** Holds a pointer to some type of Component, which automatically becomes null if
  25150. the component is deleted.
  25151. If you're using a component which may be deleted by another event that's outside
  25152. of your control, use a SafePointer instead of a normal pointer to refer to it,
  25153. and you can test whether it's null before using it to see if something has deleted
  25154. it.
  25155. The ComponentType typedef must be Component, or some subclass of Component.
  25156. You may also want to use a WeakReference<Component> object for the same purpose.
  25157. */
  25158. template <class ComponentType>
  25159. class SafePointer
  25160. {
  25161. public:
  25162. /** Creates a null SafePointer. */
  25163. SafePointer() noexcept {}
  25164. /** Creates a SafePointer that points at the given component. */
  25165. SafePointer (ComponentType* const component) : weakRef (component) {}
  25166. /** Creates a copy of another SafePointer. */
  25167. SafePointer (const SafePointer& other) noexcept : weakRef (other.weakRef) {}
  25168. /** Copies another pointer to this one. */
  25169. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  25170. /** Copies another pointer to this one. */
  25171. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  25172. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25173. ComponentType* getComponent() const noexcept { return dynamic_cast <ComponentType*> (weakRef.get()); }
  25174. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25175. operator ComponentType*() const noexcept { return getComponent(); }
  25176. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25177. ComponentType* operator->() noexcept { return getComponent(); }
  25178. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25179. const ComponentType* operator->() const noexcept { return getComponent(); }
  25180. /** If the component is valid, this deletes it and sets this pointer to null. */
  25181. void deleteAndZero() { delete getComponent(); jassert (getComponent() == nullptr); }
  25182. bool operator== (ComponentType* component) const noexcept { return weakRef == component; }
  25183. bool operator!= (ComponentType* component) const noexcept { return weakRef != component; }
  25184. private:
  25185. WeakReference<Component> weakRef;
  25186. };
  25187. /** A class to keep an eye on a component and check for it being deleted.
  25188. This is designed for use with the ListenerList::callChecked() methods, to allow
  25189. the list iterator to stop cleanly if the component is deleted by a listener callback
  25190. while the list is still being iterated.
  25191. */
  25192. class JUCE_API BailOutChecker
  25193. {
  25194. public:
  25195. /** Creates a checker that watches one component. */
  25196. BailOutChecker (Component* component);
  25197. /** Returns true if either of the two components have been deleted since this object was created. */
  25198. bool shouldBailOut() const noexcept;
  25199. private:
  25200. const WeakReference<Component> safePointer;
  25201. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  25202. };
  25203. /**
  25204. Base class for objects that can be used to automatically position a component according to
  25205. some kind of algorithm.
  25206. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  25207. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  25208. it might choose to watch some kind of value and move the component when the value changes).
  25209. */
  25210. class JUCE_API Positioner
  25211. {
  25212. public:
  25213. /** Creates a Positioner which can control the specified component. */
  25214. explicit Positioner (Component& component) noexcept;
  25215. /** Destructor. */
  25216. virtual ~Positioner() {}
  25217. /** Returns the component that this positioner controls. */
  25218. Component& getComponent() const noexcept { return component; }
  25219. /** Attempts to set the component's position to the given rectangle.
  25220. Unlike simply calling Component::setBounds(), this may involve the positioner
  25221. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  25222. positioner may try to reverse the expressions used to make them fit these new coordinates.
  25223. */
  25224. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  25225. private:
  25226. Component& component;
  25227. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  25228. };
  25229. /** Returns the Positioner object that has been set for this component.
  25230. @see setPositioner()
  25231. */
  25232. Positioner* getPositioner() const noexcept;
  25233. /** Sets a new Positioner object for this component.
  25234. If there's currently another positioner set, it will be deleted. The object that is passed in
  25235. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  25236. to clear the current positioner.
  25237. @see getPositioner()
  25238. */
  25239. void setPositioner (Positioner* newPositioner);
  25240. #ifndef DOXYGEN
  25241. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  25242. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  25243. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  25244. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  25245. #endif
  25246. private:
  25247. friend class ComponentPeer;
  25248. friend class MouseInputSource;
  25249. friend class MouseInputSourceInternal;
  25250. #ifndef DOXYGEN
  25251. static Component* currentlyFocusedComponent;
  25252. String componentName, componentID;
  25253. Component* parentComponent;
  25254. Rectangle<int> bounds;
  25255. ScopedPointer <Positioner> positioner;
  25256. ScopedPointer <AffineTransform> affineTransform;
  25257. Array <Component*> childComponentList;
  25258. LookAndFeel* lookAndFeel;
  25259. MouseCursor cursor;
  25260. ImageEffectFilter* effect;
  25261. Image bufferedImage;
  25262. class MouseListenerList;
  25263. friend class MouseListenerList;
  25264. friend class ScopedPointer <MouseListenerList>;
  25265. ScopedPointer <MouseListenerList> mouseListeners;
  25266. ScopedPointer <Array <KeyListener*> > keyListeners;
  25267. ListenerList <ComponentListener> componentListeners;
  25268. NamedValueSet properties;
  25269. friend class WeakReference<Component>;
  25270. WeakReference<Component>::Master weakReferenceMaster;
  25271. const WeakReference<Component>::SharedRef& getWeakReference();
  25272. struct ComponentFlags
  25273. {
  25274. bool hasHeavyweightPeerFlag : 1;
  25275. bool visibleFlag : 1;
  25276. bool opaqueFlag : 1;
  25277. bool ignoresMouseClicksFlag : 1;
  25278. bool allowChildMouseClicksFlag : 1;
  25279. bool wantsFocusFlag : 1;
  25280. bool isFocusContainerFlag : 1;
  25281. bool dontFocusOnMouseClickFlag : 1;
  25282. bool alwaysOnTopFlag : 1;
  25283. bool bufferToImageFlag : 1;
  25284. bool bringToFrontOnClickFlag : 1;
  25285. bool repaintOnMouseActivityFlag : 1;
  25286. bool mouseDownFlag : 1;
  25287. bool mouseOverFlag : 1;
  25288. bool mouseInsideFlag : 1;
  25289. bool currentlyModalFlag : 1;
  25290. bool isDisabledFlag : 1;
  25291. bool childCompFocusedFlag : 1;
  25292. bool dontClipGraphicsFlag : 1;
  25293. #if JUCE_DEBUG
  25294. bool isInsidePaintCall : 1;
  25295. #endif
  25296. };
  25297. union
  25298. {
  25299. uint32 componentFlags;
  25300. ComponentFlags flags;
  25301. };
  25302. uint8 componentTransparency;
  25303. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25304. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25305. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25306. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  25307. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25308. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25309. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  25310. void internalBroughtToFront();
  25311. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  25312. void internalFocusGain (const FocusChangeType cause);
  25313. void internalFocusLoss (const FocusChangeType cause);
  25314. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  25315. void internalModalInputAttempt();
  25316. void internalModifierKeysChanged();
  25317. void internalChildrenChanged();
  25318. void internalHierarchyChanged();
  25319. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  25320. void moveChildInternal (int sourceIndex, int destIndex);
  25321. void paintComponentAndChildren (Graphics& g);
  25322. void paintComponent (Graphics& g);
  25323. void paintWithinParentContext (Graphics& g);
  25324. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  25325. void repaintParent();
  25326. void sendFakeMouseMove() const;
  25327. void takeKeyboardFocus (const FocusChangeType cause);
  25328. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  25329. static void giveAwayFocus (bool sendFocusLossEvent);
  25330. void sendEnablementChangeMessage();
  25331. void sendVisibilityChangeMessage();
  25332. class ComponentHelpers;
  25333. friend class ComponentHelpers;
  25334. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  25335. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  25336. */
  25337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  25338. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25339. // This is included here just to cause a compile error if your code is still handling
  25340. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  25341. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  25342. // implement its methods instead of this Component method).
  25343. virtual void filesDropped (const StringArray&, int, int) {}
  25344. // This is included here to cause an error if you use or overload it - it has been deprecated in
  25345. // favour of contains (const Point<int>&)
  25346. void contains (int, int);
  25347. #endif
  25348. protected:
  25349. /** @internal */
  25350. virtual void internalRepaint (int x, int y, int w, int h);
  25351. /** @internal */
  25352. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  25353. #endif
  25354. };
  25355. #endif // __JUCE_COMPONENT_JUCEHEADER__
  25356. /*** End of inlined file: juce_Component.h ***/
  25357. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  25358. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25359. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25360. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  25361. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25362. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25363. /** A type used to hold the unique ID for an application command.
  25364. This is a numeric type, so it can be stored as an integer.
  25365. @see ApplicationCommandInfo, ApplicationCommandManager,
  25366. ApplicationCommandTarget, KeyPressMappingSet
  25367. */
  25368. typedef int CommandID;
  25369. /** A set of general-purpose application command IDs.
  25370. Because these commands are likely to be used in most apps, they're defined
  25371. here to help different apps to use the same numeric values for them.
  25372. Of course you don't have to use these, but some of them are used internally by
  25373. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  25374. @see ApplicationCommandInfo, ApplicationCommandManager,
  25375. ApplicationCommandTarget, KeyPressMappingSet
  25376. */
  25377. namespace StandardApplicationCommandIDs
  25378. {
  25379. /** This command ID should be used to send a "Quit the App" command.
  25380. This command is recognised by the JUCEApplication class, so if it is invoked
  25381. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  25382. object will catch it and call JUCEApplication::systemRequestedQuit().
  25383. */
  25384. static const CommandID quit = 0x1001;
  25385. /** The command ID that should be used to send a "Delete" command. */
  25386. static const CommandID del = 0x1002;
  25387. /** The command ID that should be used to send a "Cut" command. */
  25388. static const CommandID cut = 0x1003;
  25389. /** The command ID that should be used to send a "Copy to clipboard" command. */
  25390. static const CommandID copy = 0x1004;
  25391. /** The command ID that should be used to send a "Paste from clipboard" command. */
  25392. static const CommandID paste = 0x1005;
  25393. /** The command ID that should be used to send a "Select all" command. */
  25394. static const CommandID selectAll = 0x1006;
  25395. /** The command ID that should be used to send a "Deselect all" command. */
  25396. static const CommandID deselectAll = 0x1007;
  25397. }
  25398. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25399. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  25400. /**
  25401. Holds information describing an application command.
  25402. This object is used to pass information about a particular command, such as its
  25403. name, description and other usage flags.
  25404. When an ApplicationCommandTarget is asked to provide information about the commands
  25405. it can perform, this is the structure gets filled-in to describe each one.
  25406. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  25407. ApplicationCommandManager
  25408. */
  25409. struct JUCE_API ApplicationCommandInfo
  25410. {
  25411. explicit ApplicationCommandInfo (CommandID commandID) noexcept;
  25412. /** Sets a number of the structures values at once.
  25413. The meanings of each of the parameters is described below, in the appropriate
  25414. member variable's description.
  25415. */
  25416. void setInfo (const String& shortName,
  25417. const String& description,
  25418. const String& categoryName,
  25419. int flags) noexcept;
  25420. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  25421. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  25422. is false, the bit is set.
  25423. */
  25424. void setActive (bool isActive) noexcept;
  25425. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  25426. */
  25427. void setTicked (bool isTicked) noexcept;
  25428. /** Handy method for adding a keypress to the defaultKeypresses array.
  25429. This is just so you can write things like:
  25430. @code
  25431. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  25432. @endcode
  25433. instead of
  25434. @code
  25435. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  25436. @endcode
  25437. */
  25438. void addDefaultKeypress (int keyCode,
  25439. const ModifierKeys& modifiers) noexcept;
  25440. /** The command's unique ID number.
  25441. */
  25442. CommandID commandID;
  25443. /** A short name to describe the command.
  25444. This should be suitable for use in menus, on buttons that trigger the command, etc.
  25445. You can use the setInfo() method to quickly set this and some of the command's
  25446. other properties.
  25447. */
  25448. String shortName;
  25449. /** A longer description of the command.
  25450. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  25451. pop-up tooltip describing what the command does.
  25452. You can use the setInfo() method to quickly set this and some of the command's
  25453. other properties.
  25454. */
  25455. String description;
  25456. /** A named category that the command fits into.
  25457. You can give your commands any category you like, and these will be displayed in
  25458. contexts such as the KeyMappingEditorComponent, where the category is used to group
  25459. commands together.
  25460. You can use the setInfo() method to quickly set this and some of the command's
  25461. other properties.
  25462. */
  25463. String categoryName;
  25464. /** A list of zero or more keypresses that should be used as the default keys for
  25465. this command.
  25466. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  25467. this list to initialise the default set of key-to-command mappings.
  25468. @see addDefaultKeypress
  25469. */
  25470. Array <KeyPress> defaultKeypresses;
  25471. /** Flags describing the ways in which this command should be used.
  25472. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  25473. variable.
  25474. */
  25475. enum CommandFlags
  25476. {
  25477. /** Indicates that the command can't currently be performed.
  25478. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  25479. not currently permissable to perform the command. If the flag is set, then
  25480. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  25481. command or show themselves as not being enabled.
  25482. @see ApplicationCommandInfo::setActive
  25483. */
  25484. isDisabled = 1 << 0,
  25485. /** Indicates that the command should have a tick next to it on a menu.
  25486. If your command is shown on a menu and this is set, it'll show a tick next to
  25487. it. Other components such as buttons may also use this flag to indicate that it
  25488. is a value that can be toggled, and is currently in the 'on' state.
  25489. @see ApplicationCommandInfo::setTicked
  25490. */
  25491. isTicked = 1 << 1,
  25492. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  25493. it will call the command twice, once on key-down and again on key-up.
  25494. @see ApplicationCommandTarget::InvocationInfo
  25495. */
  25496. wantsKeyUpDownCallbacks = 1 << 2,
  25497. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  25498. command in its list.
  25499. */
  25500. hiddenFromKeyEditor = 1 << 3,
  25501. /** If this flag is present, then a KeyMappingEditorComponent will display the
  25502. command in its list, but won't allow the assigned keypress to be changed.
  25503. */
  25504. readOnlyInKeyEditor = 1 << 4,
  25505. /** If this flag is present and the command is invoked from a keypress, then any
  25506. buttons or menus that are also connected to the command will not flash to
  25507. indicate that they've been triggered.
  25508. */
  25509. dontTriggerVisualFeedback = 1 << 5
  25510. };
  25511. /** A bitwise-OR of the values specified in the CommandFlags enum.
  25512. You can use the setInfo() method to quickly set this and some of the command's
  25513. other properties.
  25514. */
  25515. int flags;
  25516. };
  25517. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25518. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  25519. /*** Start of inlined file: juce_MessageListener.h ***/
  25520. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  25521. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  25522. /**
  25523. MessageListener subclasses can post and receive Message objects.
  25524. @see Message, MessageManager, ActionListener, ChangeListener
  25525. */
  25526. class JUCE_API MessageListener
  25527. {
  25528. protected:
  25529. /** Creates a MessageListener. */
  25530. MessageListener() noexcept;
  25531. public:
  25532. /** Destructor.
  25533. When a MessageListener is deleted, it removes itself from a global list
  25534. of registered listeners, so that the isValidMessageListener() method
  25535. will no longer return true.
  25536. */
  25537. virtual ~MessageListener();
  25538. /** This is the callback method that receives incoming messages.
  25539. This is called by the MessageManager from its dispatch loop.
  25540. @see postMessage
  25541. */
  25542. virtual void handleMessage (const Message& message) = 0;
  25543. /** Sends a message to the message queue, for asynchronous delivery to this listener
  25544. later on.
  25545. This method can be called safely by any thread.
  25546. @param message the message object to send - this will be deleted
  25547. automatically by the message queue, so don't keep any
  25548. references to it after calling this method.
  25549. @see handleMessage
  25550. */
  25551. void postMessage (Message* message) const noexcept;
  25552. /** Checks whether this MessageListener has been deleted.
  25553. Although not foolproof, this method is safe to call on dangling or null
  25554. pointers. A list of active MessageListeners is kept internally, so this
  25555. checks whether the object is on this list or not.
  25556. Note that it's possible to get a false-positive here, if an object is
  25557. deleted and another is subsequently created that happens to be at the
  25558. exact same memory location, but I can't think of a good way of avoiding
  25559. this.
  25560. */
  25561. bool isValidMessageListener() const noexcept;
  25562. };
  25563. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  25564. /*** End of inlined file: juce_MessageListener.h ***/
  25565. /**
  25566. A command target publishes a list of command IDs that it can perform.
  25567. An ApplicationCommandManager despatches commands to targets, which must be
  25568. able to provide information about what commands they can handle.
  25569. To create a target, you'll need to inherit from this class, implementing all of
  25570. its pure virtual methods.
  25571. For info about how a target is chosen to receive a command, see
  25572. ApplicationCommandManager::getFirstCommandTarget().
  25573. @see ApplicationCommandManager, ApplicationCommandInfo
  25574. */
  25575. class JUCE_API ApplicationCommandTarget
  25576. {
  25577. public:
  25578. /** Creates a command target. */
  25579. ApplicationCommandTarget();
  25580. /** Destructor. */
  25581. virtual ~ApplicationCommandTarget();
  25582. /**
  25583. */
  25584. struct JUCE_API InvocationInfo
  25585. {
  25586. InvocationInfo (const CommandID commandID);
  25587. /** The UID of the command that should be performed. */
  25588. CommandID commandID;
  25589. /** The command's flags.
  25590. See ApplicationCommandInfo for a description of these flag values.
  25591. */
  25592. int commandFlags;
  25593. /** The types of context in which the command might be called. */
  25594. enum InvocationMethod
  25595. {
  25596. direct = 0, /**< The command is being invoked directly by a piece of code. */
  25597. fromKeyPress, /**< The command is being invoked by a key-press. */
  25598. fromMenu, /**< The command is being invoked by a menu selection. */
  25599. fromButton /**< The command is being invoked by a button click. */
  25600. };
  25601. /** The type of event that triggered this command. */
  25602. InvocationMethod invocationMethod;
  25603. /** If triggered by a keypress or menu, this will be the component that had the
  25604. keyboard focus at the time.
  25605. If triggered by a button, it may be set to that component, or it may be null.
  25606. */
  25607. Component* originatingComponent;
  25608. /** The keypress that was used to invoke it.
  25609. Note that this will be an invalid keypress if the command was invoked
  25610. by some other means than a keyboard shortcut.
  25611. */
  25612. KeyPress keyPress;
  25613. /** True if the callback is being invoked when the key is pressed,
  25614. false if the key is being released.
  25615. @see KeyPressMappingSet::addCommand()
  25616. */
  25617. bool isKeyDown;
  25618. /** If the key is being released, this indicates how long it had been held
  25619. down for.
  25620. (Only relevant if isKeyDown is false.)
  25621. */
  25622. int millisecsSinceKeyPressed;
  25623. };
  25624. /** This must return the next target to try after this one.
  25625. When a command is being sent, and the first target can't handle
  25626. that command, this method is used to determine the next target that should
  25627. be tried.
  25628. It may return 0 if it doesn't know of another target.
  25629. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  25630. method to return a parent component that might want to handle it.
  25631. @see invoke
  25632. */
  25633. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  25634. /** This must return a complete list of commands that this target can handle.
  25635. Your target should add all the command IDs that it handles to the array that is
  25636. passed-in.
  25637. */
  25638. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  25639. /** This must provide details about one of the commands that this target can perform.
  25640. This will be called with one of the command IDs that the target provided in its
  25641. getAllCommands() methods.
  25642. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  25643. suitable information about the command. (The commandID field will already have been filled-in
  25644. by the caller).
  25645. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  25646. set all the fields at once.
  25647. If the command is currently inactive for some reason, this method must use
  25648. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  25649. bit of the ApplicationCommandInfo::flags field).
  25650. Any default key-presses for the command should be appended to the
  25651. ApplicationCommandInfo::defaultKeypresses field.
  25652. Note that if you change something that affects the status of the commands
  25653. that would be returned by this method (e.g. something that makes some commands
  25654. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  25655. to cause the manager to refresh its status.
  25656. */
  25657. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  25658. /** This must actually perform the specified command.
  25659. If this target is able to perform the command specified by the commandID field of the
  25660. InvocationInfo structure, then it should do so, and must return true.
  25661. If it can't handle this command, it should return false, which tells the caller to pass
  25662. the command on to the next target in line.
  25663. @see invoke, ApplicationCommandManager::invoke
  25664. */
  25665. virtual bool perform (const InvocationInfo& info) = 0;
  25666. /** Makes this target invoke a command.
  25667. Your code can call this method to invoke a command on this target, but normally
  25668. you'd call it indirectly via ApplicationCommandManager::invoke() or
  25669. ApplicationCommandManager::invokeDirectly().
  25670. If this target can perform the given command, it will call its perform() method to
  25671. do so. If not, then getNextCommandTarget() will be used to determine the next target
  25672. to try, and the command will be passed along to it.
  25673. @param invocationInfo this must be correctly filled-in, describing the context for
  25674. the invocation.
  25675. @param asynchronously if false, the command will be performed before this method returns.
  25676. If true, a message will be posted so that the command will be performed
  25677. later on the message thread, and this method will return immediately.
  25678. @see perform, ApplicationCommandManager::invoke
  25679. */
  25680. bool invoke (const InvocationInfo& invocationInfo,
  25681. const bool asynchronously);
  25682. /** Invokes a given command directly on this target.
  25683. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25684. structure.
  25685. */
  25686. bool invokeDirectly (const CommandID commandID,
  25687. const bool asynchronously);
  25688. /** Searches this target and all subsequent ones for the first one that can handle
  25689. the specified command.
  25690. This will use getNextCommandTarget() to determine the chain of targets to try
  25691. after this one.
  25692. */
  25693. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  25694. /** Checks whether this command can currently be performed by this target.
  25695. This will return true only if a call to getCommandInfo() doesn't set the
  25696. isDisabled flag to indicate that the command is inactive.
  25697. */
  25698. bool isCommandActive (const CommandID commandID);
  25699. /** If this object is a Component, this method will seach upwards in its current
  25700. UI hierarchy for the next parent component that implements the
  25701. ApplicationCommandTarget class.
  25702. If your target is a Component, this is a very handy method to use in your
  25703. getNextCommandTarget() implementation.
  25704. */
  25705. ApplicationCommandTarget* findFirstTargetParentComponent();
  25706. private:
  25707. // (for async invocation of commands)
  25708. class CommandTargetMessageInvoker : public MessageListener
  25709. {
  25710. public:
  25711. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  25712. ~CommandTargetMessageInvoker();
  25713. void handleMessage (const Message& message);
  25714. private:
  25715. ApplicationCommandTarget* const owner;
  25716. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  25717. };
  25718. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  25719. friend class CommandTargetMessageInvoker;
  25720. bool tryToInvoke (const InvocationInfo& info, bool async);
  25721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  25722. };
  25723. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25724. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  25725. /*** Start of inlined file: juce_ActionListener.h ***/
  25726. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  25727. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  25728. /**
  25729. Receives callbacks to indicate that some kind of event has occurred.
  25730. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  25731. about something that's happened.
  25732. @see ActionBroadcaster, ChangeListener
  25733. */
  25734. class JUCE_API ActionListener
  25735. {
  25736. public:
  25737. /** Destructor. */
  25738. virtual ~ActionListener() {}
  25739. /** Overridden by your subclass to receive the callback.
  25740. @param message the string that was specified when the event was triggered
  25741. by a call to ActionBroadcaster::sendActionMessage()
  25742. */
  25743. virtual void actionListenerCallback (const String& message) = 0;
  25744. };
  25745. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  25746. /*** End of inlined file: juce_ActionListener.h ***/
  25747. /**
  25748. An instance of this class is used to specify initialisation and shutdown
  25749. code for the application.
  25750. An application that wants to run in the JUCE framework needs to declare a
  25751. subclass of JUCEApplication and implement its various pure virtual methods.
  25752. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  25753. to declare an instance of this class and generate a suitable platform-specific
  25754. main() function.
  25755. e.g. @code
  25756. class MyJUCEApp : public JUCEApplication
  25757. {
  25758. public:
  25759. MyJUCEApp()
  25760. {
  25761. }
  25762. ~MyJUCEApp()
  25763. {
  25764. }
  25765. void initialise (const String& commandLine)
  25766. {
  25767. myMainWindow = new MyApplicationWindow();
  25768. myMainWindow->setBounds (100, 100, 400, 500);
  25769. myMainWindow->setVisible (true);
  25770. }
  25771. void shutdown()
  25772. {
  25773. myMainWindow = 0;
  25774. }
  25775. const String getApplicationName()
  25776. {
  25777. return "Super JUCE-o-matic";
  25778. }
  25779. const String getApplicationVersion()
  25780. {
  25781. return "1.0";
  25782. }
  25783. private:
  25784. ScopedPointer <MyApplicationWindow> myMainWindow;
  25785. };
  25786. // this creates wrapper code to actually launch the app properly.
  25787. START_JUCE_APPLICATION (MyJUCEApp)
  25788. @endcode
  25789. @see MessageManager
  25790. */
  25791. class JUCE_API JUCEApplication : public ApplicationCommandTarget
  25792. {
  25793. protected:
  25794. /** Constructs a JUCE app object.
  25795. If subclasses implement a constructor or destructor, they shouldn't call any
  25796. JUCE code in there - put your startup/shutdown code in initialise() and
  25797. shutdown() instead.
  25798. */
  25799. JUCEApplication();
  25800. public:
  25801. /** Destructor.
  25802. If subclasses implement a constructor or destructor, they shouldn't call any
  25803. JUCE code in there - put your startup/shutdown code in initialise() and
  25804. shutdown() instead.
  25805. */
  25806. virtual ~JUCEApplication();
  25807. /** Returns the global instance of the application object being run. */
  25808. static JUCEApplication* getInstance() noexcept { return appInstance; }
  25809. /** Called when the application starts.
  25810. This will be called once to let the application do whatever initialisation
  25811. it needs, create its windows, etc.
  25812. After the method returns, the normal event-dispatch loop will be run,
  25813. until the quit() method is called, at which point the shutdown()
  25814. method will be called to let the application clear up anything it needs
  25815. to delete.
  25816. If during the initialise() method, the application decides not to start-up
  25817. after all, it can just call the quit() method and the event loop won't be run.
  25818. @param commandLineParameters the line passed in does not include the
  25819. name of the executable, just the parameter list.
  25820. @see shutdown, quit
  25821. */
  25822. virtual void initialise (const String& commandLineParameters) = 0;
  25823. /** Returns true if the application hasn't yet completed its initialise() method
  25824. and entered the main event loop.
  25825. This is handy for things like splash screens to know when the app's up-and-running
  25826. properly.
  25827. */
  25828. bool isInitialising() const noexcept { return stillInitialising; }
  25829. /* Called to allow the application to clear up before exiting.
  25830. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25831. terminate, and this method will get called to allow the app to sort itself
  25832. out.
  25833. Be careful that nothing happens in this method that might rely on messages
  25834. being sent, or any kind of window activity, because the message loop is no
  25835. longer running at this point.
  25836. @see DeletedAtShutdown
  25837. */
  25838. virtual void shutdown() = 0;
  25839. /** Returns the application's name.
  25840. An application must implement this to name itself.
  25841. */
  25842. virtual const String getApplicationName() = 0;
  25843. /** Returns the application's version number.
  25844. */
  25845. virtual const String getApplicationVersion() = 0;
  25846. /** Checks whether multiple instances of the app are allowed.
  25847. If you application class returns true for this, more than one instance is
  25848. permitted to run (except on the Mac where this isn't possible).
  25849. If it's false, the second instance won't start, but it you will still get a
  25850. callback to anotherInstanceStarted() to tell you about this - which
  25851. gives you a chance to react to what the user was trying to do.
  25852. */
  25853. virtual bool moreThanOneInstanceAllowed();
  25854. /** Indicates that the user has tried to start up another instance of the app.
  25855. This will get called even if moreThanOneInstanceAllowed() is false.
  25856. */
  25857. virtual void anotherInstanceStarted (const String& commandLine);
  25858. /** Called when the operating system is trying to close the application.
  25859. The default implementation of this method is to call quit(), but it may
  25860. be overloaded to ignore the request or do some other special behaviour
  25861. instead. For example, you might want to offer the user the chance to save
  25862. their changes before quitting, and give them the chance to cancel.
  25863. If you want to send a quit signal to your app, this is the correct method
  25864. to call, because it means that requests that come from the system get handled
  25865. in the same way as those from your own application code. So e.g. you'd
  25866. call this method from a "quit" item on a menu bar.
  25867. */
  25868. virtual void systemRequestedQuit();
  25869. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25870. callback will be triggered, in case you want to log them or do some other
  25871. type of error-handling.
  25872. If the type of exception is derived from the std::exception class, the pointer
  25873. passed-in will be valid. If the exception is of unknown type, this pointer
  25874. will be null.
  25875. */
  25876. virtual void unhandledException (const std::exception* e,
  25877. const String& sourceFilename,
  25878. int lineNumber);
  25879. /** Signals that the main message loop should stop and the application should terminate.
  25880. This isn't synchronous, it just posts a quit message to the main queue, and
  25881. when this message arrives, the message loop will stop, the shutdown() method
  25882. will be called, and the app will exit.
  25883. Note that this will cause an unconditional quit to happen, so if you need an
  25884. extra level before this, e.g. to give the user the chance to save their work
  25885. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25886. method - see that method's help for more info.
  25887. @see MessageManager
  25888. */
  25889. static void quit();
  25890. /** Sets the value that should be returned as the application's exit code when the
  25891. app quits.
  25892. This is the value that's returned by the main() function. Normally you'd leave this
  25893. as 0 unless you want to indicate an error code.
  25894. @see getApplicationReturnValue
  25895. */
  25896. void setApplicationReturnValue (int newReturnValue) noexcept;
  25897. /** Returns the value that has been set as the application's exit code.
  25898. @see setApplicationReturnValue
  25899. */
  25900. int getApplicationReturnValue() const noexcept { return appReturnValue; }
  25901. /** Returns the application's command line params.
  25902. */
  25903. const String getCommandLineParameters() const noexcept { return commandLineParameters; }
  25904. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25905. or other kind of shared library. */
  25906. static inline bool isStandaloneApp() noexcept { return createInstance != 0; }
  25907. /** @internal */
  25908. ApplicationCommandTarget* getNextCommandTarget();
  25909. /** @internal */
  25910. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25911. /** @internal */
  25912. void getAllCommands (Array <CommandID>& commands);
  25913. /** @internal */
  25914. bool perform (const InvocationInfo& info);
  25915. #ifndef DOXYGEN
  25916. // The following methods are internal calls - not for public use.
  25917. static int main (const String& commandLine);
  25918. static int main (int argc, const char* argv[]);
  25919. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25920. bool initialiseApp (const String& commandLine);
  25921. int shutdownApp();
  25922. static void appWillTerminateByForce();
  25923. typedef JUCEApplication* (*CreateInstanceFunction)();
  25924. static CreateInstanceFunction createInstance;
  25925. #endif
  25926. private:
  25927. static JUCEApplication* appInstance;
  25928. String commandLineParameters;
  25929. ScopedPointer<InterProcessLock> appLock;
  25930. ScopedPointer<ActionListener> broadcastCallback;
  25931. int appReturnValue;
  25932. bool stillInitialising;
  25933. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25934. };
  25935. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25936. /*** End of inlined file: juce_Application.h ***/
  25937. #endif
  25938. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25939. #endif
  25940. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25941. #endif
  25942. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25943. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25944. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25945. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25946. /*** Start of inlined file: juce_Desktop.h ***/
  25947. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25948. #define __JUCE_DESKTOP_JUCEHEADER__
  25949. /*** Start of inlined file: juce_Timer.h ***/
  25950. #ifndef __JUCE_TIMER_JUCEHEADER__
  25951. #define __JUCE_TIMER_JUCEHEADER__
  25952. class InternalTimerThread;
  25953. /**
  25954. Makes repeated callbacks to a virtual method at a specified time interval.
  25955. A Timer's timerCallback() method will be repeatedly called at a given
  25956. interval. When you create a Timer object, it will do nothing until the
  25957. startTimer() method is called, which will cause the message thread to
  25958. start making callbacks at the specified interval, until stopTimer() is called
  25959. or the object is deleted.
  25960. The time interval isn't guaranteed to be precise to any more than maybe
  25961. 10-20ms, and the intervals may end up being much longer than requested if the
  25962. system is busy. Because the callbacks are made by the main message thread,
  25963. anything that blocks the message queue for a period of time will also prevent
  25964. any timers from running until it can carry on.
  25965. If you need to have a single callback that is shared by multiple timers with
  25966. different frequencies, then the MultiTimer class allows you to do that - its
  25967. structure is very similar to the Timer class, but contains multiple timers
  25968. internally, each one identified by an ID number.
  25969. @see MultiTimer
  25970. */
  25971. class JUCE_API Timer
  25972. {
  25973. protected:
  25974. /** Creates a Timer.
  25975. When created, the timer is stopped, so use startTimer() to get it going.
  25976. */
  25977. Timer() noexcept;
  25978. /** Creates a copy of another timer.
  25979. Note that this timer won't be started, even if the one you're copying
  25980. is running.
  25981. */
  25982. Timer (const Timer& other) noexcept;
  25983. public:
  25984. /** Destructor. */
  25985. virtual ~Timer();
  25986. /** The user-defined callback routine that actually gets called periodically.
  25987. It's perfectly ok to call startTimer() or stopTimer() from within this
  25988. callback to change the subsequent intervals.
  25989. */
  25990. virtual void timerCallback() = 0;
  25991. /** Starts the timer and sets the length of interval required.
  25992. If the timer is already started, this will reset it, so the
  25993. time between calling this method and the next timer callback
  25994. will not be less than the interval length passed in.
  25995. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25996. rounded up to 1)
  25997. */
  25998. void startTimer (int intervalInMilliseconds) noexcept;
  25999. /** Stops the timer.
  26000. No more callbacks will be made after this method returns.
  26001. If this is called from a different thread, any callbacks that may
  26002. be currently executing may be allowed to finish before the method
  26003. returns.
  26004. */
  26005. void stopTimer() noexcept;
  26006. /** Checks if the timer has been started.
  26007. @returns true if the timer is running.
  26008. */
  26009. bool isTimerRunning() const noexcept { return periodMs > 0; }
  26010. /** Returns the timer's interval.
  26011. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  26012. */
  26013. int getTimerInterval() const noexcept { return periodMs; }
  26014. private:
  26015. friend class InternalTimerThread;
  26016. int countdownMs, periodMs;
  26017. Timer* previous;
  26018. Timer* next;
  26019. Timer& operator= (const Timer&);
  26020. };
  26021. #endif // __JUCE_TIMER_JUCEHEADER__
  26022. /*** End of inlined file: juce_Timer.h ***/
  26023. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  26024. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26025. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26026. /**
  26027. Animates a set of components, moving them to a new position and/or fading their
  26028. alpha levels.
  26029. To animate a component, create a ComponentAnimator instance or (preferably) use the
  26030. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  26031. method to commence the movement.
  26032. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  26033. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  26034. destinations.
  26035. It's ok to delete components while they're being animated - the animator will detect this
  26036. and safely stop using them.
  26037. The class is a ChangeBroadcaster and sends a notification when any components
  26038. start or finish being animated.
  26039. @see Desktop::getAnimator
  26040. */
  26041. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  26042. private Timer
  26043. {
  26044. public:
  26045. /** Creates a ComponentAnimator. */
  26046. ComponentAnimator();
  26047. /** Destructor. */
  26048. ~ComponentAnimator();
  26049. /** Starts a component moving from its current position to a specified position.
  26050. If the component is already in the middle of an animation, that will be abandoned,
  26051. and a new animation will begin, moving the component from its current location.
  26052. The start and end speed parameters let you apply some acceleration to the component's
  26053. movement.
  26054. @param component the component to move
  26055. @param finalBounds the destination bounds to which the component should move. To leave the
  26056. component in the same place, just pass component->getBounds() for this value
  26057. @param finalAlpha the alpha value that the component should have at the end of the animation
  26058. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  26059. @param useProxyComponent if true, this means the component should be replaced by an internally
  26060. managed temporary component which is a snapshot of the original component.
  26061. This avoids the component having to paint itself as it moves, so may
  26062. be more efficient. This option also allows you to delete the original
  26063. component immediately after starting the animation, because the animation
  26064. can proceed without it. If you use a proxy, the original component will be
  26065. made invisible by this call, and then will become visible again at the end
  26066. of the animation. It'll also mean that the proxy component will be temporarily
  26067. added to the component's parent, so avoid it if this might confuse the parent
  26068. component, or if there's a chance the parent might decide to delete its children.
  26069. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  26070. the component will start by accelerating from rest; higher values mean that it
  26071. will have an initial speed greater than zero. If the value if greater than 1, it
  26072. will decelerate towards the middle of its journey. To move the component at a
  26073. constant rate for its entire animation, set both the start and end speeds to 1.0
  26074. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  26075. If this is 0, the component will decelerate to a standstill at its final position;
  26076. higher values mean the component will still be moving when it stops. To move the component
  26077. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  26078. */
  26079. void animateComponent (Component* component,
  26080. const Rectangle<int>& finalBounds,
  26081. float finalAlpha,
  26082. int animationDurationMilliseconds,
  26083. bool useProxyComponent,
  26084. double startSpeed,
  26085. double endSpeed);
  26086. /** Begins a fade-out of this components alpha level.
  26087. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  26088. a proxy. You're safe to delete the component after calling this method, and this won't
  26089. interfere with the animation's progress.
  26090. */
  26091. void fadeOut (Component* component, int millisecondsToTake);
  26092. /** Begins a fade-in of a component.
  26093. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  26094. */
  26095. void fadeIn (Component* component, int millisecondsToTake);
  26096. /** Stops a component if it's currently being animated.
  26097. If moveComponentToItsFinalPosition is true, then the component will
  26098. be immediately moved to its destination position and size. If false, it will be
  26099. left in whatever location it currently occupies.
  26100. */
  26101. void cancelAnimation (Component* component,
  26102. bool moveComponentToItsFinalPosition);
  26103. /** Clears all of the active animations.
  26104. If moveComponentsToTheirFinalPositions is true, all the components will
  26105. be immediately set to their final positions. If false, they will be
  26106. left in whatever locations they currently occupy.
  26107. */
  26108. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  26109. /** Returns the destination position for a component.
  26110. If the component is being animated, this will return the target position that
  26111. was specified when animateComponent() was called.
  26112. If the specified component isn't currently being animated, this method will just
  26113. return its current position.
  26114. */
  26115. const Rectangle<int> getComponentDestination (Component* component);
  26116. /** Returns true if the specified component is currently being animated. */
  26117. bool isAnimating (Component* component) const;
  26118. private:
  26119. class AnimationTask;
  26120. OwnedArray <AnimationTask> tasks;
  26121. uint32 lastTime;
  26122. AnimationTask* findTaskFor (Component* component) const;
  26123. void timerCallback();
  26124. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  26125. };
  26126. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26127. /*** End of inlined file: juce_ComponentAnimator.h ***/
  26128. class MouseInputSource;
  26129. class MouseInputSourceInternal;
  26130. class MouseListener;
  26131. /**
  26132. Classes can implement this interface and register themselves with the Desktop class
  26133. to receive callbacks when the currently focused component changes.
  26134. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  26135. */
  26136. class JUCE_API FocusChangeListener
  26137. {
  26138. public:
  26139. /** Destructor. */
  26140. virtual ~FocusChangeListener() {}
  26141. /** Callback to indicate that the currently focused component has changed. */
  26142. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  26143. };
  26144. /**
  26145. Describes and controls aspects of the computer's desktop.
  26146. */
  26147. class JUCE_API Desktop : private DeletedAtShutdown,
  26148. private Timer,
  26149. private AsyncUpdater
  26150. {
  26151. public:
  26152. /** There's only one dektop object, and this method will return it.
  26153. */
  26154. static Desktop& JUCE_CALLTYPE getInstance();
  26155. /** Returns a list of the positions of all the monitors available.
  26156. The first rectangle in the list will be the main monitor area.
  26157. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26158. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26159. */
  26160. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const;
  26161. /** Returns the position and size of the main monitor.
  26162. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26163. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26164. */
  26165. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const noexcept;
  26166. /** Returns the position and size of the monitor which contains this co-ordinate.
  26167. If none of the monitors contains the point, this will just return the
  26168. main monitor.
  26169. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26170. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26171. */
  26172. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  26173. /** Returns the mouse position.
  26174. The co-ordinates are relative to the top-left of the main monitor.
  26175. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  26176. you should only resort to grabbing the global mouse position if there's really no
  26177. way to get the coordinates via a mouse event callback instead.
  26178. */
  26179. static const Point<int> getMousePosition();
  26180. /** Makes the mouse pointer jump to a given location.
  26181. The co-ordinates are relative to the top-left of the main monitor.
  26182. */
  26183. static void setMousePosition (const Point<int>& newPosition);
  26184. /** Returns the last position at which a mouse button was pressed.
  26185. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  26186. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  26187. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  26188. if possible, and only ever call this as a last resort.
  26189. */
  26190. static const Point<int> getLastMouseDownPosition();
  26191. /** Returns the number of times the mouse button has been clicked since the
  26192. app started.
  26193. Each mouse-down event increments this number by 1.
  26194. */
  26195. static int getMouseButtonClickCounter();
  26196. /** This lets you prevent the screensaver from becoming active.
  26197. Handy if you're running some sort of presentation app where having a screensaver
  26198. appear would be annoying.
  26199. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  26200. won't enable a screensaver unless the user has actually set one up).
  26201. The disablement will only happen while the Juce application is the foreground
  26202. process - if another task is running in front of it, then the screensaver will
  26203. be unaffected.
  26204. @see isScreenSaverEnabled
  26205. */
  26206. static void setScreenSaverEnabled (bool isEnabled);
  26207. /** Returns true if the screensaver has not been turned off.
  26208. This will return the last value passed into setScreenSaverEnabled(). Note that
  26209. it won't tell you whether the user is actually using a screen saver, just
  26210. whether this app is deliberately preventing one from running.
  26211. @see setScreenSaverEnabled
  26212. */
  26213. static bool isScreenSaverEnabled();
  26214. /** Registers a MouseListener that will receive all mouse events that occur on
  26215. any component.
  26216. @see removeGlobalMouseListener
  26217. */
  26218. void addGlobalMouseListener (MouseListener* listener);
  26219. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  26220. method.
  26221. @see addGlobalMouseListener
  26222. */
  26223. void removeGlobalMouseListener (MouseListener* listener);
  26224. /** Registers a MouseListener that will receive a callback whenever the focused
  26225. component changes.
  26226. */
  26227. void addFocusChangeListener (FocusChangeListener* listener);
  26228. /** Unregisters a listener that was added with addFocusChangeListener(). */
  26229. void removeFocusChangeListener (FocusChangeListener* listener);
  26230. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  26231. The component must already be on the desktop for this method to work. It will
  26232. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  26233. etc will be hidden.
  26234. To exit kiosk mode, just call setKioskModeComponent (nullptr). When this is called,
  26235. the component that's currently being used will be resized back to the size
  26236. and position it was in before being put into this mode.
  26237. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  26238. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  26239. to hide as much on-screen paraphenalia as possible.
  26240. */
  26241. void setKioskModeComponent (Component* componentToUse,
  26242. bool allowMenusAndBars = true);
  26243. /** Returns the component that is currently being used in kiosk-mode.
  26244. This is the component that was last set by setKioskModeComponent(). If none
  26245. has been set, this returns 0.
  26246. */
  26247. Component* getKioskModeComponent() const noexcept { return kioskModeComponent; }
  26248. /** Returns the number of components that are currently active as top-level
  26249. desktop windows.
  26250. @see getComponent, Component::addToDesktop
  26251. */
  26252. int getNumComponents() const noexcept;
  26253. /** Returns one of the top-level desktop window components.
  26254. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  26255. index is out-of-range.
  26256. @see getNumComponents, Component::addToDesktop
  26257. */
  26258. Component* getComponent (int index) const noexcept;
  26259. /** Finds the component at a given screen location.
  26260. This will drill down into top-level windows to find the child component at
  26261. the given position.
  26262. Returns 0 if the co-ordinates are inside a non-Juce window.
  26263. */
  26264. Component* findComponentAt (const Point<int>& screenPosition) const;
  26265. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  26266. your animations.
  26267. Having a single shared ComponentAnimator object makes it more efficient when multiple
  26268. components are being moved around simultaneously. It's also more convenient than having
  26269. to manage your own instance of one.
  26270. @see ComponentAnimator
  26271. */
  26272. ComponentAnimator& getAnimator() noexcept { return animator; }
  26273. /** Returns the current default look-and-feel for components which don't have one
  26274. explicitly set.
  26275. @see setDefaultLookAndFeel
  26276. */
  26277. LookAndFeel& getDefaultLookAndFeel() noexcept;
  26278. /** Changes the default look-and-feel.
  26279. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  26280. set to nullptr, it will revert to using the system's
  26281. default one. The object passed-in must be deleted by the
  26282. caller when it's no longer needed.
  26283. @see getDefaultLookAndFeel
  26284. */
  26285. void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel);
  26286. /** Returns the number of MouseInputSource objects the system has at its disposal.
  26287. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26288. system, there could be one input source per potential finger.
  26289. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  26290. @see getMouseSource
  26291. */
  26292. int getNumMouseSources() const noexcept { return mouseSources.size(); }
  26293. /** Returns one of the system's MouseInputSource objects.
  26294. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  26295. a null pointer.
  26296. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26297. system, there could be one input source per potential finger.
  26298. */
  26299. MouseInputSource* getMouseSource (int index) const noexcept { return mouseSources [index]; }
  26300. /** Returns the main mouse input device that the system is using.
  26301. @see getNumMouseSources()
  26302. */
  26303. MouseInputSource& getMainMouseSource() const noexcept { return *mouseSources.getUnchecked(0); }
  26304. /** Returns the number of mouse-sources that are currently being dragged.
  26305. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  26306. juce component has the button down on it. In a multi-touch system, this could
  26307. be any number from 0 to the number of simultaneous touches that can be detected.
  26308. */
  26309. int getNumDraggingMouseSources() const noexcept;
  26310. /** Returns one of the mouse sources that's currently being dragged.
  26311. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  26312. out of range, or if no mice or fingers are down, this will return a null pointer.
  26313. */
  26314. MouseInputSource* getDraggingMouseSource (int index) const noexcept;
  26315. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  26316. current mouse-drag operation.
  26317. This allows you to make sure that mouseDrag() events are sent continuously, even
  26318. when the mouse isn't moving. This can be useful for things like auto-scrolling
  26319. components when the mouse is near an edge.
  26320. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  26321. minimum interval between consecutive mouse drag callbacks. The callbacks
  26322. will continue until the mouse is released, and then the interval will be reset,
  26323. so you need to make sure it's called every time you begin a drag event.
  26324. Passing an interval of 0 or less will cancel the auto-repeat.
  26325. @see mouseDrag
  26326. */
  26327. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  26328. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  26329. enum DisplayOrientation
  26330. {
  26331. upright = 1, /**< Indicates that the display is the normal way up. */
  26332. upsideDown = 2, /**< Indicates that the display is upside-down. */
  26333. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  26334. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  26335. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  26336. };
  26337. /** In a tablet device which can be turned around, this returns the current orientation. */
  26338. DisplayOrientation getCurrentOrientation() const;
  26339. /** Sets which orientations the display is allowed to auto-rotate to.
  26340. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  26341. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  26342. set bit.
  26343. */
  26344. void setOrientationsEnabled (int allowedOrientations);
  26345. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  26346. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  26347. */
  26348. bool isOrientationEnabled (DisplayOrientation orientation) const noexcept;
  26349. /** Tells this object to refresh its idea of what the screen resolution is.
  26350. (Called internally by the native code).
  26351. */
  26352. void refreshMonitorSizes();
  26353. /** True if the OS supports semitransparent windows */
  26354. static bool canUseSemiTransparentWindows() noexcept;
  26355. private:
  26356. static Desktop* instance;
  26357. friend class Component;
  26358. friend class ComponentPeer;
  26359. friend class MouseInputSource;
  26360. friend class MouseInputSourceInternal;
  26361. friend class DeletedAtShutdown;
  26362. friend class TopLevelWindowManager;
  26363. OwnedArray <MouseInputSource> mouseSources;
  26364. void createMouseInputSources();
  26365. ListenerList <MouseListener> mouseListeners;
  26366. ListenerList <FocusChangeListener> focusListeners;
  26367. Array <Component*> desktopComponents;
  26368. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  26369. Point<int> lastFakeMouseMove;
  26370. void sendMouseMove();
  26371. int mouseClickCounter;
  26372. void incrementMouseClickCounter() noexcept;
  26373. ScopedPointer<Timer> dragRepeater;
  26374. ScopedPointer<LookAndFeel> defaultLookAndFeel;
  26375. WeakReference<LookAndFeel> currentLookAndFeel;
  26376. Component* kioskModeComponent;
  26377. Rectangle<int> kioskComponentOriginalBounds;
  26378. int allowedOrientations;
  26379. ComponentAnimator animator;
  26380. void timerCallback();
  26381. void resetTimer();
  26382. int getNumDisplayMonitors() const noexcept;
  26383. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const noexcept;
  26384. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  26385. void addDesktopComponent (Component* c);
  26386. void removeDesktopComponent (Component* c);
  26387. void componentBroughtToFront (Component* c);
  26388. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  26389. void triggerFocusCallback();
  26390. void handleAsyncUpdate();
  26391. Desktop();
  26392. ~Desktop();
  26393. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  26394. };
  26395. #endif // __JUCE_DESKTOP_JUCEHEADER__
  26396. /*** End of inlined file: juce_Desktop.h ***/
  26397. class KeyPressMappingSet;
  26398. class ApplicationCommandManagerListener;
  26399. /**
  26400. One of these objects holds a list of all the commands your app can perform,
  26401. and despatches these commands when needed.
  26402. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  26403. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  26404. to invoke automatically, which means you don't have to handle the result of a menu
  26405. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  26406. which can choose which events they want to handle.
  26407. This architecture also allows for nested ApplicationCommandTargets, so that for example
  26408. you could have two different objects, one inside the other, both of which can respond to
  26409. a "delete" command. Depending on which one has focus, the command will be sent to the
  26410. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  26411. method.
  26412. To set up your app to use commands, you'll need to do the following:
  26413. - Create a global ApplicationCommandManager to hold the list of all possible
  26414. commands. (This will also manage a set of key-mappings for them).
  26415. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  26416. This allows the object to provide a list of commands that it can perform, and
  26417. to handle them.
  26418. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  26419. or ApplicationCommandManager::registerCommand().
  26420. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  26421. method to access the key-mapper object, which you will need to register as a key-listener
  26422. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  26423. about setting this up.
  26424. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  26425. cause these commands to be invoked automatically.
  26426. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  26427. When a command is invoked, the ApplicationCommandManager will try to choose the best
  26428. ApplicationCommandTarget to receive the specified command. To do this it will use the
  26429. current keyboard focus to see which component might be interested, and will search the
  26430. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  26431. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  26432. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  26433. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  26434. point if the command still hasn't been performed, it will be passed to the current
  26435. JUCEApplication object (which is itself an ApplicationCommandTarget).
  26436. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  26437. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  26438. the object yourself.
  26439. @see ApplicationCommandTarget, ApplicationCommandInfo
  26440. */
  26441. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  26442. private FocusChangeListener
  26443. {
  26444. public:
  26445. /** Creates an ApplicationCommandManager.
  26446. Once created, you'll need to register all your app's commands with it, using
  26447. ApplicationCommandManager::registerAllCommandsForTarget() or
  26448. ApplicationCommandManager::registerCommand().
  26449. */
  26450. ApplicationCommandManager();
  26451. /** Destructor.
  26452. Make sure that you don't delete this if pointers to it are still being used by
  26453. objects such as PopupMenus or Buttons.
  26454. */
  26455. virtual ~ApplicationCommandManager();
  26456. /** Clears the current list of all commands.
  26457. Note that this will also clear the contents of the KeyPressMappingSet.
  26458. */
  26459. void clearCommands();
  26460. /** Adds a command to the list of registered commands.
  26461. @see registerAllCommandsForTarget
  26462. */
  26463. void registerCommand (const ApplicationCommandInfo& newCommand);
  26464. /** Adds all the commands that this target publishes to the manager's list.
  26465. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  26466. to get details about all the commands that this target can do, and will call
  26467. registerCommand() to add each one to the manger's list.
  26468. @see registerCommand
  26469. */
  26470. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  26471. /** Removes the command with a specified ID.
  26472. Note that this will also remove any key mappings that are mapped to the command.
  26473. */
  26474. void removeCommand (CommandID commandID);
  26475. /** This should be called to tell the manager that one of its registered commands may have changed
  26476. its active status.
  26477. Because the command manager only finds out whether a command is active or inactive by querying
  26478. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  26479. allows things like buttons to update their enablement, etc.
  26480. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  26481. for any registered listeners.
  26482. */
  26483. void commandStatusChanged();
  26484. /** Returns the number of commands that have been registered.
  26485. @see registerCommand
  26486. */
  26487. int getNumCommands() const noexcept { return commands.size(); }
  26488. /** Returns the details about one of the registered commands.
  26489. The index is between 0 and (getNumCommands() - 1).
  26490. */
  26491. const ApplicationCommandInfo* getCommandForIndex (int index) const noexcept { return commands [index]; }
  26492. /** Returns the details about a given command ID.
  26493. This will search the list of registered commands for one with the given command
  26494. ID number, and return its associated info. If no matching command is found, this
  26495. will return 0.
  26496. */
  26497. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const noexcept;
  26498. /** Returns the name field for a command.
  26499. An empty string is returned if no command with this ID has been registered.
  26500. @see getDescriptionOfCommand
  26501. */
  26502. const String getNameOfCommand (CommandID commandID) const noexcept;
  26503. /** Returns the description field for a command.
  26504. An empty string is returned if no command with this ID has been registered. If the
  26505. command has no description, this will return its short name field instead.
  26506. @see getNameOfCommand
  26507. */
  26508. const String getDescriptionOfCommand (CommandID commandID) const noexcept;
  26509. /** Returns the list of categories.
  26510. This will go through all registered commands, and return a list of all the distict
  26511. categoryName values from their ApplicationCommandInfo structure.
  26512. @see getCommandsInCategory()
  26513. */
  26514. StringArray getCommandCategories() const;
  26515. /** Returns a list of all the command UIDs in a particular category.
  26516. @see getCommandCategories()
  26517. */
  26518. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  26519. /** Returns the manager's internal set of key mappings.
  26520. This object can be used to edit the keypresses. To actually link this object up
  26521. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  26522. class.
  26523. @see KeyPressMappingSet
  26524. */
  26525. KeyPressMappingSet* getKeyMappings() const noexcept { return keyMappings; }
  26526. /** Invokes the given command directly, sending it to the default target.
  26527. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  26528. structure.
  26529. */
  26530. bool invokeDirectly (CommandID commandID, bool asynchronously);
  26531. /** Sends a command to the default target.
  26532. This will choose a target using getFirstCommandTarget(), and send the specified command
  26533. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  26534. first target can't handle the command, it will be passed on to targets further down the
  26535. chain (see ApplicationCommandTarget::invoke() for more info).
  26536. @param invocationInfo this must be correctly filled-in, describing the context for
  26537. the invocation.
  26538. @param asynchronously if false, the command will be performed before this method returns.
  26539. If true, a message will be posted so that the command will be performed
  26540. later on the message thread, and this method will return immediately.
  26541. @see ApplicationCommandTarget::invoke
  26542. */
  26543. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  26544. bool asynchronously);
  26545. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  26546. Whenever the manager needs to know which target a command should be sent to, it calls
  26547. this method to determine the first one to try.
  26548. By default, this method will return the target that was set by calling setFirstCommandTarget().
  26549. If no target is set, it will return the result of findDefaultComponentTarget().
  26550. If you need to make sure all commands go via your own custom target, then you can
  26551. either use setFirstCommandTarget() to specify a single target, or override this method
  26552. if you need more complex logic to choose one.
  26553. It may return 0 if no targets are available.
  26554. @see getTargetForCommand, invoke, invokeDirectly
  26555. */
  26556. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  26557. /** Sets a target to be returned by getFirstCommandTarget().
  26558. If this is set to 0, then getFirstCommandTarget() will by default return the
  26559. result of findDefaultComponentTarget().
  26560. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  26561. deleting the target object.
  26562. */
  26563. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) noexcept;
  26564. /** Tries to find the best target to use to perform a given command.
  26565. This will call getFirstCommandTarget() to find the preferred target, and will
  26566. check whether that target can handle the given command. If it can't, then it'll use
  26567. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  26568. so on until no more are available.
  26569. If no targets are found that can perform the command, this method will return 0.
  26570. If a target is found, then it will get the target to fill-in the upToDateInfo
  26571. structure with the latest info about that command, so that the caller can see
  26572. whether the command is disabled, ticked, etc.
  26573. */
  26574. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  26575. ApplicationCommandInfo& upToDateInfo);
  26576. /** Registers a listener that will be called when various events occur. */
  26577. void addListener (ApplicationCommandManagerListener* listener);
  26578. /** Deregisters a previously-added listener. */
  26579. void removeListener (ApplicationCommandManagerListener* listener);
  26580. /** Looks for a suitable command target based on which Components have the keyboard focus.
  26581. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  26582. but is exposed here in case it's useful.
  26583. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  26584. windows, etc., and using the findTargetForComponent() method.
  26585. */
  26586. static ApplicationCommandTarget* findDefaultComponentTarget();
  26587. /** Examines this component and all its parents in turn, looking for the first one
  26588. which is a ApplicationCommandTarget.
  26589. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  26590. that class.
  26591. */
  26592. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  26593. private:
  26594. OwnedArray <ApplicationCommandInfo> commands;
  26595. ListenerList <ApplicationCommandManagerListener> listeners;
  26596. ScopedPointer <KeyPressMappingSet> keyMappings;
  26597. ApplicationCommandTarget* firstTarget;
  26598. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  26599. void handleAsyncUpdate();
  26600. void globalFocusChanged (Component*);
  26601. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  26602. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  26603. // version of this method.
  26604. virtual short getFirstCommandTarget() { return 0; }
  26605. #endif
  26606. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  26607. };
  26608. /**
  26609. A listener that receives callbacks from an ApplicationCommandManager when
  26610. commands are invoked or the command list is changed.
  26611. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  26612. */
  26613. class JUCE_API ApplicationCommandManagerListener
  26614. {
  26615. public:
  26616. /** Destructor. */
  26617. virtual ~ApplicationCommandManagerListener() {}
  26618. /** Called when an app command is about to be invoked. */
  26619. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  26620. /** Called when commands are registered or deregistered from the
  26621. command manager, or when commands are made active or inactive.
  26622. Note that if you're using this to watch for changes to whether a command is disabled,
  26623. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  26624. whenever the status of your command might have changed.
  26625. */
  26626. virtual void applicationCommandListChanged() = 0;
  26627. };
  26628. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  26629. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  26630. #endif
  26631. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  26632. #endif
  26633. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26634. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  26635. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26636. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26637. /*** Start of inlined file: juce_PropertiesFile.h ***/
  26638. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  26639. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  26640. /** Wrapper on a file that stores a list of key/value data pairs.
  26641. Useful for storing application settings, etc. See the PropertySet class for
  26642. the interfaces that read and write values.
  26643. Not designed for very large amounts of data, as it keeps all the values in
  26644. memory and writes them out to disk lazily when they are changed.
  26645. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  26646. with it, and these will be signalled when a value changes.
  26647. @see PropertySet
  26648. */
  26649. class JUCE_API PropertiesFile : public PropertySet,
  26650. public ChangeBroadcaster,
  26651. private Timer
  26652. {
  26653. public:
  26654. enum FileFormatOptions
  26655. {
  26656. ignoreCaseOfKeyNames = 1,
  26657. storeAsBinary = 2,
  26658. storeAsCompressedBinary = 4,
  26659. storeAsXML = 8
  26660. };
  26661. /**
  26662. Creates a PropertiesFile object.
  26663. @param file the file to use
  26664. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  26665. is changed, the object will wait for this amount
  26666. of time and then save the file. If zero, the file
  26667. will be written to disk immediately on being changed
  26668. (which might be slow, as it'll re-write synchronously
  26669. each time a value-change method is called). If it is
  26670. less than zero, the file won't be saved until
  26671. save() or saveIfNeeded() are explicitly called.
  26672. @param optionFlags a combination of the flags in the FileFormatOptions
  26673. enum, which specify the type of file to save, and other
  26674. options.
  26675. @param processLock an optional InterprocessLock object that will be used to
  26676. prevent multiple threads or processes from writing to the file
  26677. at the same time. The PropertiesFile will keep a pointer to
  26678. this object but will not take ownership of it - the caller is
  26679. responsible for making sure that the lock doesn't get deleted
  26680. before the PropertiesFile has been deleted.
  26681. */
  26682. PropertiesFile (const File& file,
  26683. int millisecondsBeforeSaving,
  26684. int optionFlags,
  26685. InterProcessLock* processLock = nullptr);
  26686. /** Destructor.
  26687. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  26688. */
  26689. ~PropertiesFile();
  26690. /** Returns true if this file was created from a valid (or non-existent) file.
  26691. If the file failed to load correctly because it was corrupt or had insufficient
  26692. access, this will be false.
  26693. */
  26694. bool isValidFile() const noexcept { return loadedOk; }
  26695. /** This will flush all the values to disk if they've changed since the last
  26696. time they were saved.
  26697. Returns false if it fails to write to the file for some reason (maybe because
  26698. it's read-only or the directory doesn't exist or something).
  26699. @see save
  26700. */
  26701. bool saveIfNeeded();
  26702. /** This will force a write-to-disk of the current values, regardless of whether
  26703. anything has changed since the last save.
  26704. Returns false if it fails to write to the file for some reason (maybe because
  26705. it's read-only or the directory doesn't exist or something).
  26706. @see saveIfNeeded
  26707. */
  26708. bool save();
  26709. /** Returns true if the properties have been altered since the last time they were saved.
  26710. The file is flagged as needing to be saved when you change a value, but you can
  26711. explicitly set this flag with setNeedsToBeSaved().
  26712. */
  26713. bool needsToBeSaved() const;
  26714. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  26715. @see needsToBeSaved
  26716. */
  26717. void setNeedsToBeSaved (bool needsToBeSaved);
  26718. /** Returns the file that's being used. */
  26719. File getFile() const { return file; }
  26720. /** Handy utility to create a properties file in whatever the standard OS-specific
  26721. location is for these things.
  26722. This uses getDefaultAppSettingsFile() to decide what file to create, then
  26723. creates a PropertiesFile object with the specified properties. See
  26724. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  26725. what the parameters do.
  26726. @see getDefaultAppSettingsFile
  26727. */
  26728. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  26729. const String& fileNameSuffix,
  26730. const String& folderName,
  26731. bool commonToAllUsers,
  26732. int millisecondsBeforeSaving,
  26733. int propertiesFileOptions,
  26734. InterProcessLock* processLock = nullptr);
  26735. /** Handy utility to choose a file in the standard OS-dependent location for application
  26736. settings files.
  26737. So on a Mac, this will return a file called:
  26738. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  26739. On Windows it'll return something like:
  26740. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  26741. On Linux it'll return
  26742. ~/.[folderName]/[applicationName].[fileNameSuffix]
  26743. If you pass an empty string as the folder name, it'll use the app name for this (or
  26744. omit the folder name on the Mac).
  26745. If commonToAllUsers is true, then this will return the same file for all users of the
  26746. computer, regardless of the current user. If it is false, the file will be specific to
  26747. only the current user. Use this to choose whether you're saving settings that are common
  26748. or user-specific.
  26749. */
  26750. static File getDefaultAppSettingsFile (const String& applicationName,
  26751. const String& fileNameSuffix,
  26752. const String& folderName,
  26753. bool commonToAllUsers);
  26754. protected:
  26755. virtual void propertyChanged();
  26756. private:
  26757. File file;
  26758. int timerInterval;
  26759. const int options;
  26760. bool loadedOk, needsWriting;
  26761. InterProcessLock* processLock;
  26762. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  26763. InterProcessLock::ScopedLockType* createProcessLock() const;
  26764. void timerCallback();
  26765. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  26766. };
  26767. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  26768. /*** End of inlined file: juce_PropertiesFile.h ***/
  26769. /**
  26770. Manages a collection of properties.
  26771. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  26772. as a singleton.
  26773. It holds two different PropertiesFile objects internally, one for user-specific
  26774. settings (stored in your user directory), and one for settings that are common to
  26775. all users (stored in a folder accessible to all users).
  26776. The class manages the creation of these files on-demand, allowing access via the
  26777. getUserSettings() and getCommonSettings() methods. It also has a few handy
  26778. methods like testWriteAccess() to check that the files can be saved.
  26779. If you're using one of these as a singleton, then your app's start-up code should
  26780. first of all call setStorageParameters() to tell it the parameters to use to create
  26781. the properties files.
  26782. @see PropertiesFile
  26783. */
  26784. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26785. {
  26786. public:
  26787. /**
  26788. Creates an ApplicationProperties object.
  26789. Before using it, you must call setStorageParameters() to give it the info
  26790. it needs to create the property files.
  26791. */
  26792. ApplicationProperties();
  26793. /** Destructor. */
  26794. ~ApplicationProperties();
  26795. juce_DeclareSingleton (ApplicationProperties, false)
  26796. /** Gives the object the information it needs to create the appropriate properties files.
  26797. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  26798. info about how these parameters are used.
  26799. */
  26800. void setStorageParameters (const String& applicationName,
  26801. const String& fileNameSuffix,
  26802. const String& folderName,
  26803. int millisecondsBeforeSaving,
  26804. int propertiesFileOptions,
  26805. InterProcessLock* processLock = nullptr);
  26806. /** Tests whether the files can be successfully written to, and can show
  26807. an error message if not.
  26808. Returns true if none of the tests fail.
  26809. @param testUserSettings if true, the user settings file will be tested
  26810. @param testCommonSettings if true, the common settings file will be tested
  26811. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26812. message box if either of the tests fail
  26813. */
  26814. bool testWriteAccess (bool testUserSettings,
  26815. bool testCommonSettings,
  26816. bool showWarningDialogOnFailure);
  26817. /** Returns the user settings file.
  26818. The first time this is called, it will create and load the properties file.
  26819. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26820. the common settings are used as a second-chance place to look. This is done via the
  26821. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26822. to the fallback for the user settings.
  26823. @see getCommonSettings
  26824. */
  26825. PropertiesFile* getUserSettings();
  26826. /** Returns the common settings file.
  26827. The first time this is called, it will create and load the properties file.
  26828. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26829. read-only (e.g. because the user doesn't have permission to write
  26830. to shared files), then this will return the user settings instead,
  26831. (like getUserSettings() would do). This is handy if you'd like to
  26832. write a value to the common settings, but if that's no possible,
  26833. then you'd rather write to the user settings than none at all.
  26834. If returnUserPropsIfReadOnly is false, this method will always return
  26835. the common settings, even if any changes to them can't be saved.
  26836. @see getUserSettings
  26837. */
  26838. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26839. /** Saves both files if they need to be saved.
  26840. @see PropertiesFile::saveIfNeeded
  26841. */
  26842. bool saveIfNeeded();
  26843. /** Flushes and closes both files if they are open.
  26844. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26845. and closes both files. They will then be re-opened the next time getUserSettings()
  26846. or getCommonSettings() is called.
  26847. */
  26848. void closeFiles();
  26849. private:
  26850. ScopedPointer <PropertiesFile> userProps, commonProps;
  26851. String appName, fileSuffix, folderName;
  26852. int msBeforeSaving, options;
  26853. int commonSettingsAreReadOnly;
  26854. InterProcessLock* processLock;
  26855. void openFiles();
  26856. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26857. };
  26858. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26859. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26860. #endif
  26861. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26862. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26863. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26864. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26865. /*** Start of inlined file: juce_AudioFormat.h ***/
  26866. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26867. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26868. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26869. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26870. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26871. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26872. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26873. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26874. /**
  26875. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26876. audio sample format class.
  26877. @see AudioData::Pointer.
  26878. */
  26879. class JUCE_API AudioData
  26880. {
  26881. public:
  26882. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26883. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26884. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26885. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26886. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26887. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26888. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26889. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26890. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26891. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26892. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26893. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26894. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26895. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26896. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26897. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26898. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26899. #ifndef DOXYGEN
  26900. class BigEndian
  26901. {
  26902. public:
  26903. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatBE(); }
  26904. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatBE (newValue); }
  26905. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32BE(); }
  26906. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32BE (newValue); }
  26907. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromBE (source); }
  26908. enum { isBigEndian = 1 };
  26909. };
  26910. class LittleEndian
  26911. {
  26912. public:
  26913. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatLE(); }
  26914. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatLE (newValue); }
  26915. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32LE(); }
  26916. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32LE (newValue); }
  26917. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromLE (source); }
  26918. enum { isBigEndian = 0 };
  26919. };
  26920. #if JUCE_BIG_ENDIAN
  26921. class NativeEndian : public BigEndian {};
  26922. #else
  26923. class NativeEndian : public LittleEndian {};
  26924. #endif
  26925. class Int8
  26926. {
  26927. public:
  26928. inline Int8 (void* data_) noexcept : data (static_cast <int8*> (data_)) {}
  26929. inline void advance() noexcept { ++data; }
  26930. inline void skip (int numSamples) noexcept { data += numSamples; }
  26931. inline float getAsFloatLE() const noexcept { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26932. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26933. inline void setAsFloatLE (float newValue) noexcept { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26934. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26935. inline int32 getAsInt32LE() const noexcept { return (int) (*data << 24); }
  26936. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26937. inline void setAsInt32LE (int newValue) noexcept { *data = (int8) (newValue >> 24); }
  26938. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26939. inline void clear() noexcept { *data = 0; }
  26940. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26941. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26942. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26943. inline void copyFromSameType (Int8& source) noexcept { *data = *source.data; }
  26944. int8* data;
  26945. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26946. };
  26947. class UInt8
  26948. {
  26949. public:
  26950. inline UInt8 (void* data_) noexcept : data (static_cast <uint8*> (data_)) {}
  26951. inline void advance() noexcept { ++data; }
  26952. inline void skip (int numSamples) noexcept { data += numSamples; }
  26953. inline float getAsFloatLE() const noexcept { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26954. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26955. inline void setAsFloatLE (float newValue) noexcept { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26956. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26957. inline int32 getAsInt32LE() const noexcept { return (int) ((*data - 128) << 24); }
  26958. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26959. inline void setAsInt32LE (int newValue) noexcept { *data = (uint8) (128 + (newValue >> 24)); }
  26960. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26961. inline void clear() noexcept { *data = 128; }
  26962. inline void clearMultiple (int num) noexcept { memset (data, 128, num) ;}
  26963. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26964. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26965. inline void copyFromSameType (UInt8& source) noexcept { *data = *source.data; }
  26966. uint8* data;
  26967. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26968. };
  26969. class Int16
  26970. {
  26971. public:
  26972. inline Int16 (void* data_) noexcept : data (static_cast <uint16*> (data_)) {}
  26973. inline void advance() noexcept { ++data; }
  26974. inline void skip (int numSamples) noexcept { data += numSamples; }
  26975. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26976. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26977. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26978. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26979. inline int32 getAsInt32LE() const noexcept { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26980. inline int32 getAsInt32BE() const noexcept { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26981. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26982. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26983. inline void clear() noexcept { *data = 0; }
  26984. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26985. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26986. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26987. inline void copyFromSameType (Int16& source) noexcept { *data = *source.data; }
  26988. uint16* data;
  26989. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26990. };
  26991. class Int24
  26992. {
  26993. public:
  26994. inline Int24 (void* data_) noexcept : data (static_cast <char*> (data_)) {}
  26995. inline void advance() noexcept { data += 3; }
  26996. inline void skip (int numSamples) noexcept { data += 3 * numSamples; }
  26997. inline float getAsFloatLE() const noexcept { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26998. inline float getAsFloatBE() const noexcept { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26999. inline void setAsFloatLE (float newValue) noexcept { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  27000. inline void setAsFloatBE (float newValue) noexcept { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  27001. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  27002. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  27003. inline void setAsInt32LE (int32 newValue) noexcept { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  27004. inline void setAsInt32BE (int32 newValue) noexcept { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  27005. inline void clear() noexcept { data[0] = 0; data[1] = 0; data[2] = 0; }
  27006. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27007. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  27008. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  27009. inline void copyFromSameType (Int24& source) noexcept { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  27010. char* data;
  27011. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  27012. };
  27013. class Int32
  27014. {
  27015. public:
  27016. inline Int32 (void* data_) noexcept : data (static_cast <uint32*> (data_)) {}
  27017. inline void advance() noexcept { ++data; }
  27018. inline void skip (int numSamples) noexcept { data += numSamples; }
  27019. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  27020. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  27021. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  27022. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  27023. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data); }
  27024. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  27025. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  27026. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  27027. inline void clear() noexcept { *data = 0; }
  27028. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27029. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  27030. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  27031. inline void copyFromSameType (Int32& source) noexcept { *data = *source.data; }
  27032. uint32* data;
  27033. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  27034. };
  27035. class Float32
  27036. {
  27037. public:
  27038. inline Float32 (void* data_) noexcept : data (static_cast <float*> (data_)) {}
  27039. inline void advance() noexcept { ++data; }
  27040. inline void skip (int numSamples) noexcept { data += numSamples; }
  27041. #if JUCE_BIG_ENDIAN
  27042. inline float getAsFloatBE() const noexcept { return *data; }
  27043. inline void setAsFloatBE (float newValue) noexcept { *data = newValue; }
  27044. inline float getAsFloatLE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  27045. inline void setAsFloatLE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  27046. #else
  27047. inline float getAsFloatLE() const noexcept { return *data; }
  27048. inline void setAsFloatLE (float newValue) noexcept { *data = newValue; }
  27049. inline float getAsFloatBE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  27050. inline void setAsFloatBE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  27051. #endif
  27052. inline int32 getAsInt32LE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
  27053. inline int32 getAsInt32BE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
  27054. inline void setAsInt32LE (int32 newValue) noexcept { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  27055. inline void setAsInt32BE (int32 newValue) noexcept { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  27056. inline void clear() noexcept { *data = 0; }
  27057. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27058. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsFloatLE (source.getAsFloat()); }
  27059. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsFloatBE (source.getAsFloat()); }
  27060. inline void copyFromSameType (Float32& source) noexcept { *data = *source.data; }
  27061. float* data;
  27062. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  27063. };
  27064. class NonInterleaved
  27065. {
  27066. public:
  27067. inline NonInterleaved() noexcept {}
  27068. inline NonInterleaved (const NonInterleaved&) noexcept {}
  27069. inline NonInterleaved (const int) noexcept {}
  27070. inline void copyFrom (const NonInterleaved&) noexcept {}
  27071. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.advance(); }
  27072. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numSamples); }
  27073. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { s.clearMultiple (numSamples); }
  27074. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) noexcept { return SampleFormatType::bytesPerSample; }
  27075. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  27076. };
  27077. class Interleaved
  27078. {
  27079. public:
  27080. inline Interleaved() noexcept : numInterleavedChannels (1) {}
  27081. inline Interleaved (const Interleaved& other) noexcept : numInterleavedChannels (other.numInterleavedChannels) {}
  27082. inline Interleaved (const int numInterleavedChannels_) noexcept : numInterleavedChannels (numInterleavedChannels_) {}
  27083. inline void copyFrom (const Interleaved& other) noexcept { numInterleavedChannels = other.numInterleavedChannels; }
  27084. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.skip (numInterleavedChannels); }
  27085. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numInterleavedChannels * numSamples); }
  27086. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  27087. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const noexcept { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  27088. int numInterleavedChannels;
  27089. enum { isInterleavedType = 1 };
  27090. };
  27091. class NonConst
  27092. {
  27093. public:
  27094. typedef void VoidType;
  27095. static inline void* toVoidPtr (VoidType* v) noexcept { return v; }
  27096. enum { isConst = 0 };
  27097. };
  27098. class Const
  27099. {
  27100. public:
  27101. typedef const void VoidType;
  27102. static inline void* toVoidPtr (VoidType* v) noexcept { return const_cast<void*> (v); }
  27103. enum { isConst = 1 };
  27104. };
  27105. #endif
  27106. /**
  27107. A pointer to a block of audio data with a particular encoding.
  27108. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  27109. the audio format as a series of template parameters, e.g.
  27110. @code
  27111. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  27112. AudioData::Pointer <AudioData::Int16,
  27113. AudioData::LittleEndian,
  27114. AudioData::NonInterleaved,
  27115. AudioData::Const> pointer (someRawAudioData);
  27116. // These methods read the sample that is being pointed to
  27117. float firstSampleAsFloat = pointer.getAsFloat();
  27118. int32 firstSampleAsInt = pointer.getAsInt32();
  27119. ++pointer; // moves the pointer to the next sample.
  27120. pointer += 3; // skips the next 3 samples.
  27121. @endcode
  27122. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  27123. converting its format.
  27124. @see AudioData::Converter
  27125. */
  27126. template <typename SampleFormat,
  27127. typename Endianness,
  27128. typename InterleavingType,
  27129. typename Constness>
  27130. class Pointer
  27131. {
  27132. public:
  27133. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  27134. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  27135. for interleaved formats, use the constructor that also takes a number of channels.
  27136. */
  27137. Pointer (typename Constness::VoidType* sourceData) noexcept
  27138. : data (Constness::toVoidPtr (sourceData))
  27139. {
  27140. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  27141. // you should pass NonInterleaved as the template parameter for the interleaving type!
  27142. static_jassert (InterleavingType::isInterleavedType == 0);
  27143. }
  27144. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  27145. For non-interleaved data, use the other constructor.
  27146. */
  27147. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) noexcept
  27148. : data (Constness::toVoidPtr (sourceData)),
  27149. interleaving (numInterleavedChannels)
  27150. {
  27151. }
  27152. /** Creates a copy of another pointer. */
  27153. Pointer (const Pointer& other) noexcept
  27154. : data (other.data),
  27155. interleaving (other.interleaving)
  27156. {
  27157. }
  27158. Pointer& operator= (const Pointer& other) noexcept
  27159. {
  27160. data = other.data;
  27161. interleaving.copyFrom (other.interleaving);
  27162. return *this;
  27163. }
  27164. /** Returns the value of the first sample as a floating point value.
  27165. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  27166. formats, the value could be outside that range, although -1 to 1 is the standard range.
  27167. */
  27168. inline float getAsFloat() const noexcept { return Endianness::getAsFloat (data); }
  27169. /** Sets the value of the first sample as a floating point value.
  27170. (This method can only be used if the AudioData::NonConst option was used).
  27171. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  27172. range will be clipped. For floating point formats, any value passed in here will be
  27173. written directly, although -1 to 1 is the standard range.
  27174. */
  27175. inline void setAsFloat (float newValue) noexcept
  27176. {
  27177. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27178. Endianness::setAsFloat (data, newValue);
  27179. }
  27180. /** Returns the value of the first sample as a 32-bit integer.
  27181. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  27182. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  27183. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  27184. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  27185. */
  27186. inline int32 getAsInt32() const noexcept { return Endianness::getAsInt32 (data); }
  27187. /** Sets the value of the first sample as a 32-bit integer.
  27188. This will be mapped to the range of the format that is being written - see getAsInt32().
  27189. */
  27190. inline void setAsInt32 (int32 newValue) noexcept
  27191. {
  27192. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27193. Endianness::setAsInt32 (data, newValue);
  27194. }
  27195. /** Moves the pointer along to the next sample. */
  27196. inline Pointer& operator++() noexcept { advance(); return *this; }
  27197. /** Moves the pointer back to the previous sample. */
  27198. inline Pointer& operator--() noexcept { interleaving.advanceDataBy (data, -1); return *this; }
  27199. /** Adds a number of samples to the pointer's position. */
  27200. Pointer& operator+= (int samplesToJump) noexcept { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  27201. /** Writes a stream of samples into this pointer from another pointer.
  27202. This will copy the specified number of samples, converting between formats appropriately.
  27203. */
  27204. void convertSamples (Pointer source, int numSamples) const noexcept
  27205. {
  27206. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27207. Pointer dest (*this);
  27208. while (--numSamples >= 0)
  27209. {
  27210. dest.data.copyFromSameType (source.data);
  27211. dest.advance();
  27212. source.advance();
  27213. }
  27214. }
  27215. /** Writes a stream of samples into this pointer from another pointer.
  27216. This will copy the specified number of samples, converting between formats appropriately.
  27217. */
  27218. template <class OtherPointerType>
  27219. void convertSamples (OtherPointerType source, int numSamples) const noexcept
  27220. {
  27221. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27222. Pointer dest (*this);
  27223. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  27224. {
  27225. while (--numSamples >= 0)
  27226. {
  27227. Endianness::copyFrom (dest.data, source);
  27228. dest.advance();
  27229. ++source;
  27230. }
  27231. }
  27232. else // copy backwards if we're increasing the sample width..
  27233. {
  27234. dest += numSamples;
  27235. source += numSamples;
  27236. while (--numSamples >= 0)
  27237. Endianness::copyFrom ((--dest).data, --source);
  27238. }
  27239. }
  27240. /** Sets a number of samples to zero. */
  27241. void clearSamples (int numSamples) const noexcept
  27242. {
  27243. Pointer dest (*this);
  27244. dest.interleaving.clear (dest.data, numSamples);
  27245. }
  27246. /** Returns true if the pointer is using a floating-point format. */
  27247. static bool isFloatingPoint() noexcept { return (bool) SampleFormat::isFloat; }
  27248. /** Returns true if the format is big-endian. */
  27249. static bool isBigEndian() noexcept { return (bool) Endianness::isBigEndian; }
  27250. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  27251. static int getBytesPerSample() noexcept { return (int) SampleFormat::bytesPerSample; }
  27252. /** Returns the number of interleaved channels in the format. */
  27253. int getNumInterleavedChannels() const noexcept { return (int) this->numInterleavedChannels; }
  27254. /** Returns the number of bytes between the start address of each sample. */
  27255. int getNumBytesBetweenSamples() const noexcept { return interleaving.getNumBytesBetweenSamples (data); }
  27256. /** Returns the accuracy of this format when represented as a 32-bit integer.
  27257. This is the smallest number above 0 that can be represented in the sample format, converted to
  27258. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  27259. its resolution is 0x100.
  27260. */
  27261. static int get32BitResolution() noexcept { return (int) SampleFormat::resolution; }
  27262. /** Returns a pointer to the underlying data. */
  27263. const void* getRawData() const noexcept { return data.data; }
  27264. private:
  27265. SampleFormat data;
  27266. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  27267. // advantage of EBCO causes an internal compiler error in VC6..
  27268. inline void advance() noexcept { interleaving.advanceData (data); }
  27269. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  27270. Pointer operator-- (int);
  27271. };
  27272. /** A base class for objects that are used to convert between two different sample formats.
  27273. The AudioData::ConverterInstance implements this base class and can be templated, so
  27274. you can create an instance that converts between two particular formats, and then
  27275. store this in the abstract base class.
  27276. @see AudioData::ConverterInstance
  27277. */
  27278. class Converter
  27279. {
  27280. public:
  27281. virtual ~Converter() {}
  27282. /** Converts a sequence of samples from the converter's source format into the dest format. */
  27283. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  27284. /** Converts a sequence of samples from the converter's source format into the dest format.
  27285. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  27286. particular sub-channel of the data to be used.
  27287. */
  27288. virtual void convertSamples (void* destSamples, int destSubChannel,
  27289. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  27290. };
  27291. /**
  27292. A class that converts between two templated AudioData::Pointer types, and which
  27293. implements the AudioData::Converter interface.
  27294. This can be used as a concrete instance of the AudioData::Converter abstract class.
  27295. @see AudioData::Converter
  27296. */
  27297. template <class SourceSampleType, class DestSampleType>
  27298. class ConverterInstance : public Converter
  27299. {
  27300. public:
  27301. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  27302. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  27303. {}
  27304. ~ConverterInstance() {}
  27305. void convertSamples (void* dest, const void* source, int numSamples) const
  27306. {
  27307. SourceSampleType s (source, sourceChannels);
  27308. DestSampleType d (dest, destChannels);
  27309. d.convertSamples (s, numSamples);
  27310. }
  27311. void convertSamples (void* dest, int destSubChannel,
  27312. const void* source, int sourceSubChannel, int numSamples) const
  27313. {
  27314. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  27315. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  27316. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  27317. d.convertSamples (s, numSamples);
  27318. }
  27319. private:
  27320. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  27321. const int sourceChannels, destChannels;
  27322. };
  27323. };
  27324. /**
  27325. A set of routines to convert buffers of 32-bit floating point data to and from
  27326. various integer formats.
  27327. Note that these functions are deprecated - the AudioData class provides a much more
  27328. flexible set of conversion classes now.
  27329. */
  27330. class JUCE_API AudioDataConverters
  27331. {
  27332. public:
  27333. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27334. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27335. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27336. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27337. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27338. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27339. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27340. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27341. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27342. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27343. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27344. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27345. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27346. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27347. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27348. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27349. enum DataFormat
  27350. {
  27351. int16LE,
  27352. int16BE,
  27353. int24LE,
  27354. int24BE,
  27355. int32LE,
  27356. int32BE,
  27357. float32LE,
  27358. float32BE,
  27359. };
  27360. static void convertFloatToFormat (DataFormat destFormat,
  27361. const float* source, void* dest, int numSamples);
  27362. static void convertFormatToFloat (DataFormat sourceFormat,
  27363. const void* source, float* dest, int numSamples);
  27364. static void interleaveSamples (const float** source, float* dest,
  27365. int numSamples, int numChannels);
  27366. static void deinterleaveSamples (const float* source, float** dest,
  27367. int numSamples, int numChannels);
  27368. private:
  27369. AudioDataConverters();
  27370. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  27371. };
  27372. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27373. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27374. class AudioFormat;
  27375. /**
  27376. Reads samples from an audio file stream.
  27377. A subclass that reads a specific type of audio format will be created by
  27378. an AudioFormat object.
  27379. @see AudioFormat, AudioFormatWriter
  27380. */
  27381. class JUCE_API AudioFormatReader
  27382. {
  27383. protected:
  27384. /** Creates an AudioFormatReader object.
  27385. @param sourceStream the stream to read from - this will be deleted
  27386. by this object when it is no longer needed. (Some
  27387. specialised readers might not use this parameter and
  27388. can leave it as 0).
  27389. @param formatName the description that will be returned by the getFormatName()
  27390. method
  27391. */
  27392. AudioFormatReader (InputStream* sourceStream,
  27393. const String& formatName);
  27394. public:
  27395. /** Destructor. */
  27396. virtual ~AudioFormatReader();
  27397. /** Returns a description of what type of format this is.
  27398. E.g. "AIFF"
  27399. */
  27400. const String getFormatName() const noexcept { return formatName; }
  27401. /** Reads samples from the stream.
  27402. @param destSamples an array of buffers into which the sample data for each
  27403. channel will be written.
  27404. If the format is fixed-point, each channel will be written
  27405. as an array of 32-bit signed integers using the full
  27406. range -0x80000000 to 0x7fffffff, regardless of the source's
  27407. bit-depth. If it is a floating-point format, you should cast
  27408. the resulting array to a (float**) to get the values (in the
  27409. range -1.0 to 1.0 or beyond)
  27410. If the format is stereo, then destSamples[0] is the left channel
  27411. data, and destSamples[1] is the right channel.
  27412. The numDestChannels parameter indicates how many pointers this array
  27413. contains, but some of these pointers can be null if you don't want to
  27414. read data for some of the channels
  27415. @param numDestChannels the number of array elements in the destChannels array
  27416. @param startSampleInSource the position in the audio file or stream at which the samples
  27417. should be read, as a number of samples from the start of the
  27418. stream. It's ok for this to be beyond the start or end of the
  27419. available data - any samples that are out-of-range will be returned
  27420. as zeros.
  27421. @param numSamplesToRead the number of samples to read. If this is greater than the number
  27422. of samples that the file or stream contains. the result will be padded
  27423. with zeros
  27424. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  27425. for some of the channels that you pass in, then they should be filled with
  27426. copies of valid source channels.
  27427. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  27428. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  27429. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  27430. was false, then only the first channel would be filled with the file's contents, and
  27431. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  27432. from a stereo file, then the last 3 would all end up with copies of the same data.
  27433. @returns true if the operation succeeded, false if there was an error. Note
  27434. that reading sections of data beyond the extent of the stream isn't an
  27435. error - the reader should just return zeros for these regions
  27436. @see readMaxLevels
  27437. */
  27438. bool read (int* const* destSamples,
  27439. int numDestChannels,
  27440. int64 startSampleInSource,
  27441. int numSamplesToRead,
  27442. bool fillLeftoverChannelsWithCopies);
  27443. /** Finds the highest and lowest sample levels from a section of the audio stream.
  27444. This will read a block of samples from the stream, and measure the
  27445. highest and lowest sample levels from the channels in that section, returning
  27446. these as normalised floating-point levels.
  27447. @param startSample the offset into the audio stream to start reading from. It's
  27448. ok for this to be beyond the start or end of the stream.
  27449. @param numSamples how many samples to read
  27450. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  27451. @param highestLeft on return, this is the highest absolute sample from the left channel
  27452. @param lowestRight on return, this is the lowest absolute sample from the right
  27453. channel (if there is one)
  27454. @param highestRight on return, this is the highest absolute sample from the right
  27455. channel (if there is one)
  27456. @see read
  27457. */
  27458. virtual void readMaxLevels (int64 startSample,
  27459. int64 numSamples,
  27460. float& lowestLeft,
  27461. float& highestLeft,
  27462. float& lowestRight,
  27463. float& highestRight);
  27464. /** Scans the source looking for a sample whose magnitude is in a specified range.
  27465. This will read from the source, either forwards or backwards between two sample
  27466. positions, until it finds a sample whose magnitude lies between two specified levels.
  27467. If it finds a suitable sample, it returns its position; if not, it will return -1.
  27468. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  27469. points when you're searching for a continuous range of samples
  27470. @param startSample the first sample to look at
  27471. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  27472. the search will go backwards
  27473. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27474. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27475. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  27476. of this many consecutive samples, all of which lie
  27477. within the target range. When it finds such a sequence,
  27478. it returns the position of the first in-range sample
  27479. it found (i.e. the earliest one if scanning forwards, the
  27480. latest one if scanning backwards)
  27481. */
  27482. int64 searchForLevel (int64 startSample,
  27483. int64 numSamplesToSearch,
  27484. double magnitudeRangeMinimum,
  27485. double magnitudeRangeMaximum,
  27486. int minimumConsecutiveSamples);
  27487. /** The sample-rate of the stream. */
  27488. double sampleRate;
  27489. /** The number of bits per sample, e.g. 16, 24, 32. */
  27490. unsigned int bitsPerSample;
  27491. /** The total number of samples in the audio stream. */
  27492. int64 lengthInSamples;
  27493. /** The total number of channels in the audio stream. */
  27494. unsigned int numChannels;
  27495. /** Indicates whether the data is floating-point or fixed. */
  27496. bool usesFloatingPointData;
  27497. /** A set of metadata values that the reader has pulled out of the stream.
  27498. Exactly what these values are depends on the format, so you can
  27499. check out the format implementation code to see what kind of stuff
  27500. they understand.
  27501. */
  27502. StringPairArray metadataValues;
  27503. /** The input stream, for use by subclasses. */
  27504. InputStream* input;
  27505. /** Subclasses must implement this method to perform the low-level read operation.
  27506. Callers should use read() instead of calling this directly.
  27507. @param destSamples the array of destination buffers to fill. Some of these
  27508. pointers may be null
  27509. @param numDestChannels the number of items in the destSamples array. This
  27510. value is guaranteed not to be greater than the number of
  27511. channels that this reader object contains
  27512. @param startOffsetInDestBuffer the number of samples from the start of the
  27513. dest data at which to begin writing
  27514. @param startSampleInFile the number of samples into the source data at which
  27515. to begin reading. This value is guaranteed to be >= 0.
  27516. @param numSamples the number of samples to read
  27517. */
  27518. virtual bool readSamples (int** destSamples,
  27519. int numDestChannels,
  27520. int startOffsetInDestBuffer,
  27521. int64 startSampleInFile,
  27522. int numSamples) = 0;
  27523. protected:
  27524. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  27525. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  27526. struct ReadHelper
  27527. {
  27528. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  27529. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  27530. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) noexcept
  27531. {
  27532. for (int i = 0; i < numDestChannels; ++i)
  27533. {
  27534. if (destData[i] != nullptr)
  27535. {
  27536. DestType dest (destData[i]);
  27537. dest += destOffset;
  27538. if (i < numSourceChannels)
  27539. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  27540. else
  27541. dest.clearSamples (numSamples);
  27542. }
  27543. }
  27544. }
  27545. };
  27546. private:
  27547. String formatName;
  27548. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  27549. };
  27550. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27551. /*** End of inlined file: juce_AudioFormatReader.h ***/
  27552. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  27553. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27554. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27555. /*** Start of inlined file: juce_AudioSource.h ***/
  27556. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27557. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  27558. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  27559. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27560. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27561. class AudioFormatReader;
  27562. class AudioFormatWriter;
  27563. /**
  27564. A multi-channel buffer of 32-bit floating point audio samples.
  27565. */
  27566. class JUCE_API AudioSampleBuffer
  27567. {
  27568. public:
  27569. /** Creates a buffer with a specified number of channels and samples.
  27570. The contents of the buffer will initially be undefined, so use clear() to
  27571. set all the samples to zero.
  27572. The buffer will allocate its memory internally, and this will be released
  27573. when the buffer is deleted.
  27574. */
  27575. AudioSampleBuffer (int numChannels,
  27576. int numSamples) noexcept;
  27577. /** Creates a buffer using a pre-allocated block of memory.
  27578. Note that if the buffer is resized or its number of channels is changed, it
  27579. will re-allocate memory internally and copy the existing data to this new area,
  27580. so it will then stop directly addressing this memory.
  27581. @param dataToReferTo a pre-allocated array containing pointers to the data
  27582. for each channel that should be used by this buffer. The
  27583. buffer will only refer to this memory, it won't try to delete
  27584. it when the buffer is deleted or resized.
  27585. @param numChannels the number of channels to use - this must correspond to the
  27586. number of elements in the array passed in
  27587. @param numSamples the number of samples to use - this must correspond to the
  27588. size of the arrays passed in
  27589. */
  27590. AudioSampleBuffer (float** dataToReferTo,
  27591. int numChannels,
  27592. int numSamples) noexcept;
  27593. /** Creates a buffer using a pre-allocated block of memory.
  27594. Note that if the buffer is resized or its number of channels is changed, it
  27595. will re-allocate memory internally and copy the existing data to this new area,
  27596. so it will then stop directly addressing this memory.
  27597. @param dataToReferTo a pre-allocated array containing pointers to the data
  27598. for each channel that should be used by this buffer. The
  27599. buffer will only refer to this memory, it won't try to delete
  27600. it when the buffer is deleted or resized.
  27601. @param numChannels the number of channels to use - this must correspond to the
  27602. number of elements in the array passed in
  27603. @param startSample the offset within the arrays at which the data begins
  27604. @param numSamples the number of samples to use - this must correspond to the
  27605. size of the arrays passed in
  27606. */
  27607. AudioSampleBuffer (float** dataToReferTo,
  27608. int numChannels,
  27609. int startSample,
  27610. int numSamples) noexcept;
  27611. /** Copies another buffer.
  27612. This buffer will make its own copy of the other's data, unless the buffer was created
  27613. using an external data buffer, in which case boths buffers will just point to the same
  27614. shared block of data.
  27615. */
  27616. AudioSampleBuffer (const AudioSampleBuffer& other) noexcept;
  27617. /** Copies another buffer onto this one.
  27618. This buffer's size will be changed to that of the other buffer.
  27619. */
  27620. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) noexcept;
  27621. /** Destructor.
  27622. This will free any memory allocated by the buffer.
  27623. */
  27624. virtual ~AudioSampleBuffer() noexcept;
  27625. /** Returns the number of channels of audio data that this buffer contains.
  27626. @see getSampleData
  27627. */
  27628. int getNumChannels() const noexcept { return numChannels; }
  27629. /** Returns the number of samples allocated in each of the buffer's channels.
  27630. @see getSampleData
  27631. */
  27632. int getNumSamples() const noexcept { return size; }
  27633. /** Returns a pointer one of the buffer's channels.
  27634. For speed, this doesn't check whether the channel number is out of range,
  27635. so be careful when using it!
  27636. */
  27637. float* getSampleData (const int channelNumber) const noexcept
  27638. {
  27639. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27640. return channels [channelNumber];
  27641. }
  27642. /** Returns a pointer to a sample in one of the buffer's channels.
  27643. For speed, this doesn't check whether the channel and sample number
  27644. are out-of-range, so be careful when using it!
  27645. */
  27646. float* getSampleData (const int channelNumber,
  27647. const int sampleOffset) const noexcept
  27648. {
  27649. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27650. jassert (isPositiveAndBelow (sampleOffset, size));
  27651. return channels [channelNumber] + sampleOffset;
  27652. }
  27653. /** Returns an array of pointers to the channels in the buffer.
  27654. Don't modify any of the pointers that are returned, and bear in mind that
  27655. these will become invalid if the buffer is resized.
  27656. */
  27657. float** getArrayOfChannels() const noexcept { return channels; }
  27658. /** Changes the buffer's size or number of channels.
  27659. This can expand or contract the buffer's length, and add or remove channels.
  27660. If keepExistingContent is true, it will try to preserve as much of the
  27661. old data as it can in the new buffer.
  27662. If clearExtraSpace is true, then any extra channels or space that is
  27663. allocated will be also be cleared. If false, then this space is left
  27664. uninitialised.
  27665. If avoidReallocating is true, then changing the buffer's size won't reduce the
  27666. amount of memory that is currently allocated (but it will still increase it if
  27667. the new size is bigger than the amount it currently has). If this is false, then
  27668. a new allocation will be done so that the buffer uses takes up the minimum amount
  27669. of memory that it needs.
  27670. */
  27671. void setSize (int newNumChannels,
  27672. int newNumSamples,
  27673. bool keepExistingContent = false,
  27674. bool clearExtraSpace = false,
  27675. bool avoidReallocating = false) noexcept;
  27676. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  27677. There's also a constructor that lets you specify arrays like this, but this
  27678. lets you change the channels dynamically.
  27679. Note that if the buffer is resized or its number of channels is changed, it
  27680. will re-allocate memory internally and copy the existing data to this new area,
  27681. so it will then stop directly addressing this memory.
  27682. @param dataToReferTo a pre-allocated array containing pointers to the data
  27683. for each channel that should be used by this buffer. The
  27684. buffer will only refer to this memory, it won't try to delete
  27685. it when the buffer is deleted or resized.
  27686. @param numChannels the number of channels to use - this must correspond to the
  27687. number of elements in the array passed in
  27688. @param numSamples the number of samples to use - this must correspond to the
  27689. size of the arrays passed in
  27690. */
  27691. void setDataToReferTo (float** dataToReferTo,
  27692. int numChannels,
  27693. int numSamples) noexcept;
  27694. /** Clears all the samples in all channels. */
  27695. void clear() noexcept;
  27696. /** Clears a specified region of all the channels.
  27697. For speed, this doesn't check whether the channel and sample number
  27698. are in-range, so be careful!
  27699. */
  27700. void clear (int startSample,
  27701. int numSamples) noexcept;
  27702. /** Clears a specified region of just one channel.
  27703. For speed, this doesn't check whether the channel and sample number
  27704. are in-range, so be careful!
  27705. */
  27706. void clear (int channel,
  27707. int startSample,
  27708. int numSamples) noexcept;
  27709. /** Applies a gain multiple to a region of one channel.
  27710. For speed, this doesn't check whether the channel and sample number
  27711. are in-range, so be careful!
  27712. */
  27713. void applyGain (int channel,
  27714. int startSample,
  27715. int numSamples,
  27716. float gain) noexcept;
  27717. /** Applies a gain multiple to a region of all the channels.
  27718. For speed, this doesn't check whether the sample numbers
  27719. are in-range, so be careful!
  27720. */
  27721. void applyGain (int startSample,
  27722. int numSamples,
  27723. float gain) noexcept;
  27724. /** Applies a range of gains to a region of a channel.
  27725. The gain that is applied to each sample will vary from
  27726. startGain on the first sample to endGain on the last Sample,
  27727. so it can be used to do basic fades.
  27728. For speed, this doesn't check whether the sample numbers
  27729. are in-range, so be careful!
  27730. */
  27731. void applyGainRamp (int channel,
  27732. int startSample,
  27733. int numSamples,
  27734. float startGain,
  27735. float endGain) noexcept;
  27736. /** Adds samples from another buffer to this one.
  27737. @param destChannel the channel within this buffer to add the samples to
  27738. @param destStartSample the start sample within this buffer's channel
  27739. @param source the source buffer to add from
  27740. @param sourceChannel the channel within the source buffer to read from
  27741. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27742. @param numSamples the number of samples to process
  27743. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27744. added to this buffer's samples
  27745. @see copyFrom
  27746. */
  27747. void addFrom (int destChannel,
  27748. int destStartSample,
  27749. const AudioSampleBuffer& source,
  27750. int sourceChannel,
  27751. int sourceStartSample,
  27752. int numSamples,
  27753. float gainToApplyToSource = 1.0f) noexcept;
  27754. /** Adds samples from an array of floats to one of the channels.
  27755. @param destChannel the channel within this buffer to add the samples to
  27756. @param destStartSample the start sample within this buffer's channel
  27757. @param source the source data to use
  27758. @param numSamples the number of samples to process
  27759. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27760. added to this buffer's samples
  27761. @see copyFrom
  27762. */
  27763. void addFrom (int destChannel,
  27764. int destStartSample,
  27765. const float* source,
  27766. int numSamples,
  27767. float gainToApplyToSource = 1.0f) noexcept;
  27768. /** Adds samples from an array of floats, applying a gain ramp to them.
  27769. @param destChannel the channel within this buffer to add the samples to
  27770. @param destStartSample the start sample within this buffer's channel
  27771. @param source the source data to use
  27772. @param numSamples the number of samples to process
  27773. @param startGain the gain to apply to the first sample (this is multiplied with
  27774. the source samples before they are added to this buffer)
  27775. @param endGain the gain to apply to the final sample. The gain is linearly
  27776. interpolated between the first and last samples.
  27777. */
  27778. void addFromWithRamp (int destChannel,
  27779. int destStartSample,
  27780. const float* source,
  27781. int numSamples,
  27782. float startGain,
  27783. float endGain) noexcept;
  27784. /** Copies samples from another buffer to this one.
  27785. @param destChannel the channel within this buffer to copy the samples to
  27786. @param destStartSample the start sample within this buffer's channel
  27787. @param source the source buffer to read from
  27788. @param sourceChannel the channel within the source buffer to read from
  27789. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27790. @param numSamples the number of samples to process
  27791. @see addFrom
  27792. */
  27793. void copyFrom (int destChannel,
  27794. int destStartSample,
  27795. const AudioSampleBuffer& source,
  27796. int sourceChannel,
  27797. int sourceStartSample,
  27798. int numSamples) noexcept;
  27799. /** Copies samples from an array of floats into one of the channels.
  27800. @param destChannel the channel within this buffer to copy the samples to
  27801. @param destStartSample the start sample within this buffer's channel
  27802. @param source the source buffer to read from
  27803. @param numSamples the number of samples to process
  27804. @see addFrom
  27805. */
  27806. void copyFrom (int destChannel,
  27807. int destStartSample,
  27808. const float* source,
  27809. int numSamples) noexcept;
  27810. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27811. @param destChannel the channel within this buffer to copy the samples to
  27812. @param destStartSample the start sample within this buffer's channel
  27813. @param source the source buffer to read from
  27814. @param numSamples the number of samples to process
  27815. @param gain the gain to apply
  27816. @see addFrom
  27817. */
  27818. void copyFrom (int destChannel,
  27819. int destStartSample,
  27820. const float* source,
  27821. int numSamples,
  27822. float gain) noexcept;
  27823. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27824. @param destChannel the channel within this buffer to copy the samples to
  27825. @param destStartSample the start sample within this buffer's channel
  27826. @param source the source buffer to read from
  27827. @param numSamples the number of samples to process
  27828. @param startGain the gain to apply to the first sample (this is multiplied with
  27829. the source samples before they are copied to this buffer)
  27830. @param endGain the gain to apply to the final sample. The gain is linearly
  27831. interpolated between the first and last samples.
  27832. @see addFrom
  27833. */
  27834. void copyFromWithRamp (int destChannel,
  27835. int destStartSample,
  27836. const float* source,
  27837. int numSamples,
  27838. float startGain,
  27839. float endGain) noexcept;
  27840. /** Finds the highest and lowest sample values in a given range.
  27841. @param channel the channel to read from
  27842. @param startSample the start sample within the channel
  27843. @param numSamples the number of samples to check
  27844. @param minVal on return, the lowest value that was found
  27845. @param maxVal on return, the highest value that was found
  27846. */
  27847. void findMinMax (int channel,
  27848. int startSample,
  27849. int numSamples,
  27850. float& minVal,
  27851. float& maxVal) const noexcept;
  27852. /** Finds the highest absolute sample value within a region of a channel.
  27853. */
  27854. float getMagnitude (int channel,
  27855. int startSample,
  27856. int numSamples) const noexcept;
  27857. /** Finds the highest absolute sample value within a region on all channels.
  27858. */
  27859. float getMagnitude (int startSample,
  27860. int numSamples) const noexcept;
  27861. /** Returns the root mean squared level for a region of a channel.
  27862. */
  27863. float getRMSLevel (int channel,
  27864. int startSample,
  27865. int numSamples) const noexcept;
  27866. /** Fills a section of the buffer using an AudioReader as its source.
  27867. This will convert the reader's fixed- or floating-point data to
  27868. the buffer's floating-point format, and will try to intelligently
  27869. cope with mismatches between the number of channels in the reader
  27870. and the buffer.
  27871. @see writeToAudioWriter
  27872. */
  27873. void readFromAudioReader (AudioFormatReader* reader,
  27874. int startSample,
  27875. int numSamples,
  27876. int64 readerStartSample,
  27877. bool useReaderLeftChan,
  27878. bool useReaderRightChan);
  27879. /** Writes a section of this buffer to an audio writer.
  27880. This saves you having to mess about with channels or floating/fixed
  27881. point conversion.
  27882. @see readFromAudioReader
  27883. */
  27884. void writeToAudioWriter (AudioFormatWriter* writer,
  27885. int startSample,
  27886. int numSamples) const;
  27887. private:
  27888. int numChannels, size;
  27889. size_t allocatedBytes;
  27890. float** channels;
  27891. HeapBlock <char> allocatedData;
  27892. float* preallocatedChannelSpace [32];
  27893. void allocateData();
  27894. void allocateChannels (float** dataToReferTo, int offset);
  27895. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27896. };
  27897. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27898. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27899. /**
  27900. Used by AudioSource::getNextAudioBlock().
  27901. */
  27902. struct JUCE_API AudioSourceChannelInfo
  27903. {
  27904. /** The destination buffer to fill with audio data.
  27905. When the AudioSource::getNextAudioBlock() method is called, the active section
  27906. of this buffer should be filled with whatever output the source produces.
  27907. Only the samples specified by the startSample and numSamples members of this structure
  27908. should be affected by the call.
  27909. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27910. method can be treated as the input if the source is performing some kind of filter operation,
  27911. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27912. a handy way of doing this.
  27913. The number of channels in the buffer could be anything, so the AudioSource
  27914. must cope with this in whatever way is appropriate for its function.
  27915. */
  27916. AudioSampleBuffer* buffer;
  27917. /** The first sample in the buffer from which the callback is expected
  27918. to write data. */
  27919. int startSample;
  27920. /** The number of samples in the buffer which the callback is expected to
  27921. fill with data. */
  27922. int numSamples;
  27923. /** Convenient method to clear the buffer if the source is not producing any data. */
  27924. void clearActiveBufferRegion() const
  27925. {
  27926. if (buffer != nullptr)
  27927. buffer->clear (startSample, numSamples);
  27928. }
  27929. };
  27930. /**
  27931. Base class for objects that can produce a continuous stream of audio.
  27932. An AudioSource has two states: 'prepared' and 'unprepared'.
  27933. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27934. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27935. process the audio data.
  27936. Once playback has finished, the releaseResources() method is called to put the stream
  27937. back into an 'unprepared' state.
  27938. @see AudioFormatReaderSource, ResamplingAudioSource
  27939. */
  27940. class JUCE_API AudioSource
  27941. {
  27942. protected:
  27943. /** Creates an AudioSource. */
  27944. AudioSource() noexcept {}
  27945. public:
  27946. /** Destructor. */
  27947. virtual ~AudioSource() {}
  27948. /** Tells the source to prepare for playing.
  27949. An AudioSource has two states: prepared and unprepared.
  27950. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27951. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27952. This callback allows the source to initialise any resources it might need when playing.
  27953. Once playback has finished, the releaseResources() method is called to put the stream
  27954. back into an 'unprepared' state.
  27955. Note that this method could be called more than once in succession without
  27956. a matching call to releaseResources(), so make sure your code is robust and
  27957. can handle that kind of situation.
  27958. @param samplesPerBlockExpected the number of samples that the source
  27959. will be expected to supply each time its
  27960. getNextAudioBlock() method is called. This
  27961. number may vary slightly, because it will be dependent
  27962. on audio hardware callbacks, and these aren't
  27963. guaranteed to always use a constant block size, so
  27964. the source should be able to cope with small variations.
  27965. @param sampleRate the sample rate that the output will be used at - this
  27966. is needed by sources such as tone generators.
  27967. @see releaseResources, getNextAudioBlock
  27968. */
  27969. virtual void prepareToPlay (int samplesPerBlockExpected,
  27970. double sampleRate) = 0;
  27971. /** Allows the source to release anything it no longer needs after playback has stopped.
  27972. This will be called when the source is no longer going to have its getNextAudioBlock()
  27973. method called, so it should release any spare memory, etc. that it might have
  27974. allocated during the prepareToPlay() call.
  27975. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27976. releaseResources(), and it may be called more than once in succession, so make sure your
  27977. code is robust and doesn't make any assumptions about when it will be called.
  27978. @see prepareToPlay, getNextAudioBlock
  27979. */
  27980. virtual void releaseResources() = 0;
  27981. /** Called repeatedly to fetch subsequent blocks of audio data.
  27982. After calling the prepareToPlay() method, this callback will be made each
  27983. time the audio playback hardware (or whatever other destination the audio
  27984. data is going to) needs another block of data.
  27985. It will generally be called on a high-priority system thread, or possibly even
  27986. an interrupt, so be careful not to do too much work here, as that will cause
  27987. audio glitches!
  27988. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27989. */
  27990. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27991. };
  27992. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27993. /*** End of inlined file: juce_AudioSource.h ***/
  27994. class AudioThumbnail;
  27995. /**
  27996. Writes samples to an audio file stream.
  27997. A subclass that writes a specific type of audio format will be created by
  27998. an AudioFormat object.
  27999. After creating one of these with the AudioFormat::createWriterFor() method
  28000. you can call its write() method to store the samples, and then delete it.
  28001. @see AudioFormat, AudioFormatReader
  28002. */
  28003. class JUCE_API AudioFormatWriter
  28004. {
  28005. protected:
  28006. /** Creates an AudioFormatWriter object.
  28007. @param destStream the stream to write to - this will be deleted
  28008. by this object when it is no longer needed
  28009. @param formatName the description that will be returned by the getFormatName()
  28010. method
  28011. @param sampleRate the sample rate to use - the base class just stores
  28012. this value, it doesn't do anything with it
  28013. @param numberOfChannels the number of channels to write - the base class just stores
  28014. this value, it doesn't do anything with it
  28015. @param bitsPerSample the bit depth of the stream - the base class just stores
  28016. this value, it doesn't do anything with it
  28017. */
  28018. AudioFormatWriter (OutputStream* destStream,
  28019. const String& formatName,
  28020. double sampleRate,
  28021. unsigned int numberOfChannels,
  28022. unsigned int bitsPerSample);
  28023. public:
  28024. /** Destructor. */
  28025. virtual ~AudioFormatWriter();
  28026. /** Returns a description of what type of format this is.
  28027. E.g. "AIFF file"
  28028. */
  28029. const String getFormatName() const noexcept { return formatName; }
  28030. /** Writes a set of samples to the audio stream.
  28031. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  28032. can use AudioSampleBuffer::writeToAudioWriter().
  28033. @param samplesToWrite an array of arrays containing the sample data for
  28034. each channel to write. This is a zero-terminated
  28035. array of arrays, and can contain a different number
  28036. of channels than the actual stream uses, and the
  28037. writer should do its best to cope with this.
  28038. If the format is fixed-point, each channel will be formatted
  28039. as an array of signed integers using the full 32-bit
  28040. range -0x80000000 to 0x7fffffff, regardless of the source's
  28041. bit-depth. If it is a floating-point format, you should treat
  28042. the arrays as arrays of floats, and just cast it to an (int**)
  28043. to pass it into the method.
  28044. @param numSamples the number of samples to write
  28045. */
  28046. virtual bool write (const int** samplesToWrite,
  28047. int numSamples) = 0;
  28048. /** Reads a section of samples from an AudioFormatReader, and writes these to
  28049. the output.
  28050. This will take care of any floating-point conversion that's required to convert
  28051. between the two formats. It won't deal with sample-rate conversion, though.
  28052. If numSamplesToRead < 0, it will write the entire length of the reader.
  28053. @returns false if it can't read or write properly during the operation
  28054. */
  28055. bool writeFromAudioReader (AudioFormatReader& reader,
  28056. int64 startSample,
  28057. int64 numSamplesToRead);
  28058. /** Reads some samples from an AudioSource, and writes these to the output.
  28059. The source must already have been initialised with the AudioSource::prepareToPlay() method
  28060. @param source the source to read from
  28061. @param numSamplesToRead total number of samples to read and write
  28062. @param samplesPerBlock the maximum number of samples to fetch from the source
  28063. @returns false if it can't read or write properly during the operation
  28064. */
  28065. bool writeFromAudioSource (AudioSource& source,
  28066. int numSamplesToRead,
  28067. int samplesPerBlock = 2048);
  28068. /** Writes some samples from an AudioSampleBuffer.
  28069. */
  28070. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  28071. int startSample, int numSamples);
  28072. /** Returns the sample rate being used. */
  28073. double getSampleRate() const noexcept { return sampleRate; }
  28074. /** Returns the number of channels being written. */
  28075. int getNumChannels() const noexcept { return numChannels; }
  28076. /** Returns the bit-depth of the data being written. */
  28077. int getBitsPerSample() const noexcept { return bitsPerSample; }
  28078. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  28079. bool isFloatingPoint() const noexcept { return usesFloatingPointData; }
  28080. /**
  28081. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  28082. data into a buffer which will be flushed to disk by a background thread.
  28083. */
  28084. class ThreadedWriter
  28085. {
  28086. public:
  28087. /** Creates a ThreadedWriter for a given writer and a thread.
  28088. The writer object which is passed in here will be owned and deleted by
  28089. the ThreadedWriter when it is no longer needed.
  28090. To stop the writer and flush the buffer to disk, simply delete this object.
  28091. */
  28092. ThreadedWriter (AudioFormatWriter* writer,
  28093. TimeSliceThread& backgroundThread,
  28094. int numSamplesToBuffer);
  28095. /** Destructor. */
  28096. ~ThreadedWriter();
  28097. /** Pushes some incoming audio data into the FIFO.
  28098. If there's enough free space in the buffer, this will add the data to it,
  28099. If the FIFO is too full to accept this many samples, the method will return
  28100. false - then you could either wait until the background thread has had time to
  28101. consume some of the buffered data and try again, or you can give up
  28102. and lost this block.
  28103. The data must be an array containing the same number of channels as the
  28104. AudioFormatWriter object is using. None of these channels can be null.
  28105. */
  28106. bool write (const float** data, int numSamples);
  28107. /** Allows you to specify a thumbnail that this writer should update with the
  28108. incoming data.
  28109. The thumbnail will be cleared and will the writer will begin adding data to
  28110. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  28111. */
  28112. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  28113. /** @internal */
  28114. class Buffer; // (only public for VC6 compatibility)
  28115. private:
  28116. friend class ScopedPointer<Buffer>;
  28117. ScopedPointer<Buffer> buffer;
  28118. };
  28119. protected:
  28120. /** The sample rate of the stream. */
  28121. double sampleRate;
  28122. /** The number of channels being written to the stream. */
  28123. unsigned int numChannels;
  28124. /** The bit depth of the file. */
  28125. unsigned int bitsPerSample;
  28126. /** True if it's a floating-point format, false if it's fixed-point. */
  28127. bool usesFloatingPointData;
  28128. /** The output stream for Use by subclasses. */
  28129. OutputStream* output;
  28130. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  28131. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  28132. struct WriteHelper
  28133. {
  28134. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  28135. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  28136. static void write (void* destData, int numDestChannels, const int** source,
  28137. int numSamples, const int sourceOffset = 0) noexcept
  28138. {
  28139. for (int i = 0; i < numDestChannels; ++i)
  28140. {
  28141. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  28142. if (*source != nullptr)
  28143. {
  28144. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  28145. ++source;
  28146. }
  28147. else
  28148. {
  28149. dest.clearSamples (numSamples);
  28150. }
  28151. }
  28152. }
  28153. };
  28154. private:
  28155. String formatName;
  28156. friend class ThreadedWriter;
  28157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  28158. };
  28159. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28160. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  28161. /**
  28162. Subclasses of AudioFormat are used to read and write different audio
  28163. file formats.
  28164. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  28165. */
  28166. class JUCE_API AudioFormat
  28167. {
  28168. public:
  28169. /** Destructor. */
  28170. virtual ~AudioFormat();
  28171. /** Returns the name of this format.
  28172. e.g. "WAV file" or "AIFF file"
  28173. */
  28174. const String& getFormatName() const;
  28175. /** Returns all the file extensions that might apply to a file of this format.
  28176. The first item will be the one that's preferred when creating a new file.
  28177. So for a wav file this might just return ".wav"; for an AIFF file it might
  28178. return two items, ".aif" and ".aiff"
  28179. */
  28180. const StringArray& getFileExtensions() const;
  28181. /** Returns true if this the given file can be read by this format.
  28182. Subclasses shouldn't do too much work here, just check the extension or
  28183. file type. The base class implementation just checks the file's extension
  28184. against one of the ones that was registered in the constructor.
  28185. */
  28186. virtual bool canHandleFile (const File& fileToTest);
  28187. /** Returns a set of sample rates that the format can read and write. */
  28188. virtual const Array <int> getPossibleSampleRates() = 0;
  28189. /** Returns a set of bit depths that the format can read and write. */
  28190. virtual const Array <int> getPossibleBitDepths() = 0;
  28191. /** Returns true if the format can do 2-channel audio. */
  28192. virtual bool canDoStereo() = 0;
  28193. /** Returns true if the format can do 1-channel audio. */
  28194. virtual bool canDoMono() = 0;
  28195. /** Returns true if the format uses compressed data. */
  28196. virtual bool isCompressed();
  28197. /** Returns a list of different qualities that can be used when writing.
  28198. Non-compressed formats will just return an empty array, but for something
  28199. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  28200. When calling createWriterFor(), an index from this array is passed in to
  28201. tell the format which option is required.
  28202. */
  28203. virtual const StringArray getQualityOptions();
  28204. /** Tries to create an object that can read from a stream containing audio
  28205. data in this format.
  28206. The reader object that is returned can be used to read from the stream, and
  28207. should then be deleted by the caller.
  28208. @param sourceStream the stream to read from - the AudioFormatReader object
  28209. that is returned will delete this stream when it no longer
  28210. needs it.
  28211. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  28212. should delete the stream object that was passed-in. (If a valid
  28213. reader is returned, it will always be in charge of deleting the
  28214. stream, so this parameter is ignored)
  28215. @see AudioFormatReader
  28216. */
  28217. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28218. bool deleteStreamIfOpeningFails) = 0;
  28219. /** Tries to create an object that can write to a stream with this audio format.
  28220. The writer object that is returned can be used to write to the stream, and
  28221. should then be deleted by the caller.
  28222. If the stream can't be created for some reason (e.g. the parameters passed in
  28223. here aren't suitable), this will return 0.
  28224. @param streamToWriteTo the stream that the data will go to - this will be
  28225. deleted by the AudioFormatWriter object when it's no longer
  28226. needed. If no AudioFormatWriter can be created by this method,
  28227. the stream will NOT be deleted, so that the caller can re-use it
  28228. to try to open a different format, etc
  28229. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  28230. returned by getPossibleSampleRates()
  28231. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  28232. the choice will depend on the results of canDoMono() and
  28233. canDoStereo()
  28234. @param bitsPerSample the bits per sample to use - this must be one of the values
  28235. returned by getPossibleBitDepths()
  28236. @param metadataValues a set of metadata values that the writer should try to write
  28237. to the stream. Exactly what these are depends on the format,
  28238. and the subclass doesn't actually have to do anything with
  28239. them if it doesn't want to. Have a look at the specific format
  28240. implementation classes to see possible values that can be
  28241. used
  28242. @param qualityOptionIndex the index of one of compression qualities returned by the
  28243. getQualityOptions() method. If there aren't any quality options
  28244. for this format, just pass 0 in this parameter, as it'll be
  28245. ignored
  28246. @see AudioFormatWriter
  28247. */
  28248. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28249. double sampleRateToUse,
  28250. unsigned int numberOfChannels,
  28251. int bitsPerSample,
  28252. const StringPairArray& metadataValues,
  28253. int qualityOptionIndex) = 0;
  28254. protected:
  28255. /** Creates an AudioFormat object.
  28256. @param formatName this sets the value that will be returned by getFormatName()
  28257. @param fileExtensions a zero-terminated list of file extensions - this is what will
  28258. be returned by getFileExtension()
  28259. */
  28260. AudioFormat (const String& formatName,
  28261. const StringArray& fileExtensions);
  28262. private:
  28263. String formatName;
  28264. StringArray fileExtensions;
  28265. };
  28266. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  28267. /*** End of inlined file: juce_AudioFormat.h ***/
  28268. /**
  28269. Reads and Writes AIFF format audio files.
  28270. @see AudioFormat
  28271. */
  28272. class JUCE_API AiffAudioFormat : public AudioFormat
  28273. {
  28274. public:
  28275. /** Creates an format object. */
  28276. AiffAudioFormat();
  28277. /** Destructor. */
  28278. ~AiffAudioFormat();
  28279. const Array <int> getPossibleSampleRates();
  28280. const Array <int> getPossibleBitDepths();
  28281. bool canDoStereo();
  28282. bool canDoMono();
  28283. #if JUCE_MAC
  28284. bool canHandleFile (const File& fileToTest);
  28285. #endif
  28286. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28287. bool deleteStreamIfOpeningFails);
  28288. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28289. double sampleRateToUse,
  28290. unsigned int numberOfChannels,
  28291. int bitsPerSample,
  28292. const StringPairArray& metadataValues,
  28293. int qualityOptionIndex);
  28294. private:
  28295. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  28296. };
  28297. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28298. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  28299. #endif
  28300. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28301. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  28302. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28303. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28304. #if JUCE_USE_CDBURNER || DOXYGEN
  28305. /**
  28306. */
  28307. class AudioCDBurner : public ChangeBroadcaster
  28308. {
  28309. public:
  28310. /** Returns a list of available optical drives.
  28311. Use openDevice() to open one of the items from this list.
  28312. */
  28313. static const StringArray findAvailableDevices();
  28314. /** Tries to open one of the optical drives.
  28315. The deviceIndex is an index into the array returned by findAvailableDevices().
  28316. */
  28317. static AudioCDBurner* openDevice (const int deviceIndex);
  28318. /** Destructor. */
  28319. ~AudioCDBurner();
  28320. enum DiskState
  28321. {
  28322. unknown, /**< An error condition, if the device isn't responding. */
  28323. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  28324. may seem to be permanently open. */
  28325. noDisc, /**< The drive has no disk in it. */
  28326. writableDiskPresent, /**< The drive contains a writeable disk. */
  28327. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  28328. };
  28329. /** Returns the current status of the device.
  28330. To get informed when the drive's status changes, attach a ChangeListener to
  28331. the AudioCDBurner.
  28332. */
  28333. DiskState getDiskState() const;
  28334. /** Returns true if there's a writable disk in the drive. */
  28335. bool isDiskPresent() const;
  28336. /** Sends an eject signal to the drive.
  28337. The eject will happen asynchronously, so you can use getDiskState() and
  28338. waitUntilStateChange() to monitor its progress.
  28339. */
  28340. bool openTray();
  28341. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  28342. @returns the device's new state
  28343. */
  28344. DiskState waitUntilStateChange (int timeOutMilliseconds);
  28345. /** Returns the set of possible write speeds that the device can handle.
  28346. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  28347. Note that if there's no media present in the drive, this value may be unavailable!
  28348. @see setWriteSpeed, getWriteSpeed
  28349. */
  28350. const Array<int> getAvailableWriteSpeeds() const;
  28351. /** Tries to enable or disable buffer underrun safety on devices that support it.
  28352. @returns true if it's now enabled. If the device doesn't support it, this
  28353. will always return false.
  28354. */
  28355. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  28356. /** Returns the number of free blocks on the disk.
  28357. There are 75 blocks per second, at 44100Hz.
  28358. */
  28359. int getNumAvailableAudioBlocks() const;
  28360. /** Adds a track to be written.
  28361. The source passed-in here will be kept by this object, and it will
  28362. be used and deleted at some point in the future, either during the
  28363. burn() method or when this AudioCDBurner object is deleted. Your caller
  28364. method shouldn't keep a reference to it or use it again after passing
  28365. it in here.
  28366. */
  28367. bool addAudioTrack (AudioSource* source, int numSamples);
  28368. /** Receives progress callbacks during a cd-burn operation.
  28369. @see AudioCDBurner::burn()
  28370. */
  28371. class BurnProgressListener
  28372. {
  28373. public:
  28374. BurnProgressListener() noexcept {}
  28375. virtual ~BurnProgressListener() {}
  28376. /** Called at intervals to report on the progress of the AudioCDBurner.
  28377. To cancel the burn, return true from this method.
  28378. */
  28379. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28380. };
  28381. /** Runs the burn process.
  28382. This method will block until the operation is complete.
  28383. @param listener the object to receive callbacks about progress
  28384. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  28385. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  28386. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  28387. 0 or less to mean the fastest speed.
  28388. */
  28389. const String burn (BurnProgressListener* listener,
  28390. bool ejectDiscAfterwards,
  28391. bool performFakeBurnForTesting,
  28392. int writeSpeed);
  28393. /** If a burn operation is currently in progress, this tells it to stop
  28394. as soon as possible.
  28395. It's also possible to stop the burn process by returning true from
  28396. BurnProgressListener::audioCDBurnProgress()
  28397. */
  28398. void abortBurn();
  28399. private:
  28400. AudioCDBurner (const int deviceIndex);
  28401. class Pimpl;
  28402. friend class ScopedPointer<Pimpl>;
  28403. ScopedPointer<Pimpl> pimpl;
  28404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  28405. };
  28406. #endif
  28407. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28408. /*** End of inlined file: juce_AudioCDBurner.h ***/
  28409. #endif
  28410. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28411. /*** Start of inlined file: juce_AudioCDReader.h ***/
  28412. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28413. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28414. #if JUCE_USE_CDREADER || DOXYGEN
  28415. #if JUCE_MAC
  28416. #endif
  28417. /**
  28418. A type of AudioFormatReader that reads from an audio CD.
  28419. One of these can be used to read a CD as if it's one big audio stream. Use the
  28420. getPositionOfTrackStart() method to find where the individual tracks are
  28421. within the stream.
  28422. @see AudioFormatReader
  28423. */
  28424. class JUCE_API AudioCDReader : public AudioFormatReader
  28425. {
  28426. public:
  28427. /** Returns a list of names of Audio CDs currently available for reading.
  28428. If there's a CD drive but no CD in it, this might return an empty list, or
  28429. possibly a device that can be opened but which has no tracks, depending
  28430. on the platform.
  28431. @see createReaderForCD
  28432. */
  28433. static const StringArray getAvailableCDNames();
  28434. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28435. @param index the index of one of the available CDs - use getAvailableCDNames()
  28436. to find out how many there are.
  28437. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28438. caller will be responsible for deleting the object returned.
  28439. */
  28440. static AudioCDReader* createReaderForCD (const int index);
  28441. /** Destructor. */
  28442. ~AudioCDReader();
  28443. /** Implementation of the AudioFormatReader method. */
  28444. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28445. int64 startSampleInFile, int numSamples);
  28446. /** Checks whether the CD has been removed from the drive.
  28447. */
  28448. bool isCDStillPresent() const;
  28449. /** Returns the total number of tracks (audio + data).
  28450. */
  28451. int getNumTracks() const;
  28452. /** Finds the sample offset of the start of a track.
  28453. @param trackNum the track number, where trackNum = 0 is the first track
  28454. and trackNum = getNumTracks() means the end of the CD.
  28455. */
  28456. int getPositionOfTrackStart (int trackNum) const;
  28457. /** Returns true if a given track is an audio track.
  28458. @param trackNum the track number, where 0 is the first track.
  28459. */
  28460. bool isTrackAudio (int trackNum) const;
  28461. /** Returns an array of sample offsets for the start of each track, followed by
  28462. the sample position of the end of the CD.
  28463. */
  28464. const Array<int>& getTrackOffsets() const;
  28465. /** Refreshes the object's table of contents.
  28466. If the disc has been ejected and a different one put in since this
  28467. object was created, this will cause it to update its idea of how many tracks
  28468. there are, etc.
  28469. */
  28470. void refreshTrackLengths();
  28471. /** Enables scanning for indexes within tracks.
  28472. @see getLastIndex
  28473. */
  28474. void enableIndexScanning (bool enabled);
  28475. /** Returns the index number found during the last read() call.
  28476. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28477. Then when the read() method is called, if it comes across an index within that
  28478. block, the index number is stored and returned by this method.
  28479. Some devices might not support indexes, of course.
  28480. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28481. @see enableIndexScanning
  28482. */
  28483. int getLastIndex() const;
  28484. /** Scans a track to find the position of any indexes within it.
  28485. @param trackNumber the track to look in, where 0 is the first track on the disc
  28486. @returns an array of sample positions of any index points found (not including
  28487. the index that marks the start of the track)
  28488. */
  28489. const Array <int> findIndexesInTrack (const int trackNumber);
  28490. /** Returns the CDDB id number for the CD.
  28491. It's not a great way of identifying a disc, but it's traditional.
  28492. */
  28493. int getCDDBId();
  28494. /** Tries to eject the disk.
  28495. Of course this might not be possible, if some other process is using it.
  28496. */
  28497. void ejectDisk();
  28498. enum
  28499. {
  28500. framesPerSecond = 75,
  28501. samplesPerFrame = 44100 / framesPerSecond
  28502. };
  28503. private:
  28504. Array<int> trackStartSamples;
  28505. #if JUCE_MAC
  28506. File volumeDir;
  28507. Array<File> tracks;
  28508. int currentReaderTrack;
  28509. ScopedPointer <AudioFormatReader> reader;
  28510. AudioCDReader (const File& volume);
  28511. #elif JUCE_WINDOWS
  28512. bool audioTracks [100];
  28513. void* handle;
  28514. MemoryBlock buffer;
  28515. bool indexingEnabled;
  28516. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28517. AudioCDReader (void* handle);
  28518. int getIndexAt (int samplePos);
  28519. #elif JUCE_LINUX
  28520. AudioCDReader();
  28521. #endif
  28522. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  28523. };
  28524. #endif
  28525. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28526. /*** End of inlined file: juce_AudioCDReader.h ***/
  28527. #endif
  28528. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28529. #endif
  28530. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28531. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  28532. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28533. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28534. /**
  28535. A class for keeping a list of available audio formats, and for deciding which
  28536. one to use to open a given file.
  28537. You can either use this class as a singleton object, or create instances of it
  28538. yourself. Once created, use its registerFormat() method to tell it which
  28539. formats it should use.
  28540. @see AudioFormat
  28541. */
  28542. class JUCE_API AudioFormatManager
  28543. {
  28544. public:
  28545. /** Creates an empty format manager.
  28546. Before it'll be any use, you'll need to call registerFormat() with all the
  28547. formats you want it to be able to recognise.
  28548. */
  28549. AudioFormatManager();
  28550. /** Destructor. */
  28551. ~AudioFormatManager();
  28552. /** Adds a format to the manager's list of available file types.
  28553. The object passed-in will be deleted by this object, so don't keep a pointer
  28554. to it!
  28555. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28556. return this one when called.
  28557. */
  28558. void registerFormat (AudioFormat* newFormat,
  28559. bool makeThisTheDefaultFormat);
  28560. /** Handy method to make it easy to register the formats that come with Juce.
  28561. Currently, this will add WAV and AIFF to the list.
  28562. */
  28563. void registerBasicFormats();
  28564. /** Clears the list of known formats. */
  28565. void clearFormats();
  28566. /** Returns the number of currently registered file formats. */
  28567. int getNumKnownFormats() const;
  28568. /** Returns one of the registered file formats. */
  28569. AudioFormat* getKnownFormat (int index) const;
  28570. /** Looks for which of the known formats is listed as being for a given file
  28571. extension.
  28572. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28573. */
  28574. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28575. /** Returns the format which has been set as the default one.
  28576. You can set a format as being the default when it is registered. It's useful
  28577. when you want to write to a file, because the best format may change between
  28578. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28579. If none has been set as the default, this method will just return the first
  28580. one in the list.
  28581. */
  28582. AudioFormat* getDefaultFormat() const;
  28583. /** Returns a set of wildcards for file-matching that contains the extensions for
  28584. all known formats.
  28585. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28586. */
  28587. const String getWildcardForAllFormats() const;
  28588. /** Searches through the known formats to try to create a suitable reader for
  28589. this file.
  28590. If none of the registered formats can open the file, it'll return 0. If it
  28591. returns a reader, it's the caller's responsibility to delete the reader.
  28592. */
  28593. AudioFormatReader* createReaderFor (const File& audioFile);
  28594. /** Searches through the known formats to try to create a suitable reader for
  28595. this stream.
  28596. The stream object that is passed-in will be deleted by this method or by the
  28597. reader that is returned, so the caller should not keep any references to it.
  28598. The stream that is passed-in must be capable of being repositioned so
  28599. that all the formats can have a go at opening it.
  28600. If none of the registered formats can open the stream, it'll return 0. If it
  28601. returns a reader, it's the caller's responsibility to delete the reader.
  28602. */
  28603. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28604. private:
  28605. OwnedArray<AudioFormat> knownFormats;
  28606. int defaultFormatIndex;
  28607. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  28608. };
  28609. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28610. /*** End of inlined file: juce_AudioFormatManager.h ***/
  28611. #endif
  28612. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28613. #endif
  28614. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28615. #endif
  28616. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28617. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  28618. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28619. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28620. /**
  28621. This class is used to wrap an AudioFormatReader and only read from a
  28622. subsection of the file.
  28623. So if you have a reader which can read a 1000 sample file, you could wrap it
  28624. in one of these to only access, e.g. samples 100 to 200, and any samples
  28625. outside that will come back as 0. Accessing sample 0 from this reader will
  28626. actually read the first sample from the other's subsection, which might
  28627. be at a non-zero position.
  28628. @see AudioFormatReader
  28629. */
  28630. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28631. {
  28632. public:
  28633. /** Creates a AudioSubsectionReader for a given data source.
  28634. @param sourceReader the source reader from which we'll be taking data
  28635. @param subsectionStartSample the sample within the source reader which will be
  28636. mapped onto sample 0 for this reader.
  28637. @param subsectionLength the number of samples from the source that will
  28638. make up the subsection. If this reader is asked for
  28639. any samples beyond this region, it will return zero.
  28640. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28641. this object is deleted.
  28642. */
  28643. AudioSubsectionReader (AudioFormatReader* sourceReader,
  28644. int64 subsectionStartSample,
  28645. int64 subsectionLength,
  28646. bool deleteSourceWhenDeleted);
  28647. /** Destructor. */
  28648. ~AudioSubsectionReader();
  28649. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28650. int64 startSampleInFile, int numSamples);
  28651. void readMaxLevels (int64 startSample,
  28652. int64 numSamples,
  28653. float& lowestLeft,
  28654. float& highestLeft,
  28655. float& lowestRight,
  28656. float& highestRight);
  28657. private:
  28658. AudioFormatReader* const source;
  28659. int64 startSample, length;
  28660. const bool deleteSourceWhenDeleted;
  28661. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  28662. };
  28663. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28664. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  28665. #endif
  28666. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28667. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  28668. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28669. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28670. class AudioThumbnailCache;
  28671. /**
  28672. Makes it easy to quickly draw scaled views of the waveform shape of an
  28673. audio file.
  28674. To use this class, just create an AudioThumbNail class for the file you want
  28675. to draw, call setSource to tell it which file or resource to use, then call
  28676. drawChannel() to draw it.
  28677. The class will asynchronously scan the wavefile to create its scaled-down view,
  28678. so you should make your UI repaint itself as this data comes in. To do this, the
  28679. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28680. listeners should repaint themselves.
  28681. The thumbnail stores an internal low-res version of the wave data, and this can
  28682. be loaded and saved to avoid having to scan the file again.
  28683. @see AudioThumbnailCache
  28684. */
  28685. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  28686. {
  28687. public:
  28688. /** Creates an audio thumbnail.
  28689. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28690. of the audio data, this is the scale at which it should be done. (This
  28691. number is the number of original samples that will be averaged for each
  28692. low-res sample)
  28693. @param formatManagerToUse the audio format manager that is used to open the file
  28694. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28695. thread and storage that is used to by the thumbnail, and the cache
  28696. object can be shared between multiple thumbnails
  28697. */
  28698. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  28699. AudioFormatManager& formatManagerToUse,
  28700. AudioThumbnailCache& cacheToUse);
  28701. /** Destructor. */
  28702. ~AudioThumbnail();
  28703. /** Clears and resets the thumbnail. */
  28704. void clear();
  28705. /** Specifies the file or stream that contains the audio file.
  28706. For a file, just call
  28707. @code
  28708. setSource (new FileInputSource (file))
  28709. @endcode
  28710. You can pass a zero in here to clear the thumbnail.
  28711. The source that is passed in will be deleted by this object when it is no longer needed.
  28712. @returns true if the source could be opened as a valid audio file, false if this failed for
  28713. some reason.
  28714. */
  28715. bool setSource (InputSource* newSource);
  28716. /** Gives the thumbnail an AudioFormatReader to use directly.
  28717. This will start parsing the audio in a background thread (unless the hash code
  28718. can be looked-up successfully in the thumbnail cache). Note that the reader
  28719. object will be held by the thumbnail and deleted later when no longer needed.
  28720. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  28721. or change the input source, so the file will be held open for all this time. If
  28722. you don't want the thumbnail to keep a file handle open continuously, you
  28723. should use the setSource() method instead, which will only open the file when
  28724. it needs to.
  28725. */
  28726. void setReader (AudioFormatReader* newReader, int64 hashCode);
  28727. /** Resets the thumbnail, ready for adding data with the specified format.
  28728. If you're going to generate a thumbnail yourself, call this before using addBlock()
  28729. to add the data.
  28730. */
  28731. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  28732. /** Adds a block of level data to the thumbnail.
  28733. Call reset() before using this, to tell the thumbnail about the data format.
  28734. */
  28735. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  28736. int startOffsetInBuffer, int numSamples);
  28737. /** Reloads the low res thumbnail data from an input stream.
  28738. This is not an audio file stream! It takes a stream of thumbnail data that would
  28739. previously have been created by the saveTo() method.
  28740. @see saveTo
  28741. */
  28742. void loadFrom (InputStream& input);
  28743. /** Saves the low res thumbnail data to an output stream.
  28744. The data that is written can later be reloaded using loadFrom().
  28745. @see loadFrom
  28746. */
  28747. void saveTo (OutputStream& output) const;
  28748. /** Returns the number of channels in the file. */
  28749. int getNumChannels() const noexcept;
  28750. /** Returns the length of the audio file, in seconds. */
  28751. double getTotalLength() const noexcept;
  28752. /** Draws the waveform for a channel.
  28753. The waveform will be drawn within the specified rectangle, where startTime
  28754. and endTime specify the times within the audio file that should be positioned
  28755. at the left and right edges of the rectangle.
  28756. The waveform will be scaled vertically so that a full-volume sample will fill
  28757. the rectangle vertically, but you can also specify an extra vertical scale factor
  28758. with the verticalZoomFactor parameter.
  28759. */
  28760. void drawChannel (Graphics& g,
  28761. const Rectangle<int>& area,
  28762. double startTimeSeconds,
  28763. double endTimeSeconds,
  28764. int channelNum,
  28765. float verticalZoomFactor);
  28766. /** Draws the waveforms for all channels in the thumbnail.
  28767. This will call drawChannel() to render each of the thumbnail's channels, stacked
  28768. above each other within the specified area.
  28769. @see drawChannel
  28770. */
  28771. void drawChannels (Graphics& g,
  28772. const Rectangle<int>& area,
  28773. double startTimeSeconds,
  28774. double endTimeSeconds,
  28775. float verticalZoomFactor);
  28776. /** Returns true if the low res preview is fully generated. */
  28777. bool isFullyLoaded() const noexcept;
  28778. /** Returns the number of samples that have been set in the thumbnail. */
  28779. int64 getNumSamplesFinished() const noexcept;
  28780. /** Returns the highest level in the thumbnail.
  28781. Note that because the thumb only stores low-resolution data, this isn't
  28782. an accurate representation of the highest value, it's only a rough approximation.
  28783. */
  28784. float getApproximatePeak() const;
  28785. /** Reads the approximate min and max levels from a section of the thumbnail.
  28786. The lowest and highest samples are returned in minValue and maxValue, but obviously
  28787. because the thumb only stores low-resolution data, these numbers will only be a rough
  28788. approximation of the true values.
  28789. */
  28790. void getApproximateMinMax (double startTime, double endTime, int channelIndex,
  28791. float& minValue, float& maxValue) const noexcept;
  28792. /** Returns the hash code that was set by setSource() or setReader(). */
  28793. int64 getHashCode() const;
  28794. #ifndef DOXYGEN
  28795. class LevelDataSource; // (this is only public to avoid a VC6 bug)
  28796. #endif
  28797. private:
  28798. AudioFormatManager& formatManagerToUse;
  28799. AudioThumbnailCache& cache;
  28800. struct MinMaxValue;
  28801. class ThumbData;
  28802. class CachedWindow;
  28803. friend class LevelDataSource;
  28804. friend class ScopedPointer<LevelDataSource>;
  28805. friend class ThumbData;
  28806. friend class OwnedArray<ThumbData>;
  28807. friend class CachedWindow;
  28808. friend class ScopedPointer<CachedWindow>;
  28809. ScopedPointer<LevelDataSource> source;
  28810. ScopedPointer<CachedWindow> window;
  28811. OwnedArray<ThumbData> channels;
  28812. int32 samplesPerThumbSample;
  28813. int64 totalSamples, numSamplesFinished;
  28814. int32 numChannels;
  28815. double sampleRate;
  28816. CriticalSection lock;
  28817. void clearChannelData();
  28818. bool setDataSource (LevelDataSource* newSource);
  28819. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28820. void createChannels (int length);
  28821. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28822. };
  28823. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28824. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28825. #endif
  28826. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28827. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28828. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28829. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28830. struct ThumbnailCacheEntry;
  28831. /**
  28832. An instance of this class is used to manage multiple AudioThumbnail objects.
  28833. The cache runs a single background thread that is shared by all the thumbnails
  28834. that need it, and it maintains a set of low-res previews in memory, to avoid
  28835. having to re-scan audio files too often.
  28836. @see AudioThumbnail
  28837. */
  28838. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28839. {
  28840. public:
  28841. /** Creates a cache object.
  28842. The maxNumThumbsToStore parameter lets you specify how many previews should
  28843. be kept in memory at once.
  28844. */
  28845. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28846. /** Destructor. */
  28847. ~AudioThumbnailCache();
  28848. /** Clears out any stored thumbnails.
  28849. */
  28850. void clear();
  28851. /** Reloads the specified thumb if this cache contains the appropriate stored
  28852. data.
  28853. This is called automatically by the AudioThumbnail class, so you shouldn't
  28854. normally need to call it directly.
  28855. */
  28856. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28857. /** Stores the cachable data from the specified thumb in this cache.
  28858. This is called automatically by the AudioThumbnail class, so you shouldn't
  28859. normally need to call it directly.
  28860. */
  28861. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28862. private:
  28863. OwnedArray <ThumbnailCacheEntry> thumbs;
  28864. int maxNumThumbsToStore;
  28865. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28866. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28867. };
  28868. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28869. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28870. #endif
  28871. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28872. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28873. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28874. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28875. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28876. /**
  28877. Reads and writes the lossless-compression FLAC audio format.
  28878. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28879. and make sure your include search path and library search path are set up to find
  28880. the FLAC header files and static libraries.
  28881. @see AudioFormat
  28882. */
  28883. class JUCE_API FlacAudioFormat : public AudioFormat
  28884. {
  28885. public:
  28886. FlacAudioFormat();
  28887. ~FlacAudioFormat();
  28888. const Array <int> getPossibleSampleRates();
  28889. const Array <int> getPossibleBitDepths();
  28890. bool canDoStereo();
  28891. bool canDoMono();
  28892. bool isCompressed();
  28893. const StringArray getQualityOptions();
  28894. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28895. bool deleteStreamIfOpeningFails);
  28896. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28897. double sampleRateToUse,
  28898. unsigned int numberOfChannels,
  28899. int bitsPerSample,
  28900. const StringPairArray& metadataValues,
  28901. int qualityOptionIndex);
  28902. private:
  28903. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28904. };
  28905. #endif
  28906. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28907. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28908. #endif
  28909. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28910. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28911. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28912. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28913. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28914. /**
  28915. Reads and writes the Ogg-Vorbis audio format.
  28916. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28917. and make sure your include search path and library search path are set up to find
  28918. the Vorbis and Ogg header files and static libraries.
  28919. @see AudioFormat,
  28920. */
  28921. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28922. {
  28923. public:
  28924. OggVorbisAudioFormat();
  28925. ~OggVorbisAudioFormat();
  28926. const Array <int> getPossibleSampleRates();
  28927. const Array <int> getPossibleBitDepths();
  28928. bool canDoStereo();
  28929. bool canDoMono();
  28930. bool isCompressed();
  28931. const StringArray getQualityOptions();
  28932. /** Tries to estimate the quality level of an ogg file based on its size.
  28933. If it can't read the file for some reason, this will just return 1 (medium quality),
  28934. otherwise it will return the approximate quality setting that would have been used
  28935. to create the file.
  28936. @see getQualityOptions
  28937. */
  28938. int estimateOggFileQuality (const File& source);
  28939. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28940. bool deleteStreamIfOpeningFails);
  28941. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28942. double sampleRateToUse,
  28943. unsigned int numberOfChannels,
  28944. int bitsPerSample,
  28945. const StringPairArray& metadataValues,
  28946. int qualityOptionIndex);
  28947. private:
  28948. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28949. };
  28950. #endif
  28951. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28952. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28953. #endif
  28954. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28955. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28956. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28957. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28958. #if JUCE_QUICKTIME
  28959. /**
  28960. Uses QuickTime to read the audio track a movie or media file.
  28961. As well as QuickTime movies, this should also manage to open other audio
  28962. files that quicktime can understand, like mp3, m4a, etc.
  28963. @see AudioFormat
  28964. */
  28965. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28966. {
  28967. public:
  28968. /** Creates a format object. */
  28969. QuickTimeAudioFormat();
  28970. /** Destructor. */
  28971. ~QuickTimeAudioFormat();
  28972. const Array <int> getPossibleSampleRates();
  28973. const Array <int> getPossibleBitDepths();
  28974. bool canDoStereo();
  28975. bool canDoMono();
  28976. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28977. bool deleteStreamIfOpeningFails);
  28978. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28979. double sampleRateToUse,
  28980. unsigned int numberOfChannels,
  28981. int bitsPerSample,
  28982. const StringPairArray& metadataValues,
  28983. int qualityOptionIndex);
  28984. private:
  28985. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28986. };
  28987. #endif
  28988. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28989. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28990. #endif
  28991. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28992. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28993. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28994. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28995. /**
  28996. Reads and Writes WAV format audio files.
  28997. @see AudioFormat
  28998. */
  28999. class JUCE_API WavAudioFormat : public AudioFormat
  29000. {
  29001. public:
  29002. /** Creates a format object. */
  29003. WavAudioFormat();
  29004. /** Destructor. */
  29005. ~WavAudioFormat();
  29006. /** Metadata property name used by wav readers and writers for adding
  29007. a BWAV chunk to the file.
  29008. @see AudioFormatReader::metadataValues, createWriterFor
  29009. */
  29010. static const char* const bwavDescription;
  29011. /** Metadata property name used by wav readers and writers for adding
  29012. a BWAV chunk to the file.
  29013. @see AudioFormatReader::metadataValues, createWriterFor
  29014. */
  29015. static const char* const bwavOriginator;
  29016. /** Metadata property name used by wav readers and writers for adding
  29017. a BWAV chunk to the file.
  29018. @see AudioFormatReader::metadataValues, createWriterFor
  29019. */
  29020. static const char* const bwavOriginatorRef;
  29021. /** Metadata property name used by wav readers and writers for adding
  29022. a BWAV chunk to the file.
  29023. Date format is: yyyy-mm-dd
  29024. @see AudioFormatReader::metadataValues, createWriterFor
  29025. */
  29026. static const char* const bwavOriginationDate;
  29027. /** Metadata property name used by wav readers and writers for adding
  29028. a BWAV chunk to the file.
  29029. Time format is: hh-mm-ss
  29030. @see AudioFormatReader::metadataValues, createWriterFor
  29031. */
  29032. static const char* const bwavOriginationTime;
  29033. /** Metadata property name used by wav readers and writers for adding
  29034. a BWAV chunk to the file.
  29035. This is the number of samples from the start of an edit that the
  29036. file is supposed to begin at. Seems like an obvious mistake to
  29037. only allow a file to occur in an edit once, but that's the way
  29038. it is..
  29039. @see AudioFormatReader::metadataValues, createWriterFor
  29040. */
  29041. static const char* const bwavTimeReference;
  29042. /** Metadata property name used by wav readers and writers for adding
  29043. a BWAV chunk to the file.
  29044. This is a
  29045. @see AudioFormatReader::metadataValues, createWriterFor
  29046. */
  29047. static const char* const bwavCodingHistory;
  29048. /** Utility function to fill out the appropriate metadata for a BWAV file.
  29049. This just makes it easier than using the property names directly, and it
  29050. fills out the time and date in the right format.
  29051. */
  29052. static StringPairArray createBWAVMetadata (const String& description,
  29053. const String& originator,
  29054. const String& originatorRef,
  29055. const Time& dateAndTime,
  29056. const int64 timeReferenceSamples,
  29057. const String& codingHistory);
  29058. const Array <int> getPossibleSampleRates();
  29059. const Array <int> getPossibleBitDepths();
  29060. bool canDoStereo();
  29061. bool canDoMono();
  29062. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  29063. bool deleteStreamIfOpeningFails);
  29064. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  29065. double sampleRateToUse,
  29066. unsigned int numberOfChannels,
  29067. int bitsPerSample,
  29068. const StringPairArray& metadataValues,
  29069. int qualityOptionIndex);
  29070. /** Utility function to replace the metadata in a wav file with a new set of values.
  29071. If possible, this cheats by overwriting just the metadata region of the file, rather
  29072. than by copying the whole file again.
  29073. */
  29074. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  29075. private:
  29076. JUCE_LEAK_DETECTOR (WavAudioFormat);
  29077. };
  29078. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  29079. /*** End of inlined file: juce_WavAudioFormat.h ***/
  29080. #endif
  29081. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29082. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  29083. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29084. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29085. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  29086. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29087. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29088. /**
  29089. A type of AudioSource which can be repositioned.
  29090. The basic AudioSource just streams continuously with no idea of a current
  29091. time or length, so the PositionableAudioSource is used for a finite stream
  29092. that has a current read position.
  29093. @see AudioSource, AudioTransportSource
  29094. */
  29095. class JUCE_API PositionableAudioSource : public AudioSource
  29096. {
  29097. protected:
  29098. /** Creates the PositionableAudioSource. */
  29099. PositionableAudioSource() noexcept {}
  29100. public:
  29101. /** Destructor */
  29102. ~PositionableAudioSource() {}
  29103. /** Tells the stream to move to a new position.
  29104. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  29105. should return samples from this position.
  29106. Note that this may be called on a different thread to getNextAudioBlock(),
  29107. so the subclass should make sure it's synchronised.
  29108. */
  29109. virtual void setNextReadPosition (int64 newPosition) = 0;
  29110. /** Returns the position from which the next block will be returned.
  29111. @see setNextReadPosition
  29112. */
  29113. virtual int64 getNextReadPosition() const = 0;
  29114. /** Returns the total length of the stream (in samples). */
  29115. virtual int64 getTotalLength() const = 0;
  29116. /** Returns true if this source is actually playing in a loop. */
  29117. virtual bool isLooping() const = 0;
  29118. /** Tells the source whether you'd like it to play in a loop. */
  29119. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  29120. };
  29121. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29122. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  29123. /**
  29124. A type of AudioSource that will read from an AudioFormatReader.
  29125. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  29126. */
  29127. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  29128. {
  29129. public:
  29130. /** Creates an AudioFormatReaderSource for a given reader.
  29131. @param sourceReader the reader to use as the data source - this must
  29132. not be null
  29133. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  29134. when this object is deleted; if false it will be
  29135. left up to the caller to manage its lifetime
  29136. */
  29137. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  29138. bool deleteReaderWhenThisIsDeleted);
  29139. /** Destructor. */
  29140. ~AudioFormatReaderSource();
  29141. /** Toggles loop-mode.
  29142. If set to true, it will continuously loop the input source. If false,
  29143. it will just emit silence after the source has finished.
  29144. @see isLooping
  29145. */
  29146. void setLooping (bool shouldLoop);
  29147. /** Returns whether loop-mode is turned on or not. */
  29148. bool isLooping() const { return looping; }
  29149. /** Returns the reader that's being used. */
  29150. AudioFormatReader* getAudioFormatReader() const noexcept { return reader; }
  29151. /** Implementation of the AudioSource method. */
  29152. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29153. /** Implementation of the AudioSource method. */
  29154. void releaseResources();
  29155. /** Implementation of the AudioSource method. */
  29156. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29157. /** Implements the PositionableAudioSource method. */
  29158. void setNextReadPosition (int64 newPosition);
  29159. /** Implements the PositionableAudioSource method. */
  29160. int64 getNextReadPosition() const;
  29161. /** Implements the PositionableAudioSource method. */
  29162. int64 getTotalLength() const;
  29163. private:
  29164. OptionalScopedPointer<AudioFormatReader> reader;
  29165. int64 volatile nextPlayPos;
  29166. bool volatile looping;
  29167. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  29168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  29169. };
  29170. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29171. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  29172. #endif
  29173. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  29174. #endif
  29175. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29176. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  29177. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29178. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29179. /*** Start of inlined file: juce_AudioIODevice.h ***/
  29180. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29181. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29182. class AudioIODevice;
  29183. /**
  29184. One of these is passed to an AudioIODevice object to stream the audio data
  29185. in and out.
  29186. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  29187. method on its own high-priority audio thread, when it needs to send or receive
  29188. the next block of data.
  29189. @see AudioIODevice, AudioDeviceManager
  29190. */
  29191. class JUCE_API AudioIODeviceCallback
  29192. {
  29193. public:
  29194. /** Destructor. */
  29195. virtual ~AudioIODeviceCallback() {}
  29196. /** Processes a block of incoming and outgoing audio data.
  29197. The subclass's implementation should use the incoming audio for whatever
  29198. purposes it needs to, and must fill all the output channels with the next
  29199. block of output data before returning.
  29200. The channel data is arranged with the same array indices as the channel name
  29201. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  29202. that aren't specified in AudioIODevice::open() will have a null pointer for their
  29203. associated channel, so remember to check for this.
  29204. @param inputChannelData a set of arrays containing the audio data for each
  29205. incoming channel - this data is valid until the function
  29206. returns. There will be one channel of data for each input
  29207. channel that was enabled when the audio device was opened
  29208. (see AudioIODevice::open())
  29209. @param numInputChannels the number of pointers to channel data in the
  29210. inputChannelData array.
  29211. @param outputChannelData a set of arrays which need to be filled with the data
  29212. that should be sent to each outgoing channel of the device.
  29213. There will be one channel of data for each output channel
  29214. that was enabled when the audio device was opened (see
  29215. AudioIODevice::open())
  29216. The initial contents of the array is undefined, so the
  29217. callback function must fill all the channels with zeros if
  29218. its output is silence. Failing to do this could cause quite
  29219. an unpleasant noise!
  29220. @param numOutputChannels the number of pointers to channel data in the
  29221. outputChannelData array.
  29222. @param numSamples the number of samples in each channel of the input and
  29223. output arrays. The number of samples will depend on the
  29224. audio device's buffer size and will usually remain constant,
  29225. although this isn't guaranteed, so make sure your code can
  29226. cope with reasonable changes in the buffer size from one
  29227. callback to the next.
  29228. */
  29229. virtual void audioDeviceIOCallback (const float** inputChannelData,
  29230. int numInputChannels,
  29231. float** outputChannelData,
  29232. int numOutputChannels,
  29233. int numSamples) = 0;
  29234. /** Called to indicate that the device is about to start calling back.
  29235. This will be called just before the audio callbacks begin, either when this
  29236. callback has just been added to an audio device, or after the device has been
  29237. restarted because of a sample-rate or block-size change.
  29238. You can use this opportunity to find out the sample rate and block size
  29239. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  29240. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  29241. @param device the audio IO device that will be used to drive the callback.
  29242. Note that if you're going to store this this pointer, it is
  29243. only valid until the next time that audioDeviceStopped is called.
  29244. */
  29245. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  29246. /** Called to indicate that the device has stopped. */
  29247. virtual void audioDeviceStopped() = 0;
  29248. /** This can be overridden to be told if the device generates an error while operating.
  29249. Be aware that this could be called by any thread! And not all devices perform
  29250. this callback.
  29251. */
  29252. virtual void audioDeviceError (const String& errorMessage);
  29253. };
  29254. /**
  29255. Base class for an audio device with synchronised input and output channels.
  29256. Subclasses of this are used to implement different protocols such as DirectSound,
  29257. ASIO, CoreAudio, etc.
  29258. To create one of these, you'll need to use the AudioIODeviceType class - see the
  29259. documentation for that class for more info.
  29260. For an easier way of managing audio devices and their settings, have a look at the
  29261. AudioDeviceManager class.
  29262. @see AudioIODeviceType, AudioDeviceManager
  29263. */
  29264. class JUCE_API AudioIODevice
  29265. {
  29266. public:
  29267. /** Destructor. */
  29268. virtual ~AudioIODevice();
  29269. /** Returns the device's name, (as set in the constructor). */
  29270. const String& getName() const noexcept { return name; }
  29271. /** Returns the type of the device.
  29272. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  29273. */
  29274. const String& getTypeName() const noexcept { return typeName; }
  29275. /** Returns the names of all the available output channels on this device.
  29276. To find out which of these are currently in use, call getActiveOutputChannels().
  29277. */
  29278. virtual const StringArray getOutputChannelNames() = 0;
  29279. /** Returns the names of all the available input channels on this device.
  29280. To find out which of these are currently in use, call getActiveInputChannels().
  29281. */
  29282. virtual const StringArray getInputChannelNames() = 0;
  29283. /** Returns the number of sample-rates this device supports.
  29284. To find out which rates are available on this device, use this method to
  29285. find out how many there are, and getSampleRate() to get the rates.
  29286. @see getSampleRate
  29287. */
  29288. virtual int getNumSampleRates() = 0;
  29289. /** Returns one of the sample-rates this device supports.
  29290. To find out which rates are available on this device, use getNumSampleRates() to
  29291. find out how many there are, and getSampleRate() to get the individual rates.
  29292. The sample rate is set by the open() method.
  29293. (Note that for DirectSound some rates might not work, depending on combinations
  29294. of i/o channels that are being opened).
  29295. @see getNumSampleRates
  29296. */
  29297. virtual double getSampleRate (int index) = 0;
  29298. /** Returns the number of sizes of buffer that are available.
  29299. @see getBufferSizeSamples, getDefaultBufferSize
  29300. */
  29301. virtual int getNumBufferSizesAvailable() = 0;
  29302. /** Returns one of the possible buffer-sizes.
  29303. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  29304. @returns a number of samples
  29305. @see getNumBufferSizesAvailable, getDefaultBufferSize
  29306. */
  29307. virtual int getBufferSizeSamples (int index) = 0;
  29308. /** Returns the default buffer-size to use.
  29309. @returns a number of samples
  29310. @see getNumBufferSizesAvailable, getBufferSizeSamples
  29311. */
  29312. virtual int getDefaultBufferSize() = 0;
  29313. /** Tries to open the device ready to play.
  29314. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  29315. input channel should be enabled
  29316. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  29317. output channel should be enabled
  29318. @param sampleRate the sample rate to try to use - to find out which rates are
  29319. available, see getNumSampleRates() and getSampleRate()
  29320. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  29321. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  29322. @returns an error description if there's a problem, or an empty string if it succeeds in
  29323. opening the device
  29324. @see close
  29325. */
  29326. virtual const String open (const BigInteger& inputChannels,
  29327. const BigInteger& outputChannels,
  29328. double sampleRate,
  29329. int bufferSizeSamples) = 0;
  29330. /** Closes and releases the device if it's open. */
  29331. virtual void close() = 0;
  29332. /** Returns true if the device is still open.
  29333. A device might spontaneously close itself if something goes wrong, so this checks if
  29334. it's still open.
  29335. */
  29336. virtual bool isOpen() = 0;
  29337. /** Starts the device actually playing.
  29338. This must be called after the device has been opened.
  29339. @param callback the callback to use for streaming the data.
  29340. @see AudioIODeviceCallback, open
  29341. */
  29342. virtual void start (AudioIODeviceCallback* callback) = 0;
  29343. /** Stops the device playing.
  29344. Once a device has been started, this will stop it. Any pending calls to the
  29345. callback class will be flushed before this method returns.
  29346. */
  29347. virtual void stop() = 0;
  29348. /** Returns true if the device is still calling back.
  29349. The device might mysteriously stop, so this checks whether it's
  29350. still playing.
  29351. */
  29352. virtual bool isPlaying() = 0;
  29353. /** Returns the last error that happened if anything went wrong. */
  29354. virtual const String getLastError() = 0;
  29355. /** Returns the buffer size that the device is currently using.
  29356. If the device isn't actually open, this value doesn't really mean much.
  29357. */
  29358. virtual int getCurrentBufferSizeSamples() = 0;
  29359. /** Returns the sample rate that the device is currently using.
  29360. If the device isn't actually open, this value doesn't really mean much.
  29361. */
  29362. virtual double getCurrentSampleRate() = 0;
  29363. /** Returns the device's current physical bit-depth.
  29364. If the device isn't actually open, this value doesn't really mean much.
  29365. */
  29366. virtual int getCurrentBitDepth() = 0;
  29367. /** Returns a mask showing which of the available output channels are currently
  29368. enabled.
  29369. @see getOutputChannelNames
  29370. */
  29371. virtual const BigInteger getActiveOutputChannels() const = 0;
  29372. /** Returns a mask showing which of the available input channels are currently
  29373. enabled.
  29374. @see getInputChannelNames
  29375. */
  29376. virtual const BigInteger getActiveInputChannels() const = 0;
  29377. /** Returns the device's output latency.
  29378. This is the delay in samples between a callback getting a block of data, and
  29379. that data actually getting played.
  29380. */
  29381. virtual int getOutputLatencyInSamples() = 0;
  29382. /** Returns the device's input latency.
  29383. This is the delay in samples between some audio actually arriving at the soundcard,
  29384. and the callback getting passed this block of data.
  29385. */
  29386. virtual int getInputLatencyInSamples() = 0;
  29387. /** True if this device can show a pop-up control panel for editing its settings.
  29388. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  29389. to display it.
  29390. */
  29391. virtual bool hasControlPanel() const;
  29392. /** Shows a device-specific control panel if there is one.
  29393. This should only be called for devices which return true from hasControlPanel().
  29394. */
  29395. virtual bool showControlPanel();
  29396. protected:
  29397. /** Creates a device, setting its name and type member variables. */
  29398. AudioIODevice (const String& deviceName,
  29399. const String& typeName);
  29400. /** @internal */
  29401. String name, typeName;
  29402. };
  29403. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29404. /*** End of inlined file: juce_AudioIODevice.h ***/
  29405. /**
  29406. Wrapper class to continuously stream audio from an audio source to an
  29407. AudioIODevice.
  29408. This object acts as an AudioIODeviceCallback, so can be attached to an
  29409. output device, and will stream audio from an AudioSource.
  29410. */
  29411. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  29412. {
  29413. public:
  29414. /** Creates an empty AudioSourcePlayer. */
  29415. AudioSourcePlayer();
  29416. /** Destructor.
  29417. Make sure this object isn't still being used by an AudioIODevice before
  29418. deleting it!
  29419. */
  29420. virtual ~AudioSourcePlayer();
  29421. /** Changes the current audio source to play from.
  29422. If the source passed in is already being used, this method will do nothing.
  29423. If the source is not null, its prepareToPlay() method will be called
  29424. before it starts being used for playback.
  29425. If there's another source currently playing, its releaseResources() method
  29426. will be called after it has been swapped for the new one.
  29427. @param newSource the new source to use - this will NOT be deleted
  29428. by this object when no longer needed, so it's the
  29429. caller's responsibility to manage it.
  29430. */
  29431. void setSource (AudioSource* newSource);
  29432. /** Returns the source that's playing.
  29433. May return 0 if there's no source.
  29434. */
  29435. AudioSource* getCurrentSource() const noexcept { return source; }
  29436. /** Sets a gain to apply to the audio data.
  29437. @see getGain
  29438. */
  29439. void setGain (float newGain) noexcept;
  29440. /** Returns the current gain.
  29441. @see setGain
  29442. */
  29443. float getGain() const noexcept { return gain; }
  29444. /** Implementation of the AudioIODeviceCallback method. */
  29445. void audioDeviceIOCallback (const float** inputChannelData,
  29446. int totalNumInputChannels,
  29447. float** outputChannelData,
  29448. int totalNumOutputChannels,
  29449. int numSamples);
  29450. /** Implementation of the AudioIODeviceCallback method. */
  29451. void audioDeviceAboutToStart (AudioIODevice* device);
  29452. /** Implementation of the AudioIODeviceCallback method. */
  29453. void audioDeviceStopped();
  29454. private:
  29455. CriticalSection readLock;
  29456. AudioSource* source;
  29457. double sampleRate;
  29458. int bufferSize;
  29459. float* channels [128];
  29460. float* outputChans [128];
  29461. const float* inputChans [128];
  29462. AudioSampleBuffer tempBuffer;
  29463. float lastGain, gain;
  29464. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  29465. };
  29466. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29467. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  29468. #endif
  29469. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29470. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  29471. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29472. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29473. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  29474. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29475. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29476. /**
  29477. An AudioSource which takes another source as input, and buffers it using a thread.
  29478. Create this as a wrapper around another thread, and it will read-ahead with
  29479. a background thread to smooth out playback. You can either create one of these
  29480. directly, or use it indirectly using an AudioTransportSource.
  29481. @see PositionableAudioSource, AudioTransportSource
  29482. */
  29483. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  29484. {
  29485. public:
  29486. /** Creates a BufferingAudioSource.
  29487. @param source the input source to read from
  29488. @param deleteSourceWhenDeleted if true, then the input source object will
  29489. be deleted when this object is deleted
  29490. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  29491. @param numberOfChannels the number of channels that will be played
  29492. */
  29493. BufferingAudioSource (PositionableAudioSource* source,
  29494. bool deleteSourceWhenDeleted,
  29495. int numberOfSamplesToBuffer,
  29496. int numberOfChannels = 2);
  29497. /** Destructor.
  29498. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  29499. flag was set in the constructor.
  29500. */
  29501. ~BufferingAudioSource();
  29502. /** Implementation of the AudioSource method. */
  29503. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29504. /** Implementation of the AudioSource method. */
  29505. void releaseResources();
  29506. /** Implementation of the AudioSource method. */
  29507. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29508. /** Implements the PositionableAudioSource method. */
  29509. void setNextReadPosition (int64 newPosition);
  29510. /** Implements the PositionableAudioSource method. */
  29511. int64 getNextReadPosition() const;
  29512. /** Implements the PositionableAudioSource method. */
  29513. int64 getTotalLength() const { return source->getTotalLength(); }
  29514. /** Implements the PositionableAudioSource method. */
  29515. bool isLooping() const { return source->isLooping(); }
  29516. private:
  29517. OptionalScopedPointer<PositionableAudioSource> source;
  29518. int numberOfSamplesToBuffer, numberOfChannels;
  29519. AudioSampleBuffer buffer;
  29520. CriticalSection bufferStartPosLock;
  29521. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  29522. double volatile sampleRate;
  29523. bool wasSourceLooping;
  29524. friend class SharedBufferingAudioSourceThread;
  29525. bool readNextBufferChunk();
  29526. void readBufferSection (int64 start, int length, int bufferOffset);
  29527. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  29528. };
  29529. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29530. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  29531. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  29532. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29533. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29534. /**
  29535. A type of AudioSource that takes an input source and changes its sample rate.
  29536. @see AudioSource
  29537. */
  29538. class JUCE_API ResamplingAudioSource : public AudioSource
  29539. {
  29540. public:
  29541. /** Creates a ResamplingAudioSource for a given input source.
  29542. @param inputSource the input source to read from
  29543. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29544. this object is deleted
  29545. @param numChannels the number of channels to process
  29546. */
  29547. ResamplingAudioSource (AudioSource* inputSource,
  29548. bool deleteInputWhenDeleted,
  29549. int numChannels = 2);
  29550. /** Destructor. */
  29551. ~ResamplingAudioSource();
  29552. /** Changes the resampling ratio.
  29553. (This value can be changed at any time, even while the source is running).
  29554. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  29555. values will speed it up; lower values will slow it
  29556. down. The ratio must be greater than 0
  29557. */
  29558. void setResamplingRatio (double samplesInPerOutputSample);
  29559. /** Returns the current resampling ratio.
  29560. This is the value that was set by setResamplingRatio().
  29561. */
  29562. double getResamplingRatio() const noexcept { return ratio; }
  29563. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29564. void releaseResources();
  29565. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29566. private:
  29567. OptionalScopedPointer<AudioSource> input;
  29568. double ratio, lastRatio;
  29569. AudioSampleBuffer buffer;
  29570. int bufferPos, sampsInBuffer;
  29571. double subSampleOffset;
  29572. double coefficients[6];
  29573. SpinLock ratioLock;
  29574. const int numChannels;
  29575. HeapBlock<float*> destBuffers, srcBuffers;
  29576. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  29577. void createLowPass (double proportionalRate);
  29578. struct FilterState
  29579. {
  29580. double x1, x2, y1, y2;
  29581. };
  29582. HeapBlock<FilterState> filterStates;
  29583. void resetFilters();
  29584. void applyFilter (float* samples, int num, FilterState& fs);
  29585. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  29586. };
  29587. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29588. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  29589. /**
  29590. An AudioSource that takes a PositionableAudioSource and allows it to be
  29591. played, stopped, started, etc.
  29592. This can also be told use a buffer and background thread to read ahead, and
  29593. if can correct for different sample-rates.
  29594. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  29595. to control playback of an audio file.
  29596. @see AudioSource, AudioSourcePlayer
  29597. */
  29598. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  29599. public ChangeBroadcaster
  29600. {
  29601. public:
  29602. /** Creates an AudioTransportSource.
  29603. After creating one of these, use the setSource() method to select an input source.
  29604. */
  29605. AudioTransportSource();
  29606. /** Destructor. */
  29607. ~AudioTransportSource();
  29608. /** Sets the reader that is being used as the input source.
  29609. This will stop playback, reset the position to 0 and change to the new reader.
  29610. The source passed in will not be deleted by this object, so must be managed by
  29611. the caller.
  29612. @param newSource the new input source to use. This may be zero
  29613. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  29614. is zero, no reading ahead will be done; if it's
  29615. greater than zero, a BufferingAudioSource will be used
  29616. to do the reading-ahead
  29617. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  29618. rate of the source, and playback will be sample-rate
  29619. adjusted to maintain playback at the correct pitch. If
  29620. this is 0, no sample-rate adjustment will be performed
  29621. @param maxNumChannels the maximum number of channels that may need to be played
  29622. */
  29623. void setSource (PositionableAudioSource* newSource,
  29624. int readAheadBufferSize = 0,
  29625. double sourceSampleRateToCorrectFor = 0.0,
  29626. int maxNumChannels = 2);
  29627. /** Changes the current playback position in the source stream.
  29628. The next time the getNextAudioBlock() method is called, this
  29629. is the time from which it'll read data.
  29630. @see getPosition
  29631. */
  29632. void setPosition (double newPosition);
  29633. /** Returns the position that the next data block will be read from
  29634. This is a time in seconds.
  29635. */
  29636. double getCurrentPosition() const;
  29637. /** Returns the stream's length in seconds. */
  29638. double getLengthInSeconds() const;
  29639. /** Returns true if the player has stopped because its input stream ran out of data.
  29640. */
  29641. bool hasStreamFinished() const noexcept { return inputStreamEOF; }
  29642. /** Starts playing (if a source has been selected).
  29643. If it starts playing, this will send a message to any ChangeListeners
  29644. that are registered with this object.
  29645. */
  29646. void start();
  29647. /** Stops playing.
  29648. If it's actually playing, this will send a message to any ChangeListeners
  29649. that are registered with this object.
  29650. */
  29651. void stop();
  29652. /** Returns true if it's currently playing. */
  29653. bool isPlaying() const noexcept { return playing; }
  29654. /** Changes the gain to apply to the output.
  29655. @param newGain a factor by which to multiply the outgoing samples,
  29656. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  29657. */
  29658. void setGain (float newGain) noexcept;
  29659. /** Returns the current gain setting.
  29660. @see setGain
  29661. */
  29662. float getGain() const noexcept { return gain; }
  29663. /** Implementation of the AudioSource method. */
  29664. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29665. /** Implementation of the AudioSource method. */
  29666. void releaseResources();
  29667. /** Implementation of the AudioSource method. */
  29668. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29669. /** Implements the PositionableAudioSource method. */
  29670. void setNextReadPosition (int64 newPosition);
  29671. /** Implements the PositionableAudioSource method. */
  29672. int64 getNextReadPosition() const;
  29673. /** Implements the PositionableAudioSource method. */
  29674. int64 getTotalLength() const;
  29675. /** Implements the PositionableAudioSource method. */
  29676. bool isLooping() const;
  29677. private:
  29678. PositionableAudioSource* source;
  29679. ResamplingAudioSource* resamplerSource;
  29680. BufferingAudioSource* bufferingSource;
  29681. PositionableAudioSource* positionableSource;
  29682. AudioSource* masterSource;
  29683. CriticalSection callbackLock;
  29684. float volatile gain, lastGain;
  29685. bool volatile playing, stopped;
  29686. double sampleRate, sourceSampleRate;
  29687. int blockSize, readAheadBufferSize;
  29688. bool isPrepared, inputStreamEOF;
  29689. void releaseMasterResources();
  29690. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  29691. };
  29692. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29693. /*** End of inlined file: juce_AudioTransportSource.h ***/
  29694. #endif
  29695. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29696. #endif
  29697. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29698. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29699. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29700. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29701. /**
  29702. An AudioSource that takes the audio from another source, and re-maps its
  29703. input and output channels to a different arrangement.
  29704. You can use this to increase or decrease the number of channels that an
  29705. audio source uses, or to re-order those channels.
  29706. Call the reset() method before using it to set up a default mapping, and then
  29707. the setInputChannelMapping() and setOutputChannelMapping() methods to
  29708. create an appropriate mapping, otherwise no channels will be connected and
  29709. it'll produce silence.
  29710. @see AudioSource
  29711. */
  29712. class ChannelRemappingAudioSource : public AudioSource
  29713. {
  29714. public:
  29715. /** Creates a remapping source that will pass on audio from the given input.
  29716. @param source the input source to use. Make sure that this doesn't
  29717. get deleted before the ChannelRemappingAudioSource object
  29718. @param deleteSourceWhenDeleted if true, the input source will be deleted
  29719. when this object is deleted, if false, the caller is
  29720. responsible for its deletion
  29721. */
  29722. ChannelRemappingAudioSource (AudioSource* source,
  29723. bool deleteSourceWhenDeleted);
  29724. /** Destructor. */
  29725. ~ChannelRemappingAudioSource();
  29726. /** Specifies a number of channels that this audio source must produce from its
  29727. getNextAudioBlock() callback.
  29728. */
  29729. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  29730. /** Clears any mapped channels.
  29731. After this, no channels are mapped, so this object will produce silence. Create
  29732. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  29733. */
  29734. void clearAllMappings();
  29735. /** Creates an input channel mapping.
  29736. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  29737. data will be sent to destChannelIndex of our input source.
  29738. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  29739. source specified when this object was created).
  29740. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  29741. during our getNextAudioBlock() callback
  29742. */
  29743. void setInputChannelMapping (int destChannelIndex,
  29744. int sourceChannelIndex);
  29745. /** Creates an output channel mapping.
  29746. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  29747. our input audio source will be copied to channel destChannelIndex of the final buffer.
  29748. @param sourceChannelIndex the index of an output channel coming from our input audio source
  29749. (i.e. the source specified when this object was created).
  29750. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  29751. during our getNextAudioBlock() callback
  29752. */
  29753. void setOutputChannelMapping (int sourceChannelIndex,
  29754. int destChannelIndex);
  29755. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  29756. our input audio source.
  29757. */
  29758. int getRemappedInputChannel (int inputChannelIndex) const;
  29759. /** Returns the output channel to which channel outputChannelIndex of our input audio
  29760. source will be sent to.
  29761. */
  29762. int getRemappedOutputChannel (int outputChannelIndex) const;
  29763. /** Returns an XML object to encapsulate the state of the mappings.
  29764. @see restoreFromXml
  29765. */
  29766. XmlElement* createXml() const;
  29767. /** Restores the mappings from an XML object created by createXML().
  29768. @see createXml
  29769. */
  29770. void restoreFromXml (const XmlElement& e);
  29771. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29772. void releaseResources();
  29773. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29774. private:
  29775. OptionalScopedPointer<AudioSource> source;
  29776. Array <int> remappedInputs, remappedOutputs;
  29777. int requiredNumberOfChannels;
  29778. AudioSampleBuffer buffer;
  29779. AudioSourceChannelInfo remappedInfo;
  29780. CriticalSection lock;
  29781. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  29782. };
  29783. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29784. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29785. #endif
  29786. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29787. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  29788. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29789. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29790. /*** Start of inlined file: juce_IIRFilter.h ***/
  29791. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  29792. #define __JUCE_IIRFILTER_JUCEHEADER__
  29793. /**
  29794. An IIR filter that can perform low, high, or band-pass filtering on an
  29795. audio signal.
  29796. @see IIRFilterAudioSource
  29797. */
  29798. class JUCE_API IIRFilter
  29799. {
  29800. public:
  29801. /** Creates a filter.
  29802. Initially the filter is inactive, so will have no effect on samples that
  29803. you process with it. Use the appropriate method to turn it into the type
  29804. of filter needed.
  29805. */
  29806. IIRFilter();
  29807. /** Creates a copy of another filter. */
  29808. IIRFilter (const IIRFilter& other);
  29809. /** Destructor. */
  29810. ~IIRFilter();
  29811. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29812. Note that this clears the processing state, but the type of filter and
  29813. its coefficients aren't changed. To put a filter into an inactive state, use
  29814. the makeInactive() method.
  29815. */
  29816. void reset() noexcept;
  29817. /** Performs the filter operation on the given set of samples.
  29818. */
  29819. void processSamples (float* samples,
  29820. int numSamples) noexcept;
  29821. /** Processes a single sample, without any locking or checking.
  29822. Use this if you need fast processing of a single value, but be aware that
  29823. this isn't thread-safe in the way that processSamples() is.
  29824. */
  29825. float processSingleSampleRaw (float sample) noexcept;
  29826. /** Sets the filter up to act as a low-pass filter.
  29827. */
  29828. void makeLowPass (double sampleRate,
  29829. double frequency) noexcept;
  29830. /** Sets the filter up to act as a high-pass filter.
  29831. */
  29832. void makeHighPass (double sampleRate,
  29833. double frequency) noexcept;
  29834. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29835. The gain is a scale factor that the low frequencies are multiplied by, so values
  29836. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29837. attenuate them.
  29838. */
  29839. void makeLowShelf (double sampleRate,
  29840. double cutOffFrequency,
  29841. double Q,
  29842. float gainFactor) noexcept;
  29843. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29844. The gain is a scale factor that the high frequencies are multiplied by, so values
  29845. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29846. attenuate them.
  29847. */
  29848. void makeHighShelf (double sampleRate,
  29849. double cutOffFrequency,
  29850. double Q,
  29851. float gainFactor) noexcept;
  29852. /** Sets the filter up to act as a band pass filter centred around a
  29853. frequency, with a variable Q and gain.
  29854. The gain is a scale factor that the centre frequencies are multiplied by, so
  29855. values greater than 1.0 will boost the centre frequencies, values less than
  29856. 1.0 will attenuate them.
  29857. */
  29858. void makeBandPass (double sampleRate,
  29859. double centreFrequency,
  29860. double Q,
  29861. float gainFactor) noexcept;
  29862. /** Clears the filter's coefficients so that it becomes inactive.
  29863. */
  29864. void makeInactive() noexcept;
  29865. /** Makes this filter duplicate the set-up of another one.
  29866. */
  29867. void copyCoefficientsFrom (const IIRFilter& other) noexcept;
  29868. protected:
  29869. CriticalSection processLock;
  29870. void setCoefficients (double c1, double c2, double c3,
  29871. double c4, double c5, double c6) noexcept;
  29872. bool active;
  29873. float coefficients[6];
  29874. float x1, x2, y1, y2;
  29875. // (use the copyCoefficientsFrom() method instead of this operator)
  29876. IIRFilter& operator= (const IIRFilter&);
  29877. JUCE_LEAK_DETECTOR (IIRFilter);
  29878. };
  29879. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29880. /*** End of inlined file: juce_IIRFilter.h ***/
  29881. /**
  29882. An AudioSource that performs an IIR filter on another source.
  29883. */
  29884. class JUCE_API IIRFilterAudioSource : public AudioSource
  29885. {
  29886. public:
  29887. /** Creates a IIRFilterAudioSource for a given input source.
  29888. @param inputSource the input source to read from - this must not be null
  29889. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29890. this object is deleted
  29891. */
  29892. IIRFilterAudioSource (AudioSource* inputSource,
  29893. bool deleteInputWhenDeleted);
  29894. /** Destructor. */
  29895. ~IIRFilterAudioSource();
  29896. /** Changes the filter to use the same parameters as the one being passed in. */
  29897. void setFilterParameters (const IIRFilter& newSettings);
  29898. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29899. void releaseResources();
  29900. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29901. private:
  29902. OptionalScopedPointer<AudioSource> input;
  29903. OwnedArray <IIRFilter> iirFilters;
  29904. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29905. };
  29906. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29907. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29908. #endif
  29909. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29910. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29911. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29912. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29913. /**
  29914. An AudioSource that mixes together the output of a set of other AudioSources.
  29915. Input sources can be added and removed while the mixer is running as long as their
  29916. prepareToPlay() and releaseResources() methods are called before and after adding
  29917. them to the mixer.
  29918. */
  29919. class JUCE_API MixerAudioSource : public AudioSource
  29920. {
  29921. public:
  29922. /** Creates a MixerAudioSource.
  29923. */
  29924. MixerAudioSource();
  29925. /** Destructor. */
  29926. ~MixerAudioSource();
  29927. /** Adds an input source to the mixer.
  29928. If the mixer is running you'll need to make sure that the input source
  29929. is ready to play by calling its prepareToPlay() method before adding it.
  29930. If the mixer is stopped, then its input sources will be automatically
  29931. prepared when the mixer's prepareToPlay() method is called.
  29932. @param newInput the source to add to the mixer
  29933. @param deleteWhenRemoved if true, then this source will be deleted when
  29934. the mixer is deleted or when removeAllInputs() is
  29935. called (unless the source is previously removed
  29936. with the removeInputSource method)
  29937. */
  29938. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29939. /** Removes an input source.
  29940. If the mixer is running, this will remove the source but not call its
  29941. releaseResources() method, so the caller might want to do this manually.
  29942. @param input the source to remove
  29943. @param deleteSource whether to delete this source after it's been removed
  29944. */
  29945. void removeInputSource (AudioSource* input, bool deleteSource);
  29946. /** Removes all the input sources.
  29947. If the mixer is running, this will remove the sources but not call their
  29948. releaseResources() method, so the caller might want to do this manually.
  29949. Any sources which were added with the deleteWhenRemoved flag set will be
  29950. deleted by this method.
  29951. */
  29952. void removeAllInputs();
  29953. /** Implementation of the AudioSource method.
  29954. This will call prepareToPlay() on all its input sources.
  29955. */
  29956. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29957. /** Implementation of the AudioSource method.
  29958. This will call releaseResources() on all its input sources.
  29959. */
  29960. void releaseResources();
  29961. /** Implementation of the AudioSource method. */
  29962. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29963. private:
  29964. Array <AudioSource*> inputs;
  29965. BigInteger inputsToDelete;
  29966. CriticalSection lock;
  29967. AudioSampleBuffer tempBuffer;
  29968. double currentSampleRate;
  29969. int bufferSizeExpected;
  29970. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29971. };
  29972. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29973. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29974. #endif
  29975. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29976. #endif
  29977. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29978. #endif
  29979. #ifndef __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  29980. /*** Start of inlined file: juce_ReverbAudioSource.h ***/
  29981. #ifndef __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  29982. #define __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  29983. /*** Start of inlined file: juce_Reverb.h ***/
  29984. #ifndef __JUCE_REVERB_JUCEHEADER__
  29985. #define __JUCE_REVERB_JUCEHEADER__
  29986. /**
  29987. Performs a simple reverb effect on a stream of audio data.
  29988. This is a simple stereo reverb, based on the technique and tunings used in FreeVerb.
  29989. Use setSampleRate() to prepare it, and then call processStereo() or processMono() to
  29990. apply the reverb to your audio data.
  29991. @see ReverbAudioSource
  29992. */
  29993. class Reverb
  29994. {
  29995. public:
  29996. Reverb()
  29997. {
  29998. setParameters (Parameters());
  29999. setSampleRate (44100.0);
  30000. }
  30001. /** Holds the parameters being used by a Reverb object. */
  30002. struct Parameters
  30003. {
  30004. Parameters() noexcept
  30005. : roomSize (0.5f),
  30006. damping (0.5f),
  30007. wetLevel (0.33f),
  30008. dryLevel (0.4f),
  30009. width (1.0f),
  30010. freezeMode (0)
  30011. {}
  30012. float roomSize; /**< Room size, 0 to 1.0, where 1.0 is big, 0 is small. */
  30013. float damping; /**< Damping, 0 to 1.0, where 0 is not damped, 1.0 is fully damped. */
  30014. float wetLevel; /**< Wet level, 0 to 1.0 */
  30015. float dryLevel; /**< Dry level, 0 to 1.0 */
  30016. float width; /**< Reverb width, 0 to 1.0, where 1.0 is very wide. */
  30017. float freezeMode; /**< Freeze mode - values < 0.5 are "normal" mode, values > 0.5
  30018. put the reverb into a continuous feedback loop. */
  30019. };
  30020. /** Returns the reverb's current parameters. */
  30021. const Parameters& getParameters() const noexcept { return parameters; }
  30022. /** Applies a new set of parameters to the reverb.
  30023. Note that this doesn't attempt to lock the reverb, so if you call this in parallel with
  30024. the process method, you may get artifacts.
  30025. */
  30026. void setParameters (const Parameters& newParams)
  30027. {
  30028. const float wetScaleFactor = 3.0f;
  30029. const float dryScaleFactor = 2.0f;
  30030. const float wet = newParams.wetLevel * wetScaleFactor;
  30031. wet1 = wet * (newParams.width * 0.5f + 0.5f);
  30032. wet2 = wet * (1.0f - newParams.width) * 0.5f;
  30033. dry = newParams.dryLevel * dryScaleFactor;
  30034. gain = isFrozen (newParams.freezeMode) ? 0.0f : 0.015f;
  30035. parameters = newParams;
  30036. shouldUpdateDamping = true;
  30037. }
  30038. /** Sets the sample rate that will be used for the reverb.
  30039. You must call this before the process methods, in order to tell it the correct sample rate.
  30040. */
  30041. void setSampleRate (const double sampleRate)
  30042. {
  30043. jassert (sampleRate > 0);
  30044. static const short combTunings[] = { 1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617 }; // (at 44100Hz)
  30045. static const short allPassTunings[] = { 556, 441, 341, 225 };
  30046. const int stereoSpread = 23;
  30047. const int intSampleRate = (int) sampleRate;
  30048. int i;
  30049. for (i = 0; i < numCombs; ++i)
  30050. {
  30051. comb[0][i].setSize ((intSampleRate * combTunings[i]) / 44100);
  30052. comb[1][i].setSize ((intSampleRate * (combTunings[i] + stereoSpread)) / 44100);
  30053. }
  30054. for (i = 0; i < numAllPasses; ++i)
  30055. {
  30056. allPass[0][i].setSize ((intSampleRate * allPassTunings[i]) / 44100);
  30057. allPass[1][i].setSize ((intSampleRate * (allPassTunings[i] + stereoSpread)) / 44100);
  30058. }
  30059. shouldUpdateDamping = true;
  30060. }
  30061. /** Clears the reverb's buffers. */
  30062. void reset()
  30063. {
  30064. for (int j = 0; j < numChannels; ++j)
  30065. {
  30066. int i;
  30067. for (i = 0; i < numCombs; ++i)
  30068. comb[j][i].clear();
  30069. for (i = 0; i < numAllPasses; ++i)
  30070. allPass[j][i].clear();
  30071. }
  30072. }
  30073. /** Applies the reverb to two stereo channels of audio data. */
  30074. void processStereo (float* const left, float* const right, const int numSamples) noexcept
  30075. {
  30076. jassert (left != nullptr && right != nullptr);
  30077. if (shouldUpdateDamping)
  30078. updateDamping();
  30079. for (int i = 0; i < numSamples; ++i)
  30080. {
  30081. const float input = (left[i] + right[i]) * gain;
  30082. float outL = 0, outR = 0;
  30083. int j;
  30084. for (j = 0; j < numCombs; ++j) // accumulate the comb filters in parallel
  30085. {
  30086. outL += comb[0][j].process (input);
  30087. outR += comb[1][j].process (input);
  30088. }
  30089. for (j = 0; j < numAllPasses; ++j) // run the allpass filters in series
  30090. {
  30091. outL = allPass[0][j].process (outL);
  30092. outR = allPass[1][j].process (outR);
  30093. }
  30094. left[i] = outL * wet1 + outR * wet2 + left[i] * dry;
  30095. right[i] = outR * wet1 + outL * wet2 + right[i] * dry;
  30096. }
  30097. }
  30098. /** Applies the reverb to a single mono channel of audio data. */
  30099. void processMono (float* const samples, const int numSamples) noexcept
  30100. {
  30101. jassert (samples != nullptr);
  30102. if (shouldUpdateDamping)
  30103. updateDamping();
  30104. for (int i = 0; i < numSamples; ++i)
  30105. {
  30106. const float input = samples[i] * gain;
  30107. float output = 0;
  30108. int j;
  30109. for (j = 0; j < numCombs; ++j) // accumulate the comb filters in parallel
  30110. output += comb[0][j].process (input);
  30111. for (j = 0; j < numAllPasses; ++j) // run the allpass filters in series
  30112. output = allPass[0][j].process (output);
  30113. samples[i] = output * wet1 + input * dry;
  30114. }
  30115. }
  30116. private:
  30117. Parameters parameters;
  30118. volatile bool shouldUpdateDamping;
  30119. float gain, wet1, wet2, dry;
  30120. inline static bool isFrozen (const float freezeMode) noexcept { return freezeMode >= 0.5f; }
  30121. void updateDamping() noexcept
  30122. {
  30123. const float roomScaleFactor = 0.28f;
  30124. const float roomOffset = 0.7f;
  30125. const float dampScaleFactor = 0.4f;
  30126. shouldUpdateDamping = false;
  30127. if (isFrozen (parameters.freezeMode))
  30128. setDamping (1.0f, 0.0f);
  30129. else
  30130. setDamping (parameters.damping * dampScaleFactor,
  30131. parameters.roomSize * roomScaleFactor + roomOffset);
  30132. }
  30133. void setDamping (const float dampingToUse, const float roomSizeToUse) noexcept
  30134. {
  30135. for (int j = 0; j < numChannels; ++j)
  30136. for (int i = numCombs; --i >= 0;)
  30137. comb[j][i].setFeedbackAndDamp (roomSizeToUse, dampingToUse);
  30138. }
  30139. class CombFilter
  30140. {
  30141. public:
  30142. CombFilter() noexcept : bufferSize (0), bufferIndex (0) {}
  30143. void setSize (const int size)
  30144. {
  30145. if (size != bufferSize)
  30146. {
  30147. bufferIndex = 0;
  30148. buffer.malloc (size);
  30149. bufferSize = size;
  30150. }
  30151. clear();
  30152. }
  30153. void clear() noexcept
  30154. {
  30155. last = 0;
  30156. buffer.clear (bufferSize);
  30157. }
  30158. void setFeedbackAndDamp (const float f, const float d) noexcept
  30159. {
  30160. damp1 = d;
  30161. damp2 = 1.0f - d;
  30162. feedback = f;
  30163. }
  30164. inline float process (const float input) noexcept
  30165. {
  30166. const float output = buffer [bufferIndex];
  30167. last = (output * damp2) + (last * damp1);
  30168. JUCE_UNDENORMALISE (last);
  30169. float temp = input + (last * feedback);
  30170. JUCE_UNDENORMALISE (temp);
  30171. buffer [bufferIndex] = temp;
  30172. bufferIndex = (bufferIndex + 1) % bufferSize;
  30173. return output;
  30174. }
  30175. private:
  30176. HeapBlock<float> buffer;
  30177. int bufferSize, bufferIndex;
  30178. float feedback, last, damp1, damp2;
  30179. JUCE_DECLARE_NON_COPYABLE (CombFilter);
  30180. };
  30181. class AllPassFilter
  30182. {
  30183. public:
  30184. AllPassFilter() noexcept : bufferSize (0), bufferIndex (0) {}
  30185. void setSize (const int size)
  30186. {
  30187. if (size != bufferSize)
  30188. {
  30189. bufferIndex = 0;
  30190. buffer.malloc (size);
  30191. bufferSize = size;
  30192. }
  30193. clear();
  30194. }
  30195. void clear() noexcept
  30196. {
  30197. buffer.clear (bufferSize);
  30198. }
  30199. inline float process (const float input) noexcept
  30200. {
  30201. const float bufferedValue = buffer [bufferIndex];
  30202. float temp = input + (bufferedValue * 0.5f);
  30203. JUCE_UNDENORMALISE (temp);
  30204. buffer [bufferIndex] = temp;
  30205. bufferIndex = (bufferIndex + 1) % bufferSize;
  30206. return bufferedValue - input;
  30207. }
  30208. private:
  30209. HeapBlock<float> buffer;
  30210. int bufferSize, bufferIndex;
  30211. JUCE_DECLARE_NON_COPYABLE (AllPassFilter);
  30212. };
  30213. enum { numCombs = 8, numAllPasses = 4, numChannels = 2 };
  30214. CombFilter comb [numChannels][numCombs];
  30215. AllPassFilter allPass [numChannels][numAllPasses];
  30216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Reverb);
  30217. };
  30218. #endif // __JUCE_REVERB_JUCEHEADER__
  30219. /*** End of inlined file: juce_Reverb.h ***/
  30220. /**
  30221. An AudioSource that uses the Reverb class to apply a reverb to another AudioSource.
  30222. @see Reverb
  30223. */
  30224. class JUCE_API ReverbAudioSource : public AudioSource
  30225. {
  30226. public:
  30227. /** Creates a ReverbAudioSource to process a given input source.
  30228. @param inputSource the input source to read from - this must not be null
  30229. @param deleteInputWhenDeleted if true, the input source will be deleted when
  30230. this object is deleted
  30231. */
  30232. ReverbAudioSource (AudioSource* inputSource,
  30233. bool deleteInputWhenDeleted);
  30234. /** Destructor. */
  30235. ~ReverbAudioSource();
  30236. /** Returns the parameters from the reverb. */
  30237. const Reverb::Parameters& getParameters() const noexcept { return reverb.getParameters(); }
  30238. /** Changes the reverb's parameters. */
  30239. void setParameters (const Reverb::Parameters& newParams);
  30240. void setBypassed (bool isBypassed) noexcept;
  30241. bool isBypassed() const noexcept { return bypass; }
  30242. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30243. void releaseResources();
  30244. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30245. private:
  30246. CriticalSection lock;
  30247. OptionalScopedPointer<AudioSource> input;
  30248. Reverb reverb;
  30249. volatile bool bypass;
  30250. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ReverbAudioSource);
  30251. };
  30252. #endif // __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  30253. /*** End of inlined file: juce_ReverbAudioSource.h ***/
  30254. #endif
  30255. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30256. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  30257. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30258. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30259. /**
  30260. A simple AudioSource that generates a sine wave.
  30261. */
  30262. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  30263. {
  30264. public:
  30265. /** Creates a ToneGeneratorAudioSource. */
  30266. ToneGeneratorAudioSource();
  30267. /** Destructor. */
  30268. ~ToneGeneratorAudioSource();
  30269. /** Sets the signal's amplitude. */
  30270. void setAmplitude (float newAmplitude);
  30271. /** Sets the signal's frequency. */
  30272. void setFrequency (double newFrequencyHz);
  30273. /** Implementation of the AudioSource method. */
  30274. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30275. /** Implementation of the AudioSource method. */
  30276. void releaseResources();
  30277. /** Implementation of the AudioSource method. */
  30278. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30279. private:
  30280. double frequency, sampleRate;
  30281. double currentPhase, phasePerSample;
  30282. float amplitude;
  30283. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  30284. };
  30285. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30286. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  30287. #endif
  30288. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30289. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  30290. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30291. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30292. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  30293. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30294. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30295. class AudioDeviceManager;
  30296. /**
  30297. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  30298. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  30299. method. Each of the objects returned can then be used to list the available
  30300. devices of that type. E.g.
  30301. @code
  30302. OwnedArray <AudioIODeviceType> types;
  30303. myAudioDeviceManager.createAudioDeviceTypes (types);
  30304. for (int i = 0; i < types.size(); ++i)
  30305. {
  30306. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  30307. types[i]->scanForDevices(); // This must be called before getting the list of devices
  30308. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  30309. for (int j = 0; j < deviceNames.size(); ++j)
  30310. {
  30311. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  30312. ...
  30313. }
  30314. }
  30315. @endcode
  30316. For an easier way of managing audio devices and their settings, have a look at the
  30317. AudioDeviceManager class.
  30318. @see AudioIODevice, AudioDeviceManager
  30319. */
  30320. class JUCE_API AudioIODeviceType
  30321. {
  30322. public:
  30323. /** Returns the name of this type of driver that this object manages.
  30324. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  30325. */
  30326. const String& getTypeName() const noexcept { return typeName; }
  30327. /** Refreshes the object's cached list of known devices.
  30328. This must be called at least once before calling getDeviceNames() or any of
  30329. the other device creation methods.
  30330. */
  30331. virtual void scanForDevices() = 0;
  30332. /** Returns the list of available devices of this type.
  30333. The scanForDevices() method must have been called to create this list.
  30334. @param wantInputNames only really used by DirectSound where devices are split up
  30335. into inputs and outputs, this indicates whether to use
  30336. the input or output name to refer to a pair of devices.
  30337. */
  30338. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  30339. /** Returns the name of the default device.
  30340. This will be one of the names from the getDeviceNames() list.
  30341. @param forInput if true, this means that a default input device should be
  30342. returned; if false, it should return the default output
  30343. */
  30344. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  30345. /** Returns the index of a given device in the list of device names.
  30346. If asInput is true, it shows the index in the inputs list, otherwise it
  30347. looks for it in the outputs list.
  30348. */
  30349. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  30350. /** Returns true if two different devices can be used for the input and output.
  30351. */
  30352. virtual bool hasSeparateInputsAndOutputs() const = 0;
  30353. /** Creates one of the devices of this type.
  30354. The deviceName must be one of the strings returned by getDeviceNames(), and
  30355. scanForDevices() must have been called before this method is used.
  30356. */
  30357. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  30358. const String& inputDeviceName) = 0;
  30359. struct DeviceSetupDetails
  30360. {
  30361. AudioDeviceManager* manager;
  30362. int minNumInputChannels, maxNumInputChannels;
  30363. int minNumOutputChannels, maxNumOutputChannels;
  30364. bool useStereoPairs;
  30365. };
  30366. /** Destructor. */
  30367. virtual ~AudioIODeviceType();
  30368. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  30369. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  30370. /** Creates an iOS device type if it's available on this platform, or returns null. */
  30371. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  30372. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  30373. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  30374. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  30375. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  30376. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  30377. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  30378. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  30379. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  30380. /** Creates a JACK device type if it's available on this platform, or returns null. */
  30381. static AudioIODeviceType* createAudioIODeviceType_JACK();
  30382. /** Creates an Android device type if it's available on this platform, or returns null. */
  30383. static AudioIODeviceType* createAudioIODeviceType_Android();
  30384. protected:
  30385. explicit AudioIODeviceType (const String& typeName);
  30386. private:
  30387. String typeName;
  30388. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  30389. };
  30390. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30391. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  30392. /*** Start of inlined file: juce_MidiInput.h ***/
  30393. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  30394. #define __JUCE_MIDIINPUT_JUCEHEADER__
  30395. /*** Start of inlined file: juce_MidiMessage.h ***/
  30396. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  30397. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  30398. /**
  30399. Encapsulates a MIDI message.
  30400. @see MidiMessageSequence, MidiOutput, MidiInput
  30401. */
  30402. class JUCE_API MidiMessage
  30403. {
  30404. public:
  30405. /** Creates a 3-byte short midi message.
  30406. @param byte1 message byte 1
  30407. @param byte2 message byte 2
  30408. @param byte3 message byte 3
  30409. @param timeStamp the time to give the midi message - this value doesn't
  30410. use any particular units, so will be application-specific
  30411. */
  30412. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) noexcept;
  30413. /** Creates a 2-byte short midi message.
  30414. @param byte1 message byte 1
  30415. @param byte2 message byte 2
  30416. @param timeStamp the time to give the midi message - this value doesn't
  30417. use any particular units, so will be application-specific
  30418. */
  30419. MidiMessage (int byte1, int byte2, double timeStamp = 0) noexcept;
  30420. /** Creates a 1-byte short midi message.
  30421. @param byte1 message byte 1
  30422. @param timeStamp the time to give the midi message - this value doesn't
  30423. use any particular units, so will be application-specific
  30424. */
  30425. MidiMessage (int byte1, double timeStamp = 0) noexcept;
  30426. /** Creates a midi message from a block of data. */
  30427. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  30428. /** Reads the next midi message from some data.
  30429. This will read as many bytes from a data stream as it needs to make a
  30430. complete message, and will return the number of bytes it used. This lets
  30431. you read a sequence of midi messages from a file or stream.
  30432. @param data the data to read from
  30433. @param maxBytesToUse the maximum number of bytes it's allowed to read
  30434. @param numBytesUsed returns the number of bytes that were actually needed
  30435. @param lastStatusByte in a sequence of midi messages, the initial byte
  30436. can be dropped from a message if it's the same as the
  30437. first byte of the previous message, so this lets you
  30438. supply the byte to use if the first byte of the message
  30439. has in fact been dropped.
  30440. @param timeStamp the time to give the midi message - this value doesn't
  30441. use any particular units, so will be application-specific
  30442. */
  30443. MidiMessage (const void* data, int maxBytesToUse,
  30444. int& numBytesUsed, uint8 lastStatusByte,
  30445. double timeStamp = 0);
  30446. /** Creates an active-sense message.
  30447. Since the MidiMessage has to contain a valid message, this default constructor
  30448. just initialises it with an empty sysex message.
  30449. */
  30450. MidiMessage() noexcept;
  30451. /** Creates a copy of another midi message. */
  30452. MidiMessage (const MidiMessage& other);
  30453. /** Creates a copy of another midi message, with a different timestamp. */
  30454. MidiMessage (const MidiMessage& other, double newTimeStamp);
  30455. /** Destructor. */
  30456. ~MidiMessage();
  30457. /** Copies this message from another one. */
  30458. MidiMessage& operator= (const MidiMessage& other);
  30459. /** Returns a pointer to the raw midi data.
  30460. @see getRawDataSize
  30461. */
  30462. uint8* getRawData() const noexcept { return data; }
  30463. /** Returns the number of bytes of data in the message.
  30464. @see getRawData
  30465. */
  30466. int getRawDataSize() const noexcept { return size; }
  30467. /** Returns the timestamp associated with this message.
  30468. The exact meaning of this time and its units will vary, as messages are used in
  30469. a variety of different contexts.
  30470. If you're getting the message from a midi file, this could be a time in seconds, or
  30471. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  30472. If the message is being used in a MidiBuffer, it might indicate the number of
  30473. audio samples from the start of the buffer.
  30474. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  30475. for details of the way that it initialises this value.
  30476. @see setTimeStamp, addToTimeStamp
  30477. */
  30478. double getTimeStamp() const noexcept { return timeStamp; }
  30479. /** Changes the message's associated timestamp.
  30480. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  30481. @see addToTimeStamp, getTimeStamp
  30482. */
  30483. void setTimeStamp (double newTimestamp) noexcept { timeStamp = newTimestamp; }
  30484. /** Adds a value to the message's timestamp.
  30485. The units for the timestamp will be application-specific.
  30486. */
  30487. void addToTimeStamp (double delta) noexcept { timeStamp += delta; }
  30488. /** Returns the midi channel associated with the message.
  30489. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  30490. if it's a sysex)
  30491. @see isForChannel, setChannel
  30492. */
  30493. int getChannel() const noexcept;
  30494. /** Returns true if the message applies to the given midi channel.
  30495. @param channelNumber the channel number to look for, in the range 1 to 16
  30496. @see getChannel, setChannel
  30497. */
  30498. bool isForChannel (int channelNumber) const noexcept;
  30499. /** Changes the message's midi channel.
  30500. This won't do anything for non-channel messages like sysexes.
  30501. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  30502. */
  30503. void setChannel (int newChannelNumber) noexcept;
  30504. /** Returns true if this is a system-exclusive message.
  30505. */
  30506. bool isSysEx() const noexcept;
  30507. /** Returns a pointer to the sysex data inside the message.
  30508. If this event isn't a sysex event, it'll return 0.
  30509. @see getSysExDataSize
  30510. */
  30511. const uint8* getSysExData() const noexcept;
  30512. /** Returns the size of the sysex data.
  30513. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  30514. @see getSysExData
  30515. */
  30516. int getSysExDataSize() const noexcept;
  30517. /** Returns true if this message is a 'key-down' event.
  30518. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  30519. velocity 0, it will still be considered to be a note-on and the
  30520. method will return true. If returnTrueForVelocity0 is false, then
  30521. if this is a note-on event with velocity 0, it'll be regarded as
  30522. a note-off, and the method will return false
  30523. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  30524. */
  30525. bool isNoteOn (bool returnTrueForVelocity0 = false) const noexcept;
  30526. /** Creates a key-down message (using a floating-point velocity).
  30527. @param channel the midi channel, in the range 1 to 16
  30528. @param noteNumber the key number, 0 to 127
  30529. @param velocity in the range 0 to 1.0
  30530. @see isNoteOn
  30531. */
  30532. static MidiMessage noteOn (int channel, int noteNumber, float velocity) noexcept;
  30533. /** Creates a key-down message (using an integer velocity).
  30534. @param channel the midi channel, in the range 1 to 16
  30535. @param noteNumber the key number, 0 to 127
  30536. @param velocity in the range 0 to 127
  30537. @see isNoteOn
  30538. */
  30539. static MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) noexcept;
  30540. /** Returns true if this message is a 'key-up' event.
  30541. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  30542. for a note-on event with a velocity of 0.
  30543. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  30544. */
  30545. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const noexcept;
  30546. /** Creates a key-up message.
  30547. @param channel the midi channel, in the range 1 to 16
  30548. @param noteNumber the key number, 0 to 127
  30549. @param velocity in the range 0 to 127
  30550. @see isNoteOff
  30551. */
  30552. static MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) noexcept;
  30553. /** Returns true if this message is a 'key-down' or 'key-up' event.
  30554. @see isNoteOn, isNoteOff
  30555. */
  30556. bool isNoteOnOrOff() const noexcept;
  30557. /** Returns the midi note number for note-on and note-off messages.
  30558. If the message isn't a note-on or off, the value returned is undefined.
  30559. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  30560. */
  30561. int getNoteNumber() const noexcept;
  30562. /** Changes the midi note number of a note-on or note-off message.
  30563. If the message isn't a note on or off, this will do nothing.
  30564. */
  30565. void setNoteNumber (int newNoteNumber) noexcept;
  30566. /** Returns the velocity of a note-on or note-off message.
  30567. The value returned will be in the range 0 to 127.
  30568. If the message isn't a note-on or off event, it will return 0.
  30569. @see getFloatVelocity
  30570. */
  30571. uint8 getVelocity() const noexcept;
  30572. /** Returns the velocity of a note-on or note-off message.
  30573. The value returned will be in the range 0 to 1.0
  30574. If the message isn't a note-on or off event, it will return 0.
  30575. @see getVelocity, setVelocity
  30576. */
  30577. float getFloatVelocity() const noexcept;
  30578. /** Changes the velocity of a note-on or note-off message.
  30579. If the message isn't a note on or off, this will do nothing.
  30580. @param newVelocity the new velocity, in the range 0 to 1.0
  30581. @see getFloatVelocity, multiplyVelocity
  30582. */
  30583. void setVelocity (float newVelocity) noexcept;
  30584. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  30585. If the message isn't a note on or off, this will do nothing.
  30586. @param scaleFactor the value by which to multiply the velocity
  30587. @see setVelocity
  30588. */
  30589. void multiplyVelocity (float scaleFactor) noexcept;
  30590. /** Returns true if this message is a 'sustain pedal down' controller message. */
  30591. bool isSustainPedalOn() const noexcept;
  30592. /** Returns true if this message is a 'sustain pedal up' controller message. */
  30593. bool isSustainPedalOff() const noexcept;
  30594. /** Returns true if this message is a 'sostenuto pedal down' controller message. */
  30595. bool isSostenutoPedalOn() const noexcept;
  30596. /** Returns true if this message is a 'sostenuto pedal up' controller message. */
  30597. bool isSostenutoPedalOff() const noexcept;
  30598. /** Returns true if this message is a 'soft pedal down' controller message. */
  30599. bool isSoftPedalOn() const noexcept;
  30600. /** Returns true if this message is a 'soft pedal up' controller message. */
  30601. bool isSoftPedalOff() const noexcept;
  30602. /** Returns true if the message is a program (patch) change message.
  30603. @see getProgramChangeNumber, getGMInstrumentName
  30604. */
  30605. bool isProgramChange() const noexcept;
  30606. /** Returns the new program number of a program change message.
  30607. If the message isn't a program change, the value returned will be
  30608. nonsense.
  30609. @see isProgramChange, getGMInstrumentName
  30610. */
  30611. int getProgramChangeNumber() const noexcept;
  30612. /** Creates a program-change message.
  30613. @param channel the midi channel, in the range 1 to 16
  30614. @param programNumber the midi program number, 0 to 127
  30615. @see isProgramChange, getGMInstrumentName
  30616. */
  30617. static MidiMessage programChange (int channel, int programNumber) noexcept;
  30618. /** Returns true if the message is a pitch-wheel move.
  30619. @see getPitchWheelValue, pitchWheel
  30620. */
  30621. bool isPitchWheel() const noexcept;
  30622. /** Returns the pitch wheel position from a pitch-wheel move message.
  30623. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  30624. If called for messages which aren't pitch wheel events, the number returned will be
  30625. nonsense.
  30626. @see isPitchWheel
  30627. */
  30628. int getPitchWheelValue() const noexcept;
  30629. /** Creates a pitch-wheel move message.
  30630. @param channel the midi channel, in the range 1 to 16
  30631. @param position the wheel position, in the range 0 to 16383
  30632. @see isPitchWheel
  30633. */
  30634. static MidiMessage pitchWheel (int channel, int position) noexcept;
  30635. /** Returns true if the message is an aftertouch event.
  30636. For aftertouch events, use the getNoteNumber() method to find out the key
  30637. that it applies to, and getAftertouchValue() to find out the amount. Use
  30638. getChannel() to find out the channel.
  30639. @see getAftertouchValue, getNoteNumber
  30640. */
  30641. bool isAftertouch() const noexcept;
  30642. /** Returns the amount of aftertouch from an aftertouch messages.
  30643. The value returned is in the range 0 to 127, and will be nonsense for messages
  30644. other than aftertouch messages.
  30645. @see isAftertouch
  30646. */
  30647. int getAfterTouchValue() const noexcept;
  30648. /** Creates an aftertouch message.
  30649. @param channel the midi channel, in the range 1 to 16
  30650. @param noteNumber the key number, 0 to 127
  30651. @param aftertouchAmount the amount of aftertouch, 0 to 127
  30652. @see isAftertouch
  30653. */
  30654. static MidiMessage aftertouchChange (int channel,
  30655. int noteNumber,
  30656. int aftertouchAmount) noexcept;
  30657. /** Returns true if the message is a channel-pressure change event.
  30658. This is like aftertouch, but common to the whole channel rather than a specific
  30659. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  30660. to find out the channel.
  30661. @see channelPressureChange
  30662. */
  30663. bool isChannelPressure() const noexcept;
  30664. /** Returns the pressure from a channel pressure change message.
  30665. @returns the pressure, in the range 0 to 127
  30666. @see isChannelPressure, channelPressureChange
  30667. */
  30668. int getChannelPressureValue() const noexcept;
  30669. /** Creates a channel-pressure change event.
  30670. @param channel the midi channel: 1 to 16
  30671. @param pressure the pressure, 0 to 127
  30672. @see isChannelPressure
  30673. */
  30674. static MidiMessage channelPressureChange (int channel, int pressure) noexcept;
  30675. /** Returns true if this is a midi controller message.
  30676. @see getControllerNumber, getControllerValue, controllerEvent
  30677. */
  30678. bool isController() const noexcept;
  30679. /** Returns the controller number of a controller message.
  30680. The name of the controller can be looked up using the getControllerName() method.
  30681. Note that the value returned is invalid for messages that aren't controller changes.
  30682. @see isController, getControllerName, getControllerValue
  30683. */
  30684. int getControllerNumber() const noexcept;
  30685. /** Returns the controller value from a controller message.
  30686. A value 0 to 127 is returned to indicate the new controller position.
  30687. Note that the value returned is invalid for messages that aren't controller changes.
  30688. @see isController, getControllerNumber
  30689. */
  30690. int getControllerValue() const noexcept;
  30691. /** Returns true if this message is a controller message and if it has the specified
  30692. controller type.
  30693. */
  30694. bool isControllerOfType (int controllerType) const noexcept;
  30695. /** Creates a controller message.
  30696. @param channel the midi channel, in the range 1 to 16
  30697. @param controllerType the type of controller
  30698. @param value the controller value
  30699. @see isController
  30700. */
  30701. static MidiMessage controllerEvent (int channel,
  30702. int controllerType,
  30703. int value) noexcept;
  30704. /** Checks whether this message is an all-notes-off message.
  30705. @see allNotesOff
  30706. */
  30707. bool isAllNotesOff() const noexcept;
  30708. /** Checks whether this message is an all-sound-off message.
  30709. @see allSoundOff
  30710. */
  30711. bool isAllSoundOff() const noexcept;
  30712. /** Creates an all-notes-off message.
  30713. @param channel the midi channel, in the range 1 to 16
  30714. @see isAllNotesOff
  30715. */
  30716. static MidiMessage allNotesOff (int channel) noexcept;
  30717. /** Creates an all-sound-off message.
  30718. @param channel the midi channel, in the range 1 to 16
  30719. @see isAllSoundOff
  30720. */
  30721. static MidiMessage allSoundOff (int channel) noexcept;
  30722. /** Creates an all-controllers-off message.
  30723. @param channel the midi channel, in the range 1 to 16
  30724. */
  30725. static MidiMessage allControllersOff (int channel) noexcept;
  30726. /** Returns true if this event is a meta-event.
  30727. Meta-events are things like tempo changes, track names, etc.
  30728. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30729. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30730. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30731. */
  30732. bool isMetaEvent() const noexcept;
  30733. /** Returns a meta-event's type number.
  30734. If the message isn't a meta-event, this will return -1.
  30735. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30736. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30737. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30738. */
  30739. int getMetaEventType() const noexcept;
  30740. /** Returns a pointer to the data in a meta-event.
  30741. @see isMetaEvent, getMetaEventLength
  30742. */
  30743. const uint8* getMetaEventData() const noexcept;
  30744. /** Returns the length of the data for a meta-event.
  30745. @see isMetaEvent, getMetaEventData
  30746. */
  30747. int getMetaEventLength() const noexcept;
  30748. /** Returns true if this is a 'track' meta-event. */
  30749. bool isTrackMetaEvent() const noexcept;
  30750. /** Returns true if this is an 'end-of-track' meta-event. */
  30751. bool isEndOfTrackMetaEvent() const noexcept;
  30752. /** Creates an end-of-track meta-event.
  30753. @see isEndOfTrackMetaEvent
  30754. */
  30755. static MidiMessage endOfTrack() noexcept;
  30756. /** Returns true if this is an 'track name' meta-event.
  30757. You can use the getTextFromTextMetaEvent() method to get the track's name.
  30758. */
  30759. bool isTrackNameEvent() const noexcept;
  30760. /** Returns true if this is a 'text' meta-event.
  30761. @see getTextFromTextMetaEvent
  30762. */
  30763. bool isTextMetaEvent() const noexcept;
  30764. /** Returns the text from a text meta-event.
  30765. @see isTextMetaEvent
  30766. */
  30767. String getTextFromTextMetaEvent() const;
  30768. /** Returns true if this is a 'tempo' meta-event.
  30769. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  30770. */
  30771. bool isTempoMetaEvent() const noexcept;
  30772. /** Returns the tick length from a tempo meta-event.
  30773. @param timeFormat the 16-bit time format value from the midi file's header.
  30774. @returns the tick length (in seconds).
  30775. @see isTempoMetaEvent
  30776. */
  30777. double getTempoMetaEventTickLength (short timeFormat) const noexcept;
  30778. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  30779. @see isTempoMetaEvent, getTempoMetaEventTickLength
  30780. */
  30781. double getTempoSecondsPerQuarterNote() const noexcept;
  30782. /** Creates a tempo meta-event.
  30783. @see isTempoMetaEvent
  30784. */
  30785. static MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) noexcept;
  30786. /** Returns true if this is a 'time-signature' meta-event.
  30787. @see getTimeSignatureInfo
  30788. */
  30789. bool isTimeSignatureMetaEvent() const noexcept;
  30790. /** Returns the time-signature values from a time-signature meta-event.
  30791. @see isTimeSignatureMetaEvent
  30792. */
  30793. void getTimeSignatureInfo (int& numerator, int& denominator) const noexcept;
  30794. /** Creates a time-signature meta-event.
  30795. @see isTimeSignatureMetaEvent
  30796. */
  30797. static MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  30798. /** Returns true if this is a 'key-signature' meta-event.
  30799. @see getKeySignatureNumberOfSharpsOrFlats
  30800. */
  30801. bool isKeySignatureMetaEvent() const noexcept;
  30802. /** Returns the key from a key-signature meta-event.
  30803. @see isKeySignatureMetaEvent
  30804. */
  30805. int getKeySignatureNumberOfSharpsOrFlats() const noexcept;
  30806. /** Returns true if this is a 'channel' meta-event.
  30807. A channel meta-event specifies the midi channel that should be used
  30808. for subsequent meta-events.
  30809. @see getMidiChannelMetaEventChannel
  30810. */
  30811. bool isMidiChannelMetaEvent() const noexcept;
  30812. /** Returns the channel number from a channel meta-event.
  30813. @returns the channel, in the range 1 to 16.
  30814. @see isMidiChannelMetaEvent
  30815. */
  30816. int getMidiChannelMetaEventChannel() const noexcept;
  30817. /** Creates a midi channel meta-event.
  30818. @param channel the midi channel, in the range 1 to 16
  30819. @see isMidiChannelMetaEvent
  30820. */
  30821. static MidiMessage midiChannelMetaEvent (int channel) noexcept;
  30822. /** Returns true if this is an active-sense message. */
  30823. bool isActiveSense() const noexcept;
  30824. /** Returns true if this is a midi start event.
  30825. @see midiStart
  30826. */
  30827. bool isMidiStart() const noexcept;
  30828. /** Creates a midi start event. */
  30829. static MidiMessage midiStart() noexcept;
  30830. /** Returns true if this is a midi continue event.
  30831. @see midiContinue
  30832. */
  30833. bool isMidiContinue() const noexcept;
  30834. /** Creates a midi continue event. */
  30835. static MidiMessage midiContinue() noexcept;
  30836. /** Returns true if this is a midi stop event.
  30837. @see midiStop
  30838. */
  30839. bool isMidiStop() const noexcept;
  30840. /** Creates a midi stop event. */
  30841. static MidiMessage midiStop() noexcept;
  30842. /** Returns true if this is a midi clock event.
  30843. @see midiClock, songPositionPointer
  30844. */
  30845. bool isMidiClock() const noexcept;
  30846. /** Creates a midi clock event. */
  30847. static MidiMessage midiClock() noexcept;
  30848. /** Returns true if this is a song-position-pointer message.
  30849. @see getSongPositionPointerMidiBeat, songPositionPointer
  30850. */
  30851. bool isSongPositionPointer() const noexcept;
  30852. /** Returns the midi beat-number of a song-position-pointer message.
  30853. @see isSongPositionPointer, songPositionPointer
  30854. */
  30855. int getSongPositionPointerMidiBeat() const noexcept;
  30856. /** Creates a song-position-pointer message.
  30857. The position is a number of midi beats from the start of the song, where 1 midi
  30858. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  30859. are 4 midi beats in a quarter-note.
  30860. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  30861. */
  30862. static MidiMessage songPositionPointer (int positionInMidiBeats) noexcept;
  30863. /** Returns true if this is a quarter-frame midi timecode message.
  30864. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  30865. */
  30866. bool isQuarterFrame() const noexcept;
  30867. /** Returns the sequence number of a quarter-frame midi timecode message.
  30868. This will be a value between 0 and 7.
  30869. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  30870. */
  30871. int getQuarterFrameSequenceNumber() const noexcept;
  30872. /** Returns the value from a quarter-frame message.
  30873. This will be the lower nybble of the message's data-byte, a value
  30874. between 0 and 15
  30875. */
  30876. int getQuarterFrameValue() const noexcept;
  30877. /** Creates a quarter-frame MTC message.
  30878. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  30879. @param value a value 0 to 15 for the lower nybble of the message's data byte
  30880. */
  30881. static MidiMessage quarterFrame (int sequenceNumber, int value) noexcept;
  30882. /** SMPTE timecode types.
  30883. Used by the getFullFrameParameters() and fullFrame() methods.
  30884. */
  30885. enum SmpteTimecodeType
  30886. {
  30887. fps24 = 0,
  30888. fps25 = 1,
  30889. fps30drop = 2,
  30890. fps30 = 3
  30891. };
  30892. /** Returns true if this is a full-frame midi timecode message.
  30893. */
  30894. bool isFullFrame() const noexcept;
  30895. /** Extracts the timecode information from a full-frame midi timecode message.
  30896. You should only call this on messages where you've used isFullFrame() to
  30897. check that they're the right kind.
  30898. */
  30899. void getFullFrameParameters (int& hours,
  30900. int& minutes,
  30901. int& seconds,
  30902. int& frames,
  30903. SmpteTimecodeType& timecodeType) const noexcept;
  30904. /** Creates a full-frame MTC message.
  30905. */
  30906. static MidiMessage fullFrame (int hours,
  30907. int minutes,
  30908. int seconds,
  30909. int frames,
  30910. SmpteTimecodeType timecodeType);
  30911. /** Types of MMC command.
  30912. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  30913. */
  30914. enum MidiMachineControlCommand
  30915. {
  30916. mmc_stop = 1,
  30917. mmc_play = 2,
  30918. mmc_deferredplay = 3,
  30919. mmc_fastforward = 4,
  30920. mmc_rewind = 5,
  30921. mmc_recordStart = 6,
  30922. mmc_recordStop = 7,
  30923. mmc_pause = 9
  30924. };
  30925. /** Checks whether this is an MMC message.
  30926. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  30927. */
  30928. bool isMidiMachineControlMessage() const noexcept;
  30929. /** For an MMC message, this returns its type.
  30930. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  30931. calling this method.
  30932. */
  30933. MidiMachineControlCommand getMidiMachineControlCommand() const noexcept;
  30934. /** Creates an MMC message.
  30935. */
  30936. static MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  30937. /** Checks whether this is an MMC "goto" message.
  30938. If it is, the parameters passed-in are set to the time that the message contains.
  30939. @see midiMachineControlGoto
  30940. */
  30941. bool isMidiMachineControlGoto (int& hours,
  30942. int& minutes,
  30943. int& seconds,
  30944. int& frames) const noexcept;
  30945. /** Creates an MMC "goto" message.
  30946. This messages tells the device to go to a specific frame.
  30947. @see isMidiMachineControlGoto
  30948. */
  30949. static MidiMessage midiMachineControlGoto (int hours,
  30950. int minutes,
  30951. int seconds,
  30952. int frames);
  30953. /** Creates a master-volume change message.
  30954. @param volume the volume, 0 to 1.0
  30955. */
  30956. static MidiMessage masterVolume (float volume);
  30957. /** Creates a system-exclusive message.
  30958. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  30959. */
  30960. static MidiMessage createSysExMessage (const uint8* sysexData,
  30961. int dataSize);
  30962. /** Reads a midi variable-length integer.
  30963. @param data the data to read the number from
  30964. @param numBytesUsed on return, this will be set to the number of bytes that were read
  30965. */
  30966. static int readVariableLengthVal (const uint8* data,
  30967. int& numBytesUsed) noexcept;
  30968. /** Based on the first byte of a short midi message, this uses a lookup table
  30969. to return the message length (either 1, 2, or 3 bytes).
  30970. The value passed in must be 0x80 or higher.
  30971. */
  30972. static int getMessageLengthFromFirstByte (const uint8 firstByte) noexcept;
  30973. /** Returns the name of a midi note number.
  30974. E.g "C", "D#", etc.
  30975. @param noteNumber the midi note number, 0 to 127
  30976. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  30977. they'll be flattened, e.g. "Db"
  30978. @param includeOctaveNumber if true, the octave number will be appended to the string,
  30979. e.g. "C#4"
  30980. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  30981. number that will be used for middle C's octave
  30982. @see getMidiNoteInHertz
  30983. */
  30984. static String getMidiNoteName (int noteNumber,
  30985. bool useSharps,
  30986. bool includeOctaveNumber,
  30987. int octaveNumForMiddleC);
  30988. /** Returns the frequency of a midi note number.
  30989. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  30990. @see getMidiNoteName
  30991. */
  30992. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) noexcept;
  30993. /** Returns the standard name of a GM instrument.
  30994. @param midiInstrumentNumber the program number 0 to 127
  30995. @see getProgramChangeNumber
  30996. */
  30997. static String getGMInstrumentName (int midiInstrumentNumber);
  30998. /** Returns the name of a bank of GM instruments.
  30999. @param midiBankNumber the bank, 0 to 15
  31000. */
  31001. static String getGMInstrumentBankName (int midiBankNumber);
  31002. /** Returns the standard name of a channel 10 percussion sound.
  31003. @param midiNoteNumber the key number, 35 to 81
  31004. */
  31005. static String getRhythmInstrumentName (int midiNoteNumber);
  31006. /** Returns the name of a controller type number.
  31007. @see getControllerNumber
  31008. */
  31009. static String getControllerName (int controllerNumber);
  31010. private:
  31011. double timeStamp;
  31012. uint8* data;
  31013. int size;
  31014. #ifndef DOXYGEN
  31015. union
  31016. {
  31017. uint8 asBytes[4];
  31018. uint32 asInt32;
  31019. } preallocatedData;
  31020. #endif
  31021. };
  31022. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  31023. /*** End of inlined file: juce_MidiMessage.h ***/
  31024. class MidiInput;
  31025. /**
  31026. Receives incoming messages from a physical MIDI input device.
  31027. This class is overridden to handle incoming midi messages. See the MidiInput
  31028. class for more details.
  31029. @see MidiInput
  31030. */
  31031. class JUCE_API MidiInputCallback
  31032. {
  31033. public:
  31034. /** Destructor. */
  31035. virtual ~MidiInputCallback() {}
  31036. /** Receives an incoming message.
  31037. A MidiInput object will call this method when a midi event arrives. It'll be
  31038. called on a high-priority system thread, so avoid doing anything time-consuming
  31039. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  31040. for queueing incoming messages for use later.
  31041. @param source the MidiInput object that generated the message
  31042. @param message the incoming message. The message's timestamp is set to a value
  31043. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  31044. time when the message arrived.
  31045. */
  31046. virtual void handleIncomingMidiMessage (MidiInput* source,
  31047. const MidiMessage& message) = 0;
  31048. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  31049. If a long sysex message is broken up into multiple packets, this callback is made
  31050. for each packet that arrives until the message is finished, at which point
  31051. the normal handleIncomingMidiMessage() callback will be made with the entire
  31052. message.
  31053. The message passed in will contain the start of a sysex, but won't be finished
  31054. with the terminating 0xf7 byte.
  31055. */
  31056. virtual void handlePartialSysexMessage (MidiInput* source,
  31057. const uint8* messageData,
  31058. const int numBytesSoFar,
  31059. const double timestamp)
  31060. {
  31061. // (this bit is just to avoid compiler warnings about unused variables)
  31062. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  31063. }
  31064. };
  31065. /**
  31066. Represents a midi input device.
  31067. To create one of these, use the static getDevices() method to find out what inputs are
  31068. available, and then use the openDevice() method to try to open one.
  31069. @see MidiOutput
  31070. */
  31071. class JUCE_API MidiInput
  31072. {
  31073. public:
  31074. /** Returns a list of the available midi input devices.
  31075. You can open one of the devices by passing its index into the
  31076. openDevice() method.
  31077. @see getDefaultDeviceIndex, openDevice
  31078. */
  31079. static const StringArray getDevices();
  31080. /** Returns the index of the default midi input device to use.
  31081. This refers to the index in the list returned by getDevices().
  31082. */
  31083. static int getDefaultDeviceIndex();
  31084. /** Tries to open one of the midi input devices.
  31085. This will return a MidiInput object if it manages to open it. You can then
  31086. call start() and stop() on this device, and delete it when no longer needed.
  31087. If the device can't be opened, this will return a null pointer.
  31088. @param deviceIndex the index of a device from the list returned by getDevices()
  31089. @param callback the object that will receive the midi messages from this device.
  31090. @see MidiInputCallback, getDevices
  31091. */
  31092. static MidiInput* openDevice (int deviceIndex,
  31093. MidiInputCallback* callback);
  31094. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  31095. /** This will try to create a new midi input device (Not available on Windows).
  31096. This will attempt to create a new midi input device with the specified name,
  31097. for other apps to connect to.
  31098. Returns 0 if a device can't be created.
  31099. @param deviceName the name to use for the new device
  31100. @param callback the object that will receive the midi messages from this device.
  31101. */
  31102. static MidiInput* createNewDevice (const String& deviceName,
  31103. MidiInputCallback* callback);
  31104. #endif
  31105. /** Destructor. */
  31106. virtual ~MidiInput();
  31107. /** Returns the name of this device.
  31108. */
  31109. virtual const String getName() const noexcept { return name; }
  31110. /** Allows you to set a custom name for the device, in case you don't like the name
  31111. it was given when created.
  31112. */
  31113. virtual void setName (const String& newName) noexcept { name = newName; }
  31114. /** Starts the device running.
  31115. After calling this, the device will start sending midi messages to the
  31116. MidiInputCallback object that was specified when the openDevice() method
  31117. was called.
  31118. @see stop
  31119. */
  31120. virtual void start();
  31121. /** Stops the device running.
  31122. @see start
  31123. */
  31124. virtual void stop();
  31125. protected:
  31126. String name;
  31127. void* internal;
  31128. explicit MidiInput (const String& name);
  31129. private:
  31130. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  31131. };
  31132. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  31133. /*** End of inlined file: juce_MidiInput.h ***/
  31134. /*** Start of inlined file: juce_MidiOutput.h ***/
  31135. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  31136. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  31137. /*** Start of inlined file: juce_MidiBuffer.h ***/
  31138. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  31139. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  31140. /**
  31141. Holds a sequence of time-stamped midi events.
  31142. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  31143. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  31144. @see MidiMessage
  31145. */
  31146. class JUCE_API MidiBuffer
  31147. {
  31148. public:
  31149. /** Creates an empty MidiBuffer. */
  31150. MidiBuffer() noexcept;
  31151. /** Creates a MidiBuffer containing a single midi message. */
  31152. explicit MidiBuffer (const MidiMessage& message) noexcept;
  31153. /** Creates a copy of another MidiBuffer. */
  31154. MidiBuffer (const MidiBuffer& other) noexcept;
  31155. /** Makes a copy of another MidiBuffer. */
  31156. MidiBuffer& operator= (const MidiBuffer& other) noexcept;
  31157. /** Destructor */
  31158. ~MidiBuffer();
  31159. /** Removes all events from the buffer. */
  31160. void clear() noexcept;
  31161. /** Removes all events between two times from the buffer.
  31162. All events for which (start <= event position < start + numSamples) will
  31163. be removed.
  31164. */
  31165. void clear (int start, int numSamples);
  31166. /** Returns true if the buffer is empty.
  31167. To actually retrieve the events, use a MidiBuffer::Iterator object
  31168. */
  31169. bool isEmpty() const noexcept;
  31170. /** Counts the number of events in the buffer.
  31171. This is actually quite a slow operation, as it has to iterate through all
  31172. the events, so you might prefer to call isEmpty() if that's all you need
  31173. to know.
  31174. */
  31175. int getNumEvents() const noexcept;
  31176. /** Adds an event to the buffer.
  31177. The sample number will be used to determine the position of the event in
  31178. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  31179. ignored.
  31180. If an event is added whose sample position is the same as one or more events
  31181. already in the buffer, the new event will be placed after the existing ones.
  31182. To retrieve events, use a MidiBuffer::Iterator object
  31183. */
  31184. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  31185. /** Adds an event to the buffer from raw midi data.
  31186. The sample number will be used to determine the position of the event in
  31187. the buffer, which is always kept sorted.
  31188. If an event is added whose sample position is the same as one or more events
  31189. already in the buffer, the new event will be placed after the existing ones.
  31190. The event data will be inspected to calculate the number of bytes in length that
  31191. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  31192. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  31193. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  31194. add an event at all.
  31195. To retrieve events, use a MidiBuffer::Iterator object
  31196. */
  31197. void addEvent (const void* rawMidiData,
  31198. int maxBytesOfMidiData,
  31199. int sampleNumber);
  31200. /** Adds some events from another buffer to this one.
  31201. @param otherBuffer the buffer containing the events you want to add
  31202. @param startSample the lowest sample number in the source buffer for which
  31203. events should be added. Any source events whose timestamp is
  31204. less than this will be ignored
  31205. @param numSamples the valid range of samples from the source buffer for which
  31206. events should be added - i.e. events in the source buffer whose
  31207. timestamp is greater than or equal to (startSample + numSamples)
  31208. will be ignored. If this value is less than 0, all events after
  31209. startSample will be taken.
  31210. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  31211. that are added to this buffer
  31212. */
  31213. void addEvents (const MidiBuffer& otherBuffer,
  31214. int startSample,
  31215. int numSamples,
  31216. int sampleDeltaToAdd);
  31217. /** Returns the sample number of the first event in the buffer.
  31218. If the buffer's empty, this will just return 0.
  31219. */
  31220. int getFirstEventTime() const noexcept;
  31221. /** Returns the sample number of the last event in the buffer.
  31222. If the buffer's empty, this will just return 0.
  31223. */
  31224. int getLastEventTime() const noexcept;
  31225. /** Exchanges the contents of this buffer with another one.
  31226. This is a quick operation, because no memory allocating or copying is done, it
  31227. just swaps the internal state of the two buffers.
  31228. */
  31229. void swapWith (MidiBuffer& other) noexcept;
  31230. /** Preallocates some memory for the buffer to use.
  31231. This helps to avoid needing to reallocate space when the buffer has messages
  31232. added to it.
  31233. */
  31234. void ensureSize (size_t minimumNumBytes);
  31235. /**
  31236. Used to iterate through the events in a MidiBuffer.
  31237. Note that altering the buffer while an iterator is using it isn't a
  31238. safe operation.
  31239. @see MidiBuffer
  31240. */
  31241. class JUCE_API Iterator
  31242. {
  31243. public:
  31244. /** Creates an Iterator for this MidiBuffer. */
  31245. Iterator (const MidiBuffer& buffer) noexcept;
  31246. /** Destructor. */
  31247. ~Iterator() noexcept;
  31248. /** Repositions the iterator so that the next event retrieved will be the first
  31249. one whose sample position is at greater than or equal to the given position.
  31250. */
  31251. void setNextSamplePosition (int samplePosition) noexcept;
  31252. /** Retrieves a copy of the next event from the buffer.
  31253. @param result on return, this will be the message (the MidiMessage's timestamp
  31254. is not set)
  31255. @param samplePosition on return, this will be the position of the event
  31256. @returns true if an event was found, or false if the iterator has reached
  31257. the end of the buffer
  31258. */
  31259. bool getNextEvent (MidiMessage& result,
  31260. int& samplePosition) noexcept;
  31261. /** Retrieves the next event from the buffer.
  31262. @param midiData on return, this pointer will be set to a block of data containing
  31263. the midi message. Note that to make it fast, this is a pointer
  31264. directly into the MidiBuffer's internal data, so is only valid
  31265. temporarily until the MidiBuffer is altered.
  31266. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  31267. midi message
  31268. @param samplePosition on return, this will be the position of the event
  31269. @returns true if an event was found, or false if the iterator has reached
  31270. the end of the buffer
  31271. */
  31272. bool getNextEvent (const uint8* &midiData,
  31273. int& numBytesOfMidiData,
  31274. int& samplePosition) noexcept;
  31275. private:
  31276. const MidiBuffer& buffer;
  31277. const uint8* data;
  31278. JUCE_DECLARE_NON_COPYABLE (Iterator);
  31279. };
  31280. private:
  31281. friend class MidiBuffer::Iterator;
  31282. MemoryBlock data;
  31283. int bytesUsed;
  31284. uint8* getData() const noexcept;
  31285. uint8* findEventAfter (uint8* d, int samplePosition) const noexcept;
  31286. static int getEventTime (const void* d) noexcept;
  31287. static uint16 getEventDataSize (const void* d) noexcept;
  31288. static uint16 getEventTotalSize (const void* d) noexcept;
  31289. JUCE_LEAK_DETECTOR (MidiBuffer);
  31290. };
  31291. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  31292. /*** End of inlined file: juce_MidiBuffer.h ***/
  31293. /**
  31294. Controls a physical MIDI output device.
  31295. To create one of these, use the static getDevices() method to get a list of the
  31296. available output devices, then use the openDevice() method to try to open one.
  31297. @see MidiInput
  31298. */
  31299. class JUCE_API MidiOutput : private Thread
  31300. {
  31301. public:
  31302. /** Returns a list of the available midi output devices.
  31303. You can open one of the devices by passing its index into the
  31304. openDevice() method.
  31305. @see getDefaultDeviceIndex, openDevice
  31306. */
  31307. static const StringArray getDevices();
  31308. /** Returns the index of the default midi output device to use.
  31309. This refers to the index in the list returned by getDevices().
  31310. */
  31311. static int getDefaultDeviceIndex();
  31312. /** Tries to open one of the midi output devices.
  31313. This will return a MidiOutput object if it manages to open it. You can then
  31314. send messages to this device, and delete it when no longer needed.
  31315. If the device can't be opened, this will return a null pointer.
  31316. @param deviceIndex the index of a device from the list returned by getDevices()
  31317. @see getDevices
  31318. */
  31319. static MidiOutput* openDevice (int deviceIndex);
  31320. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  31321. /** This will try to create a new midi output device (Not available on Windows).
  31322. This will attempt to create a new midi output device that other apps can connect
  31323. to and use as their midi input.
  31324. Returns 0 if a device can't be created.
  31325. @param deviceName the name to use for the new device
  31326. */
  31327. static MidiOutput* createNewDevice (const String& deviceName);
  31328. #endif
  31329. /** Destructor. */
  31330. virtual ~MidiOutput();
  31331. /** Makes this device output a midi message.
  31332. @see MidiMessage
  31333. */
  31334. virtual void sendMessageNow (const MidiMessage& message);
  31335. /** This lets you supply a block of messages that will be sent out at some point
  31336. in the future.
  31337. The MidiOutput class has an internal thread that can send out timestamped
  31338. messages - this appends a set of messages to its internal buffer, ready for
  31339. sending.
  31340. This will only work if you've already started the thread with startBackgroundThread().
  31341. A time is supplied, at which the block of messages should be sent. This time uses
  31342. the same time base as Time::getMillisecondCounter(), and must be in the future.
  31343. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  31344. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  31345. samplesPerSecondForBuffer value is needed to convert this sample position to a
  31346. real time.
  31347. */
  31348. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  31349. double millisecondCounterToStartAt,
  31350. double samplesPerSecondForBuffer);
  31351. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  31352. */
  31353. virtual void clearAllPendingMessages();
  31354. /** Starts up a background thread so that the device can send blocks of data.
  31355. Call this to get the device ready, before using sendBlockOfMessages().
  31356. */
  31357. virtual void startBackgroundThread();
  31358. /** Stops the background thread, and clears any pending midi events.
  31359. @see startBackgroundThread
  31360. */
  31361. virtual void stopBackgroundThread();
  31362. protected:
  31363. void* internal;
  31364. struct PendingMessage
  31365. {
  31366. PendingMessage (const void* data, int len, double timeStamp);
  31367. MidiMessage message;
  31368. PendingMessage* next;
  31369. };
  31370. CriticalSection lock;
  31371. PendingMessage* firstMessage;
  31372. MidiOutput();
  31373. void run();
  31374. private:
  31375. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  31376. };
  31377. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  31378. /*** End of inlined file: juce_MidiOutput.h ***/
  31379. /**
  31380. Manages the state of some audio and midi i/o devices.
  31381. This class keeps tracks of a currently-selected audio device, through
  31382. with which it continuously streams data from an audio callback, as well as
  31383. one or more midi inputs.
  31384. The idea is that your application will create one global instance of this object,
  31385. and let it take care of creating and deleting specific types of audio devices
  31386. internally. So when the device is changed, your callbacks will just keep running
  31387. without having to worry about this.
  31388. The manager can save and reload all of its device settings as XML, which
  31389. makes it very easy for you to save and reload the audio setup of your
  31390. application.
  31391. And to make it easy to let the user change its settings, there's a component
  31392. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  31393. device selection/sample-rate/latency controls.
  31394. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  31395. call addAudioCallback() to register your audio callback with it, and use that to process
  31396. your audio data.
  31397. The manager also acts as a handy hub for incoming midi messages, allowing a
  31398. listener to register for messages from either a specific midi device, or from whatever
  31399. the current default midi input device is. The listener then doesn't have to worry about
  31400. re-registering with different midi devices if they are changed or deleted.
  31401. And yet another neat trick is that amount of CPU time being used is measured and
  31402. available with the getCpuUsage() method.
  31403. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  31404. listeners whenever one of its settings is changed.
  31405. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  31406. */
  31407. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  31408. {
  31409. public:
  31410. /** Creates a default AudioDeviceManager.
  31411. Initially no audio device will be selected. You should call the initialise() method
  31412. and register an audio callback with setAudioCallback() before it'll be able to
  31413. actually make any noise.
  31414. */
  31415. AudioDeviceManager();
  31416. /** Destructor. */
  31417. ~AudioDeviceManager();
  31418. /**
  31419. This structure holds a set of properties describing the current audio setup.
  31420. An AudioDeviceManager uses this class to save/load its current settings, and to
  31421. specify your preferred options when opening a device.
  31422. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  31423. */
  31424. struct JUCE_API AudioDeviceSetup
  31425. {
  31426. /** Creates an AudioDeviceSetup object.
  31427. The default constructor sets all the member variables to indicate default values.
  31428. You can then fill-in any values you want to before passing the object to
  31429. AudioDeviceManager::initialise().
  31430. */
  31431. AudioDeviceSetup();
  31432. bool operator== (const AudioDeviceSetup& other) const;
  31433. /** The name of the audio device used for output.
  31434. The name has to be one of the ones listed by the AudioDeviceManager's currently
  31435. selected device type.
  31436. This may be the same as the input device.
  31437. An empty string indicates the default device.
  31438. */
  31439. String outputDeviceName;
  31440. /** The name of the audio device used for input.
  31441. This may be the same as the output device.
  31442. An empty string indicates the default device.
  31443. */
  31444. String inputDeviceName;
  31445. /** The current sample rate.
  31446. This rate is used for both the input and output devices.
  31447. A value of 0 indicates the default rate.
  31448. */
  31449. double sampleRate;
  31450. /** The buffer size, in samples.
  31451. This buffer size is used for both the input and output devices.
  31452. A value of 0 indicates the default buffer size.
  31453. */
  31454. int bufferSize;
  31455. /** The set of active input channels.
  31456. The bits that are set in this array indicate the channels of the
  31457. input device that are active.
  31458. If useDefaultInputChannels is true, this value is ignored.
  31459. */
  31460. BigInteger inputChannels;
  31461. /** If this is true, it indicates that the inputChannels array
  31462. should be ignored, and instead, the device's default channels
  31463. should be used.
  31464. */
  31465. bool useDefaultInputChannels;
  31466. /** The set of active output channels.
  31467. The bits that are set in this array indicate the channels of the
  31468. input device that are active.
  31469. If useDefaultOutputChannels is true, this value is ignored.
  31470. */
  31471. BigInteger outputChannels;
  31472. /** If this is true, it indicates that the outputChannels array
  31473. should be ignored, and instead, the device's default channels
  31474. should be used.
  31475. */
  31476. bool useDefaultOutputChannels;
  31477. };
  31478. /** Opens a set of audio devices ready for use.
  31479. This will attempt to open either a default audio device, or one that was
  31480. previously saved as XML.
  31481. @param numInputChannelsNeeded a minimum number of input channels needed
  31482. by your app.
  31483. @param numOutputChannelsNeeded a minimum number of output channels to open
  31484. @param savedState either a previously-saved state that was produced
  31485. by createStateXml(), or 0 if you want the manager
  31486. to choose the best device to open.
  31487. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  31488. fails to open, then a default device will be used
  31489. instead. If false, then on failure, no device is
  31490. opened.
  31491. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  31492. name, then that will be used as the default device
  31493. (assuming that there wasn't one specified in the XML).
  31494. The string can actually be a simple wildcard, containing "*"
  31495. and "?" characters
  31496. @param preferredSetupOptions if this is non-null, the structure will be used as the
  31497. set of preferred settings when opening the device. If you
  31498. use this parameter, the preferredDefaultDeviceName
  31499. field will be ignored
  31500. @returns an error message if anything went wrong, or an empty string if it worked ok.
  31501. */
  31502. const String initialise (int numInputChannelsNeeded,
  31503. int numOutputChannelsNeeded,
  31504. const XmlElement* savedState,
  31505. bool selectDefaultDeviceOnFailure,
  31506. const String& preferredDefaultDeviceName = String::empty,
  31507. const AudioDeviceSetup* preferredSetupOptions = 0);
  31508. /** Returns some XML representing the current state of the manager.
  31509. This stores the current device, its samplerate, block size, etc, and
  31510. can be restored later with initialise().
  31511. Note that this can return a null pointer if no settings have been explicitly changed
  31512. (i.e. if the device manager has just been left in its default state).
  31513. */
  31514. XmlElement* createStateXml() const;
  31515. /** Returns the current device properties that are in use.
  31516. @see setAudioDeviceSetup
  31517. */
  31518. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  31519. /** Changes the current device or its settings.
  31520. If you want to change a device property, like the current sample rate or
  31521. block size, you can call getAudioDeviceSetup() to retrieve the current
  31522. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  31523. and pass it back into this method to apply the new settings.
  31524. @param newSetup the settings that you'd like to use
  31525. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  31526. settings will be taken as having been explicitly chosen by the
  31527. user, and the next time createStateXml() is called, these settings
  31528. will be returned. If it's false, then the device is treated as a
  31529. temporary or default device, and a call to createStateXml() will
  31530. return either the last settings that were made with treatAsChosenDevice
  31531. as true, or the last XML settings that were passed into initialise().
  31532. @returns an error message if anything went wrong, or an empty string if it worked ok.
  31533. @see getAudioDeviceSetup
  31534. */
  31535. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  31536. bool treatAsChosenDevice);
  31537. /** Returns the currently-active audio device. */
  31538. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  31539. /** Returns the type of audio device currently in use.
  31540. @see setCurrentAudioDeviceType
  31541. */
  31542. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  31543. /** Returns the currently active audio device type object.
  31544. Don't keep a copy of this pointer - it's owned by the device manager and could
  31545. change at any time.
  31546. */
  31547. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  31548. /** Changes the class of audio device being used.
  31549. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  31550. this because there's only one type: CoreAudio.
  31551. For a list of types, see getAvailableDeviceTypes().
  31552. */
  31553. void setCurrentAudioDeviceType (const String& type,
  31554. bool treatAsChosenDevice);
  31555. /** Closes the currently-open device.
  31556. You can call restartLastAudioDevice() later to reopen it in the same state
  31557. that it was just in.
  31558. */
  31559. void closeAudioDevice();
  31560. /** Tries to reload the last audio device that was running.
  31561. Note that this only reloads the last device that was running before
  31562. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  31563. and can only be called after a device has been opened with SetAudioDevice().
  31564. If a device is already open, this call will do nothing.
  31565. */
  31566. void restartLastAudioDevice();
  31567. /** Registers an audio callback to be used.
  31568. The manager will redirect callbacks from whatever audio device is currently
  31569. in use to all registered callback objects. If more than one callback is
  31570. active, they will all be given the same input data, and their outputs will
  31571. be summed.
  31572. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  31573. object before returning.
  31574. To remove a callback, use removeAudioCallback().
  31575. */
  31576. void addAudioCallback (AudioIODeviceCallback* newCallback);
  31577. /** Deregisters a previously added callback.
  31578. If necessary, this method will invoke audioDeviceStopped() on the callback
  31579. object before returning.
  31580. @see addAudioCallback
  31581. */
  31582. void removeAudioCallback (AudioIODeviceCallback* callback);
  31583. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  31584. Returns a value between 0 and 1.0
  31585. */
  31586. double getCpuUsage() const;
  31587. /** Enables or disables a midi input device.
  31588. The list of devices can be obtained with the MidiInput::getDevices() method.
  31589. Any incoming messages from enabled input devices will be forwarded on to all the
  31590. listeners that have been registered with the addMidiInputCallback() method. They
  31591. can either register for messages from a particular device, or from just the
  31592. "default" midi input.
  31593. Routing the midi input via an AudioDeviceManager means that when a listener
  31594. registers for the default midi input, this default device can be changed by the
  31595. manager without the listeners having to know about it or re-register.
  31596. It also means that a listener can stay registered for a midi input that is disabled
  31597. or not present, so that when the input is re-enabled, the listener will start
  31598. receiving messages again.
  31599. @see addMidiInputCallback, isMidiInputEnabled
  31600. */
  31601. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  31602. /** Returns true if a given midi input device is being used.
  31603. @see setMidiInputEnabled
  31604. */
  31605. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  31606. /** Registers a listener for callbacks when midi events arrive from a midi input.
  31607. The device name can be empty to indicate that it wants events from whatever the
  31608. current "default" device is. Or it can be the name of one of the midi input devices
  31609. (see MidiInput::getDevices() for the names).
  31610. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  31611. events forwarded on to listeners.
  31612. */
  31613. void addMidiInputCallback (const String& midiInputDeviceName,
  31614. MidiInputCallback* callback);
  31615. /** Removes a listener that was previously registered with addMidiInputCallback().
  31616. */
  31617. void removeMidiInputCallback (const String& midiInputDeviceName,
  31618. MidiInputCallback* callback);
  31619. /** Sets a midi output device to use as the default.
  31620. The list of devices can be obtained with the MidiOutput::getDevices() method.
  31621. The specified device will be opened automatically and can be retrieved with the
  31622. getDefaultMidiOutput() method.
  31623. Pass in an empty string to deselect all devices. For the default device, you
  31624. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  31625. @see getDefaultMidiOutput, getDefaultMidiOutputName
  31626. */
  31627. void setDefaultMidiOutput (const String& deviceName);
  31628. /** Returns the name of the default midi output.
  31629. @see setDefaultMidiOutput, getDefaultMidiOutput
  31630. */
  31631. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  31632. /** Returns the current default midi output device.
  31633. If no device has been selected, or the device can't be opened, this will
  31634. return 0.
  31635. @see getDefaultMidiOutputName
  31636. */
  31637. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  31638. /** Returns a list of the types of device supported.
  31639. */
  31640. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  31641. /** Creates a list of available types.
  31642. This will add a set of new AudioIODeviceType objects to the specified list, to
  31643. represent each available types of device.
  31644. You can override this if your app needs to do something specific, like avoid
  31645. using DirectSound devices, etc.
  31646. */
  31647. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  31648. /** Plays a beep through the current audio device.
  31649. This is here to allow the audio setup UI panels to easily include a "test"
  31650. button so that the user can check where the audio is coming from.
  31651. */
  31652. void playTestSound();
  31653. /** Turns on level-measuring.
  31654. When enabled, the device manager will measure the peak input level
  31655. across all channels, and you can get this level by calling getCurrentInputLevel().
  31656. This is mainly intended for audio setup UI panels to use to create a mic
  31657. level display, so that the user can check that they've selected the right
  31658. device.
  31659. A simple filter is used to make the level decay smoothly, but this is
  31660. only intended for giving rough feedback, and not for any kind of accurate
  31661. measurement.
  31662. */
  31663. void enableInputLevelMeasurement (bool enableMeasurement);
  31664. /** Returns the current input level.
  31665. To use this, you must first enable it by calling enableInputLevelMeasurement().
  31666. See enableInputLevelMeasurement() for more info.
  31667. */
  31668. double getCurrentInputLevel() const;
  31669. /** Returns the a lock that can be used to synchronise access to the audio callback.
  31670. Obviously while this is locked, you're blocking the audio thread from running, so
  31671. it must only be used for very brief periods when absolutely necessary.
  31672. */
  31673. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  31674. /** Returns the a lock that can be used to synchronise access to the midi callback.
  31675. Obviously while this is locked, you're blocking the midi system from running, so
  31676. it must only be used for very brief periods when absolutely necessary.
  31677. */
  31678. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  31679. private:
  31680. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  31681. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  31682. AudioDeviceSetup currentSetup;
  31683. ScopedPointer <AudioIODevice> currentAudioDevice;
  31684. Array <AudioIODeviceCallback*> callbacks;
  31685. int numInputChansNeeded, numOutputChansNeeded;
  31686. String currentDeviceType;
  31687. BigInteger inputChannels, outputChannels;
  31688. ScopedPointer <XmlElement> lastExplicitSettings;
  31689. mutable bool listNeedsScanning;
  31690. bool useInputNames;
  31691. int inputLevelMeasurementEnabledCount;
  31692. double inputLevel;
  31693. ScopedPointer <AudioSampleBuffer> testSound;
  31694. int testSoundPosition;
  31695. AudioSampleBuffer tempBuffer;
  31696. StringArray midiInsFromXml;
  31697. OwnedArray <MidiInput> enabledMidiInputs;
  31698. Array <MidiInputCallback*> midiCallbacks;
  31699. StringArray midiCallbackDevices;
  31700. String defaultMidiOutputName;
  31701. ScopedPointer <MidiOutput> defaultMidiOutput;
  31702. CriticalSection audioCallbackLock, midiCallbackLock;
  31703. double cpuUsageMs, timeToCpuScale;
  31704. class CallbackHandler : public AudioIODeviceCallback,
  31705. public MidiInputCallback
  31706. {
  31707. public:
  31708. void audioDeviceIOCallback (const float**, int, float**, int, int);
  31709. void audioDeviceAboutToStart (AudioIODevice*);
  31710. void audioDeviceStopped();
  31711. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  31712. AudioDeviceManager* owner;
  31713. };
  31714. CallbackHandler callbackHandler;
  31715. friend class CallbackHandler;
  31716. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  31717. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  31718. void audioDeviceAboutToStartInt (AudioIODevice*);
  31719. void audioDeviceStoppedInt();
  31720. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  31721. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  31722. const BigInteger& ins, const BigInteger& outs);
  31723. void stopDevice();
  31724. void updateXml();
  31725. void createDeviceTypesIfNeeded();
  31726. void scanDevicesIfNeeded();
  31727. void deleteCurrentDevice();
  31728. double chooseBestSampleRate (double preferred) const;
  31729. int chooseBestBufferSize (int preferred) const;
  31730. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  31731. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  31732. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  31733. };
  31734. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  31735. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  31736. #endif
  31737. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  31738. #endif
  31739. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  31740. #endif
  31741. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  31742. #endif
  31743. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  31744. #endif
  31745. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  31746. /*** Start of inlined file: juce_Decibels.h ***/
  31747. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  31748. #define __JUCE_DECIBELS_JUCEHEADER__
  31749. /**
  31750. This class contains some helpful static methods for dealing with decibel values.
  31751. */
  31752. class Decibels
  31753. {
  31754. public:
  31755. /** Converts a dBFS value to its equivalent gain level.
  31756. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  31757. decibel value lower than minusInfinityDb will return a gain of 0.
  31758. */
  31759. template <typename Type>
  31760. static Type decibelsToGain (const Type decibels,
  31761. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31762. {
  31763. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  31764. : Type();
  31765. }
  31766. /** Converts a gain level into a dBFS value.
  31767. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  31768. If the gain is 0 (or negative), then the method will return the value
  31769. provided as minusInfinityDb.
  31770. */
  31771. template <typename Type>
  31772. static Type gainToDecibels (const Type gain,
  31773. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31774. {
  31775. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  31776. : minusInfinityDb;
  31777. }
  31778. /** Converts a decibel reading to a string, with the 'dB' suffix.
  31779. If the decibel value is lower than minusInfinityDb, the return value will
  31780. be "-INF dB".
  31781. */
  31782. template <typename Type>
  31783. static const String toString (const Type decibels,
  31784. const int decimalPlaces = 2,
  31785. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31786. {
  31787. String s;
  31788. if (decibels <= minusInfinityDb)
  31789. {
  31790. s = "-INF dB";
  31791. }
  31792. else
  31793. {
  31794. if (decibels >= Type())
  31795. s << '+';
  31796. s << String (decibels, decimalPlaces) << " dB";
  31797. }
  31798. return s;
  31799. }
  31800. private:
  31801. enum
  31802. {
  31803. defaultMinusInfinitydB = -100
  31804. };
  31805. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  31806. JUCE_DECLARE_NON_COPYABLE (Decibels);
  31807. };
  31808. #endif // __JUCE_DECIBELS_JUCEHEADER__
  31809. /*** End of inlined file: juce_Decibels.h ***/
  31810. #endif
  31811. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  31812. #endif
  31813. #ifndef __JUCE_REVERB_JUCEHEADER__
  31814. #endif
  31815. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  31816. #endif
  31817. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  31818. /*** Start of inlined file: juce_MidiFile.h ***/
  31819. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  31820. #define __JUCE_MIDIFILE_JUCEHEADER__
  31821. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  31822. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31823. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31824. /**
  31825. A sequence of timestamped midi messages.
  31826. This allows the sequence to be manipulated, and also to be read from and
  31827. written to a standard midi file.
  31828. @see MidiMessage, MidiFile
  31829. */
  31830. class JUCE_API MidiMessageSequence
  31831. {
  31832. public:
  31833. /** Creates an empty midi sequence object. */
  31834. MidiMessageSequence();
  31835. /** Creates a copy of another sequence. */
  31836. MidiMessageSequence (const MidiMessageSequence& other);
  31837. /** Replaces this sequence with another one. */
  31838. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  31839. /** Destructor. */
  31840. ~MidiMessageSequence();
  31841. /** Structure used to hold midi events in the sequence.
  31842. These structures act as 'handles' on the events as they are moved about in
  31843. the list, and make it quick to find the matching note-offs for note-on events.
  31844. @see MidiMessageSequence::getEventPointer
  31845. */
  31846. class MidiEventHolder
  31847. {
  31848. public:
  31849. /** Destructor. */
  31850. ~MidiEventHolder();
  31851. /** The message itself, whose timestamp is used to specify the event's time.
  31852. */
  31853. MidiMessage message;
  31854. /** The matching note-off event (if this is a note-on event).
  31855. If this isn't a note-on, this pointer will be null.
  31856. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  31857. note-offs up-to-date after events have been moved around in the sequence
  31858. or deleted.
  31859. */
  31860. MidiEventHolder* noteOffObject;
  31861. private:
  31862. friend class MidiMessageSequence;
  31863. MidiEventHolder (const MidiMessage& message);
  31864. JUCE_LEAK_DETECTOR (MidiEventHolder);
  31865. };
  31866. /** Clears the sequence. */
  31867. void clear();
  31868. /** Returns the number of events in the sequence. */
  31869. int getNumEvents() const;
  31870. /** Returns a pointer to one of the events. */
  31871. MidiEventHolder* getEventPointer (int index) const;
  31872. /** Returns the time of the note-up that matches the note-on at this index.
  31873. If the event at this index isn't a note-on, it'll just return 0.
  31874. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  31875. */
  31876. double getTimeOfMatchingKeyUp (int index) const;
  31877. /** Returns the index of the note-up that matches the note-on at this index.
  31878. If the event at this index isn't a note-on, it'll just return -1.
  31879. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  31880. */
  31881. int getIndexOfMatchingKeyUp (int index) const;
  31882. /** Returns the index of an event. */
  31883. int getIndexOf (MidiEventHolder* event) const;
  31884. /** Returns the index of the first event on or after the given timestamp.
  31885. If the time is beyond the end of the sequence, this will return the
  31886. number of events.
  31887. */
  31888. int getNextIndexAtTime (double timeStamp) const;
  31889. /** Returns the timestamp of the first event in the sequence.
  31890. @see getEndTime
  31891. */
  31892. double getStartTime() const;
  31893. /** Returns the timestamp of the last event in the sequence.
  31894. @see getStartTime
  31895. */
  31896. double getEndTime() const;
  31897. /** Returns the timestamp of the event at a given index.
  31898. If the index is out-of-range, this will return 0.0
  31899. */
  31900. double getEventTime (int index) const;
  31901. /** Inserts a midi message into the sequence.
  31902. The index at which the new message gets inserted will depend on its timestamp,
  31903. because the sequence is kept sorted.
  31904. Remember to call updateMatchedPairs() after adding note-on events.
  31905. @param newMessage the new message to add (an internal copy will be made)
  31906. @param timeAdjustment an optional value to add to the timestamp of the message
  31907. that will be inserted
  31908. @see updateMatchedPairs
  31909. */
  31910. void addEvent (const MidiMessage& newMessage,
  31911. double timeAdjustment = 0);
  31912. /** Deletes one of the events in the sequence.
  31913. Remember to call updateMatchedPairs() after removing events.
  31914. @param index the index of the event to delete
  31915. @param deleteMatchingNoteUp whether to also remove the matching note-off
  31916. if the event you're removing is a note-on
  31917. */
  31918. void deleteEvent (int index, bool deleteMatchingNoteUp);
  31919. /** Merges another sequence into this one.
  31920. Remember to call updateMatchedPairs() after using this method.
  31921. @param other the sequence to add from
  31922. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  31923. as they are read from the other sequence
  31924. @param firstAllowableDestTime events will not be added if their time is earlier
  31925. than this time. (This is after their time has been adjusted
  31926. by the timeAdjustmentDelta)
  31927. @param endOfAllowableDestTimes events will not be added if their time is equal to
  31928. or greater than this time. (This is after their time has
  31929. been adjusted by the timeAdjustmentDelta)
  31930. */
  31931. void addSequence (const MidiMessageSequence& other,
  31932. double timeAdjustmentDelta,
  31933. double firstAllowableDestTime,
  31934. double endOfAllowableDestTimes);
  31935. /** Makes sure all the note-on and note-off pairs are up-to-date.
  31936. Call this after moving messages about or deleting/adding messages, and it
  31937. will scan the list and make sure all the note-offs in the MidiEventHolder
  31938. structures are pointing at the correct ones.
  31939. */
  31940. void updateMatchedPairs();
  31941. /** Copies all the messages for a particular midi channel to another sequence.
  31942. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  31943. @param destSequence the sequence that the chosen events should be copied to
  31944. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  31945. channel) will also be copied across.
  31946. @see extractSysExMessages
  31947. */
  31948. void extractMidiChannelMessages (int channelNumberToExtract,
  31949. MidiMessageSequence& destSequence,
  31950. bool alsoIncludeMetaEvents) const;
  31951. /** Copies all midi sys-ex messages to another sequence.
  31952. @param destSequence this is the sequence to which any sys-exes in this sequence
  31953. will be added
  31954. @see extractMidiChannelMessages
  31955. */
  31956. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  31957. /** Removes any messages in this sequence that have a specific midi channel.
  31958. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  31959. */
  31960. void deleteMidiChannelMessages (int channelNumberToRemove);
  31961. /** Removes any sys-ex messages from this sequence.
  31962. */
  31963. void deleteSysExMessages();
  31964. /** Adds an offset to the timestamps of all events in the sequence.
  31965. @param deltaTime the amount to add to each timestamp.
  31966. */
  31967. void addTimeToMessages (double deltaTime);
  31968. /** Scans through the sequence to determine the state of any midi controllers at
  31969. a given time.
  31970. This will create a sequence of midi controller changes that can be
  31971. used to set all midi controllers to the state they would be in at the
  31972. specified time within this sequence.
  31973. As well as controllers, it will also recreate the midi program number
  31974. and pitch bend position.
  31975. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  31976. for other channels will be ignored.
  31977. @param time the time at which you want to find out the state - there are
  31978. no explicit units for this time measurement, it's the same units
  31979. as used for the timestamps of the messages
  31980. @param resultMessages an array to which midi controller-change messages will be added. This
  31981. will be the minimum number of controller changes to recreate the
  31982. state at the required time.
  31983. */
  31984. void createControllerUpdatesForTime (int channelNumber, double time,
  31985. OwnedArray<MidiMessage>& resultMessages);
  31986. /** Swaps this sequence with another one. */
  31987. void swapWith (MidiMessageSequence& other) noexcept;
  31988. /** @internal */
  31989. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  31990. const MidiMessageSequence::MidiEventHolder* second) noexcept;
  31991. private:
  31992. friend class MidiFile;
  31993. OwnedArray <MidiEventHolder> list;
  31994. void sort();
  31995. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  31996. };
  31997. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31998. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  31999. /**
  32000. Reads/writes standard midi format files.
  32001. To read a midi file, create a MidiFile object and call its readFrom() method. You
  32002. can then get the individual midi tracks from it using the getTrack() method.
  32003. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  32004. to it using the addTrack() method, and then call its writeTo() method to stream
  32005. it out.
  32006. @see MidiMessageSequence
  32007. */
  32008. class JUCE_API MidiFile
  32009. {
  32010. public:
  32011. /** Creates an empty MidiFile object.
  32012. */
  32013. MidiFile();
  32014. /** Destructor. */
  32015. ~MidiFile();
  32016. /** Returns the number of tracks in the file.
  32017. @see getTrack, addTrack
  32018. */
  32019. int getNumTracks() const noexcept;
  32020. /** Returns a pointer to one of the tracks in the file.
  32021. @returns a pointer to the track, or 0 if the index is out-of-range
  32022. @see getNumTracks, addTrack
  32023. */
  32024. const MidiMessageSequence* getTrack (int index) const noexcept;
  32025. /** Adds a midi track to the file.
  32026. This will make its own internal copy of the sequence that is passed-in.
  32027. @see getNumTracks, getTrack
  32028. */
  32029. void addTrack (const MidiMessageSequence& trackSequence);
  32030. /** Removes all midi tracks from the file.
  32031. @see getNumTracks
  32032. */
  32033. void clear();
  32034. /** Returns the raw time format code that will be written to a stream.
  32035. After reading a midi file, this method will return the time-format that
  32036. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  32037. or setSmpteTimeFormat() methods.
  32038. If the value returned is positive, it indicates the number of midi ticks
  32039. per quarter-note - see setTicksPerQuarterNote().
  32040. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  32041. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  32042. */
  32043. short getTimeFormat() const noexcept;
  32044. /** Sets the time format to use when this file is written to a stream.
  32045. If this is called, the file will be written as bars/beats using the
  32046. specified resolution, rather than SMPTE absolute times, as would be
  32047. used if setSmpteTimeFormat() had been called instead.
  32048. @param ticksPerQuarterNote e.g. 96, 960
  32049. @see setSmpteTimeFormat
  32050. */
  32051. void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;
  32052. /** Sets the time format to use when this file is written to a stream.
  32053. If this is called, the file will be written using absolute times, rather
  32054. than bars/beats as would be the case if setTicksPerBeat() had been called
  32055. instead.
  32056. @param framesPerSecond must be 24, 25, 29 or 30
  32057. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  32058. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  32059. timing, setSmpteTimeFormat (25, 40)
  32060. @see setTicksPerBeat
  32061. */
  32062. void setSmpteTimeFormat (int framesPerSecond,
  32063. int subframeResolution) noexcept;
  32064. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  32065. Useful for finding the positions of all the tempo changes in a file.
  32066. @param tempoChangeEvents a list to which all the events will be added
  32067. */
  32068. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  32069. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  32070. Useful for finding the positions of all the tempo changes in a file.
  32071. @param timeSigEvents a list to which all the events will be added
  32072. */
  32073. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  32074. /** Returns the latest timestamp in any of the tracks.
  32075. (Useful for finding the length of the file).
  32076. */
  32077. double getLastTimestamp() const;
  32078. /** Reads a midi file format stream.
  32079. After calling this, you can get the tracks that were read from the file by using the
  32080. getNumTracks() and getTrack() methods.
  32081. The timestamps of the midi events in the tracks will represent their positions in
  32082. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  32083. method.
  32084. @returns true if the stream was read successfully
  32085. */
  32086. bool readFrom (InputStream& sourceStream);
  32087. /** Writes the midi tracks as a standard midi file.
  32088. @returns true if the operation succeeded.
  32089. */
  32090. bool writeTo (OutputStream& destStream);
  32091. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  32092. This will use the midi time format and tempo/time signature info in the
  32093. tracks to convert all the timestamps to absolute values in seconds.
  32094. */
  32095. void convertTimestampTicksToSeconds();
  32096. private:
  32097. OwnedArray <MidiMessageSequence> tracks;
  32098. short timeFormat;
  32099. void readNextTrack (const uint8* data, int size);
  32100. void writeTrack (OutputStream& mainOut, int trackNum);
  32101. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  32102. };
  32103. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  32104. /*** End of inlined file: juce_MidiFile.h ***/
  32105. #endif
  32106. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  32107. #endif
  32108. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32109. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  32110. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32111. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32112. class MidiKeyboardState;
  32113. /**
  32114. Receives events from a MidiKeyboardState object.
  32115. @see MidiKeyboardState
  32116. */
  32117. class JUCE_API MidiKeyboardStateListener
  32118. {
  32119. public:
  32120. MidiKeyboardStateListener() noexcept {}
  32121. virtual ~MidiKeyboardStateListener() {}
  32122. /** Called when one of the MidiKeyboardState's keys is pressed.
  32123. This will be called synchronously when the state is either processing a
  32124. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32125. when a note is being played with its MidiKeyboardState::noteOn() method.
  32126. Note that this callback could happen from an audio callback thread, so be
  32127. careful not to block, and avoid any UI activity in the callback.
  32128. */
  32129. virtual void handleNoteOn (MidiKeyboardState* source,
  32130. int midiChannel, int midiNoteNumber, float velocity) = 0;
  32131. /** Called when one of the MidiKeyboardState's keys is released.
  32132. This will be called synchronously when the state is either processing a
  32133. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32134. when a note is being played with its MidiKeyboardState::noteOff() method.
  32135. Note that this callback could happen from an audio callback thread, so be
  32136. careful not to block, and avoid any UI activity in the callback.
  32137. */
  32138. virtual void handleNoteOff (MidiKeyboardState* source,
  32139. int midiChannel, int midiNoteNumber) = 0;
  32140. };
  32141. /**
  32142. Represents a piano keyboard, keeping track of which keys are currently pressed.
  32143. This object can parse a stream of midi events, using them to update its idea
  32144. of which keys are pressed for each individiual midi channel.
  32145. When keys go up or down, it can broadcast these events to listener objects.
  32146. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  32147. methods, and midi messages for these events will be merged into the
  32148. midi stream that gets processed by processNextMidiBuffer().
  32149. */
  32150. class JUCE_API MidiKeyboardState
  32151. {
  32152. public:
  32153. MidiKeyboardState();
  32154. ~MidiKeyboardState();
  32155. /** Resets the state of the object.
  32156. All internal data for all the channels is reset, but no events are sent as a
  32157. result.
  32158. If you want to release any keys that are currently down, and to send out note-up
  32159. midi messages for this, use the allNotesOff() method instead.
  32160. */
  32161. void reset();
  32162. /** Returns true if the given midi key is currently held down for the given midi channel.
  32163. The channel number must be between 1 and 16. If you want to see if any notes are
  32164. on for a range of channels, use the isNoteOnForChannels() method.
  32165. */
  32166. bool isNoteOn (int midiChannel, int midiNoteNumber) const noexcept;
  32167. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  32168. The channel mask has a bit set for each midi channel you want to test for - bit
  32169. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  32170. If a note is on for at least one of the specified channels, this returns true.
  32171. */
  32172. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const noexcept;
  32173. /** Turns a specified note on.
  32174. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  32175. next call to processNextMidiBuffer().
  32176. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32177. gone down.
  32178. */
  32179. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  32180. /** Turns a specified note off.
  32181. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  32182. next call to processNextMidiBuffer().
  32183. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32184. gone up.
  32185. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  32186. */
  32187. void noteOff (int midiChannel, int midiNoteNumber);
  32188. /** This will turn off any currently-down notes for the given midi channel.
  32189. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  32190. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  32191. and events being added to the midi stream.
  32192. */
  32193. void allNotesOff (int midiChannel);
  32194. /** Looks at a key-up/down event and uses it to update the state of this object.
  32195. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  32196. instead.
  32197. */
  32198. void processNextMidiEvent (const MidiMessage& message);
  32199. /** Scans a midi stream for up/down events and adds its own events to it.
  32200. This will look for any up/down events and use them to update the internal state,
  32201. synchronously making suitable callbacks to the listeners.
  32202. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  32203. and noteOff() calls will be added into the buffer.
  32204. Only the section of the buffer whose timestamps are between startSample and
  32205. (startSample + numSamples) will be affected, and any events added will be placed
  32206. between these times.
  32207. If you're going to use this method, you'll need to keep calling it regularly for
  32208. it to work satisfactorily.
  32209. To process a single midi event at a time, use the processNextMidiEvent() method
  32210. instead.
  32211. */
  32212. void processNextMidiBuffer (MidiBuffer& buffer,
  32213. int startSample,
  32214. int numSamples,
  32215. bool injectIndirectEvents);
  32216. /** Registers a listener for callbacks when keys go up or down.
  32217. @see removeListener
  32218. */
  32219. void addListener (MidiKeyboardStateListener* listener);
  32220. /** Deregisters a listener.
  32221. @see addListener
  32222. */
  32223. void removeListener (MidiKeyboardStateListener* listener);
  32224. private:
  32225. CriticalSection lock;
  32226. uint16 noteStates [128];
  32227. MidiBuffer eventsToAdd;
  32228. Array <MidiKeyboardStateListener*> listeners;
  32229. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  32230. void noteOffInternal (int midiChannel, int midiNoteNumber);
  32231. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  32232. };
  32233. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32234. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  32235. #endif
  32236. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  32237. #endif
  32238. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32239. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  32240. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32241. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32242. /**
  32243. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  32244. processing by a block-based audio callback.
  32245. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  32246. so it can easily use a midi input or keyboard component as its source.
  32247. @see MidiMessage, MidiInput
  32248. */
  32249. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  32250. public MidiInputCallback
  32251. {
  32252. public:
  32253. /** Creates a MidiMessageCollector. */
  32254. MidiMessageCollector();
  32255. /** Destructor. */
  32256. ~MidiMessageCollector();
  32257. /** Clears any messages from the queue.
  32258. You need to call this method before starting to use the collector, so that
  32259. it knows the correct sample rate to use.
  32260. */
  32261. void reset (double sampleRate);
  32262. /** Takes an incoming real-time message and adds it to the queue.
  32263. The message's timestamp is taken, and it will be ready for retrieval as part
  32264. of the block returned by the next call to removeNextBlockOfMessages().
  32265. This method is fully thread-safe when overlapping calls are made with
  32266. removeNextBlockOfMessages().
  32267. */
  32268. void addMessageToQueue (const MidiMessage& message);
  32269. /** Removes all the pending messages from the queue as a buffer.
  32270. This will also correct the messages' timestamps to make sure they're in
  32271. the range 0 to numSamples - 1.
  32272. This call should be made regularly by something like an audio processing
  32273. callback, because the time that it happens is used in calculating the
  32274. midi event positions.
  32275. This method is fully thread-safe when overlapping calls are made with
  32276. addMessageToQueue().
  32277. */
  32278. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  32279. /** @internal */
  32280. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  32281. /** @internal */
  32282. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  32283. /** @internal */
  32284. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  32285. private:
  32286. double lastCallbackTime;
  32287. CriticalSection midiCallbackLock;
  32288. MidiBuffer incomingMessages;
  32289. double sampleRate;
  32290. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  32291. };
  32292. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32293. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  32294. #endif
  32295. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32296. #endif
  32297. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  32298. #endif
  32299. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32300. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  32301. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32302. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32303. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  32304. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32305. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32306. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  32307. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32308. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32309. /*** Start of inlined file: juce_AudioProcessor.h ***/
  32310. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32311. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32312. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  32313. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32314. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32315. class AudioProcessor;
  32316. /**
  32317. Base class for the component that acts as the GUI for an AudioProcessor.
  32318. Derive your editor component from this class, and create an instance of it
  32319. by overriding the AudioProcessor::createEditor() method.
  32320. @see AudioProcessor, GenericAudioProcessorEditor
  32321. */
  32322. class JUCE_API AudioProcessorEditor : public Component
  32323. {
  32324. protected:
  32325. /** Creates an editor for the specified processor.
  32326. */
  32327. AudioProcessorEditor (AudioProcessor* owner);
  32328. public:
  32329. /** Destructor. */
  32330. ~AudioProcessorEditor();
  32331. /** Returns a pointer to the processor that this editor represents. */
  32332. AudioProcessor* getAudioProcessor() const noexcept { return owner; }
  32333. private:
  32334. AudioProcessor* const owner;
  32335. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  32336. };
  32337. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32338. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  32339. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  32340. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32341. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32342. class AudioProcessor;
  32343. /**
  32344. Base class for listeners that want to know about changes to an AudioProcessor.
  32345. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  32346. @see AudioProcessor
  32347. */
  32348. class JUCE_API AudioProcessorListener
  32349. {
  32350. public:
  32351. /** Destructor. */
  32352. virtual ~AudioProcessorListener() {}
  32353. /** Receives a callback when a parameter is changed.
  32354. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  32355. many audio processors will change their parameter during their audio callback.
  32356. This means that not only has your handler code got to be completely thread-safe,
  32357. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  32358. this event on your message thread, use this callback to trigger an AsyncUpdater
  32359. or ChangeBroadcaster which you can respond to on the message thread.
  32360. */
  32361. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  32362. int parameterIndex,
  32363. float newValue) = 0;
  32364. /** Called to indicate that something else in the plugin has changed, like its
  32365. program, number of parameters, etc.
  32366. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32367. call it during their audio callback. This means that not only has your handler code
  32368. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32369. blocking. If you need to handle this event on your message thread, use this callback
  32370. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32371. message thread.
  32372. */
  32373. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  32374. /** Indicates that a parameter change gesture has started.
  32375. E.g. if the user is dragging a slider, this would be called when they first
  32376. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  32377. called when they release it.
  32378. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32379. call it during their audio callback. This means that not only has your handler code
  32380. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32381. blocking. If you need to handle this event on your message thread, use this callback
  32382. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32383. message thread.
  32384. @see audioProcessorParameterChangeGestureEnd
  32385. */
  32386. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  32387. int parameterIndex);
  32388. /** Indicates that a parameter change gesture has finished.
  32389. E.g. if the user is dragging a slider, this would be called when they release
  32390. the mouse button.
  32391. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32392. call it during their audio callback. This means that not only has your handler code
  32393. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32394. blocking. If you need to handle this event on your message thread, use this callback
  32395. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32396. message thread.
  32397. @see audioProcessorParameterChangeGestureBegin
  32398. */
  32399. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  32400. int parameterIndex);
  32401. };
  32402. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32403. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  32404. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  32405. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32406. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32407. /**
  32408. A subclass of AudioPlayHead can supply information about the position and
  32409. status of a moving play head during audio playback.
  32410. One of these can be supplied to an AudioProcessor object so that it can find
  32411. out about the position of the audio that it is rendering.
  32412. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  32413. */
  32414. class JUCE_API AudioPlayHead
  32415. {
  32416. protected:
  32417. AudioPlayHead() {}
  32418. public:
  32419. virtual ~AudioPlayHead() {}
  32420. /** Frame rate types. */
  32421. enum FrameRateType
  32422. {
  32423. fps24 = 0,
  32424. fps25 = 1,
  32425. fps2997 = 2,
  32426. fps30 = 3,
  32427. fps2997drop = 4,
  32428. fps30drop = 5,
  32429. fpsUnknown = 99
  32430. };
  32431. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  32432. */
  32433. struct CurrentPositionInfo
  32434. {
  32435. /** The tempo in BPM */
  32436. double bpm;
  32437. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  32438. int timeSigNumerator;
  32439. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  32440. int timeSigDenominator;
  32441. /** The current play position, in seconds from the start of the edit. */
  32442. double timeInSeconds;
  32443. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  32444. double editOriginTime;
  32445. /** The current play position in pulses-per-quarter-note.
  32446. This is the number of quarter notes since the edit start.
  32447. */
  32448. double ppqPosition;
  32449. /** The position of the start of the last bar, in pulses-per-quarter-note.
  32450. This is the number of quarter notes from the start of the edit to the
  32451. start of the current bar.
  32452. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  32453. it's not available, the value will be 0.
  32454. */
  32455. double ppqPositionOfLastBarStart;
  32456. /** The video frame rate, if applicable. */
  32457. FrameRateType frameRate;
  32458. /** True if the transport is currently playing. */
  32459. bool isPlaying;
  32460. /** True if the transport is currently recording.
  32461. (When isRecording is true, then isPlaying will also be true).
  32462. */
  32463. bool isRecording;
  32464. bool operator== (const CurrentPositionInfo& other) const noexcept;
  32465. bool operator!= (const CurrentPositionInfo& other) const noexcept;
  32466. void resetToDefault();
  32467. };
  32468. /** Fills-in the given structure with details about the transport's
  32469. position at the start of the current processing block.
  32470. */
  32471. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  32472. };
  32473. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32474. /*** End of inlined file: juce_AudioPlayHead.h ***/
  32475. /**
  32476. Base class for audio processing filters or plugins.
  32477. This is intended to act as a base class of audio filter that is general enough to
  32478. be wrapped as a VST, AU, RTAS, etc, or used internally.
  32479. It is also used by the plugin hosting code as the wrapper around an instance
  32480. of a loaded plugin.
  32481. Derive your filter class from this base class, and if you're building a plugin,
  32482. you should implement a global function called createPluginFilter() which creates
  32483. and returns a new instance of your subclass.
  32484. */
  32485. class JUCE_API AudioProcessor
  32486. {
  32487. protected:
  32488. /** Constructor.
  32489. You can also do your initialisation tasks in the initialiseFilterInfo()
  32490. call, which will be made after this object has been created.
  32491. */
  32492. AudioProcessor();
  32493. public:
  32494. /** Destructor. */
  32495. virtual ~AudioProcessor();
  32496. /** Returns the name of this processor.
  32497. */
  32498. virtual const String getName() const = 0;
  32499. /** Called before playback starts, to let the filter prepare itself.
  32500. The sample rate is the target sample rate, and will remain constant until
  32501. playback stops.
  32502. The estimatedSamplesPerBlock value is a HINT about the typical number of
  32503. samples that will be processed for each callback, but isn't any kind
  32504. of guarantee. The actual block sizes that the host uses may be different
  32505. each time the callback happens, and may be more or less than this value.
  32506. */
  32507. virtual void prepareToPlay (double sampleRate,
  32508. int estimatedSamplesPerBlock) = 0;
  32509. /** Called after playback has stopped, to let the filter free up any resources it
  32510. no longer needs.
  32511. */
  32512. virtual void releaseResources() = 0;
  32513. /** Renders the next block.
  32514. When this method is called, the buffer contains a number of channels which is
  32515. at least as great as the maximum number of input and output channels that
  32516. this filter is using. It will be filled with the filter's input data and
  32517. should be replaced with the filter's output.
  32518. So for example if your filter has 2 input channels and 4 output channels, then
  32519. the buffer will contain 4 channels, the first two being filled with the
  32520. input data. Your filter should read these, do its processing, and replace
  32521. the contents of all 4 channels with its output.
  32522. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  32523. all filled with data, and your filter should overwrite the first 2 of these
  32524. with its output. But be VERY careful not to write anything to the last 3
  32525. channels, as these might be mapped to memory that the host assumes is read-only!
  32526. Note that if you have more outputs than inputs, then only those channels that
  32527. correspond to an input channel are guaranteed to contain sensible data - e.g.
  32528. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  32529. but the last two channels may contain garbage, so you should be careful not to
  32530. let this pass through without being overwritten or cleared.
  32531. Also note that the buffer may have more channels than are strictly necessary,
  32532. but your should only read/write from the ones that your filter is supposed to
  32533. be using.
  32534. The number of samples in these buffers is NOT guaranteed to be the same for every
  32535. callback, and may be more or less than the estimated value given to prepareToPlay().
  32536. Your code must be able to cope with variable-sized blocks, or you're going to get
  32537. clicks and crashes!
  32538. If the filter is receiving a midi input, then the midiMessages array will be filled
  32539. with the midi messages for this block. Each message's timestamp will indicate the
  32540. message's time, as a number of samples from the start of the block.
  32541. Any messages left in the midi buffer when this method has finished are assumed to
  32542. be the filter's midi output. This means that your filter should be careful to
  32543. clear any incoming messages from the array if it doesn't want them to be passed-on.
  32544. Be very careful about what you do in this callback - it's going to be called by
  32545. the audio thread, so any kind of interaction with the UI is absolutely
  32546. out of the question. If you change a parameter in here and need to tell your UI to
  32547. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  32548. the UI components register as listeners, and then call sendChangeMessage() inside the
  32549. processBlock() method to send out an asynchronous message. You could also use
  32550. the AsyncUpdater class in a similar way.
  32551. */
  32552. virtual void processBlock (AudioSampleBuffer& buffer,
  32553. MidiBuffer& midiMessages) = 0;
  32554. /** Returns the current AudioPlayHead object that should be used to find
  32555. out the state and position of the playhead.
  32556. You can call this from your processBlock() method, and use the AudioPlayHead
  32557. object to get the details about the time of the start of the block currently
  32558. being processed.
  32559. If the host hasn't supplied a playhead object, this will return 0.
  32560. */
  32561. AudioPlayHead* getPlayHead() const noexcept { return playHead; }
  32562. /** Returns the current sample rate.
  32563. This can be called from your processBlock() method - it's not guaranteed
  32564. to be valid at any other time, and may return 0 if it's unknown.
  32565. */
  32566. double getSampleRate() const noexcept { return sampleRate; }
  32567. /** Returns the current typical block size that is being used.
  32568. This can be called from your processBlock() method - it's not guaranteed
  32569. to be valid at any other time.
  32570. Remember it's not the ONLY block size that may be used when calling
  32571. processBlock, it's just the normal one. The actual block sizes used may be
  32572. larger or smaller than this, and will vary between successive calls.
  32573. */
  32574. int getBlockSize() const noexcept { return blockSize; }
  32575. /** Returns the number of input channels that the host will be sending the filter.
  32576. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  32577. number of channels that your filter would prefer to have, and this method lets
  32578. you know how many the host is actually using.
  32579. Note that this method is only valid during or after the prepareToPlay()
  32580. method call. Until that point, the number of channels will be unknown.
  32581. */
  32582. int getNumInputChannels() const noexcept { return numInputChannels; }
  32583. /** Returns the number of output channels that the host will be sending the filter.
  32584. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  32585. number of channels that your filter would prefer to have, and this method lets
  32586. you know how many the host is actually using.
  32587. Note that this method is only valid during or after the prepareToPlay()
  32588. method call. Until that point, the number of channels will be unknown.
  32589. */
  32590. int getNumOutputChannels() const noexcept { return numOutputChannels; }
  32591. /** Returns the name of one of the input channels, as returned by the host.
  32592. The host might not supply very useful names for channels, and this might be
  32593. something like "1", "2", "left", "right", etc.
  32594. */
  32595. virtual const String getInputChannelName (int channelIndex) const = 0;
  32596. /** Returns the name of one of the output channels, as returned by the host.
  32597. The host might not supply very useful names for channels, and this might be
  32598. something like "1", "2", "left", "right", etc.
  32599. */
  32600. virtual const String getOutputChannelName (int channelIndex) const = 0;
  32601. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  32602. virtual bool isInputChannelStereoPair (int index) const = 0;
  32603. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  32604. virtual bool isOutputChannelStereoPair (int index) const = 0;
  32605. /** This returns the number of samples delay that the filter imposes on the audio
  32606. passing through it.
  32607. The host will call this to find the latency - the filter itself should set this value
  32608. by calling setLatencySamples() as soon as it can during its initialisation.
  32609. */
  32610. int getLatencySamples() const noexcept { return latencySamples; }
  32611. /** The filter should call this to set the number of samples delay that it introduces.
  32612. The filter should call this as soon as it can during initialisation, and can call it
  32613. later if the value changes.
  32614. */
  32615. void setLatencySamples (int newLatency);
  32616. /** Returns true if the processor wants midi messages. */
  32617. virtual bool acceptsMidi() const = 0;
  32618. /** Returns true if the processor produces midi messages. */
  32619. virtual bool producesMidi() const = 0;
  32620. /** This returns a critical section that will automatically be locked while the host
  32621. is calling the processBlock() method.
  32622. Use it from your UI or other threads to lock access to variables that are used
  32623. by the process callback, but obviously be careful not to keep it locked for
  32624. too long, because that could cause stuttering playback. If you need to do something
  32625. that'll take a long time and need the processing to stop while it happens, use the
  32626. suspendProcessing() method instead.
  32627. @see suspendProcessing
  32628. */
  32629. const CriticalSection& getCallbackLock() const noexcept { return callbackLock; }
  32630. /** Enables and disables the processing callback.
  32631. If you need to do something time-consuming on a thread and would like to make sure
  32632. the audio processing callback doesn't happen until you've finished, use this
  32633. to disable the callback and re-enable it again afterwards.
  32634. E.g.
  32635. @code
  32636. void loadNewPatch()
  32637. {
  32638. suspendProcessing (true);
  32639. ..do something that takes ages..
  32640. suspendProcessing (false);
  32641. }
  32642. @endcode
  32643. If the host tries to make an audio callback while processing is suspended, the
  32644. filter will return an empty buffer, but won't block the audio thread like it would
  32645. do if you use the getCallbackLock() critical section to synchronise access.
  32646. If you're going to use this, your processBlock() method must call isSuspended() and
  32647. check whether it's suspended or not. If it is, then it should skip doing any real
  32648. processing, either emitting silence or passing the input through unchanged.
  32649. @see getCallbackLock
  32650. */
  32651. void suspendProcessing (bool shouldBeSuspended);
  32652. /** Returns true if processing is currently suspended.
  32653. @see suspendProcessing
  32654. */
  32655. bool isSuspended() const noexcept { return suspended; }
  32656. /** A plugin can override this to be told when it should reset any playing voices.
  32657. The default implementation does nothing, but a host may call this to tell the
  32658. plugin that it should stop any tails or sounds that have been left running.
  32659. */
  32660. virtual void reset();
  32661. /** Returns true if the processor is being run in an offline mode for rendering.
  32662. If the processor is being run live on realtime signals, this returns false.
  32663. If the mode is unknown, this will assume it's realtime and return false.
  32664. This value may be unreliable until the prepareToPlay() method has been called,
  32665. and could change each time prepareToPlay() is called.
  32666. @see setNonRealtime()
  32667. */
  32668. bool isNonRealtime() const noexcept { return nonRealtime; }
  32669. /** Called by the host to tell this processor whether it's being used in a non-realime
  32670. capacity for offline rendering or bouncing.
  32671. Whatever value is passed-in will be
  32672. */
  32673. void setNonRealtime (bool isNonRealtime) noexcept;
  32674. /** Creates the filter's UI.
  32675. This can return 0 if you want a UI-less filter, in which case the host may create
  32676. a generic UI that lets the user twiddle the parameters directly.
  32677. If you do want to pass back a component, the component should be created and set to
  32678. the correct size before returning it. If you implement this method, you must
  32679. also implement the hasEditor() method and make it return true.
  32680. Remember not to do anything silly like allowing your filter to keep a pointer to
  32681. the component that gets created - it could be deleted later without any warning, which
  32682. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  32683. The correct way to handle the connection between an editor component and its
  32684. filter is to use something like a ChangeBroadcaster so that the editor can
  32685. register itself as a listener, and be told when a change occurs. This lets them
  32686. safely unregister themselves when they are deleted.
  32687. Here are a few things to bear in mind when writing an editor:
  32688. - Initially there won't be an editor, until the user opens one, or they might
  32689. not open one at all. Your filter mustn't rely on it being there.
  32690. - An editor object may be deleted and a replacement one created again at any time.
  32691. - It's safe to assume that an editor will be deleted before its filter.
  32692. @see hasEditor
  32693. */
  32694. virtual AudioProcessorEditor* createEditor() = 0;
  32695. /** Your filter must override this and return true if it can create an editor component.
  32696. @see createEditor
  32697. */
  32698. virtual bool hasEditor() const = 0;
  32699. /** Returns the active editor, if there is one.
  32700. Bear in mind this can return 0, even if an editor has previously been
  32701. opened.
  32702. */
  32703. AudioProcessorEditor* getActiveEditor() const noexcept { return activeEditor; }
  32704. /** Returns the active editor, or if there isn't one, it will create one.
  32705. This may call createEditor() internally to create the component.
  32706. */
  32707. AudioProcessorEditor* createEditorIfNeeded();
  32708. /** This must return the correct value immediately after the object has been
  32709. created, and mustn't change the number of parameters later.
  32710. */
  32711. virtual int getNumParameters() = 0;
  32712. /** Returns the name of a particular parameter. */
  32713. virtual const String getParameterName (int parameterIndex) = 0;
  32714. /** Called by the host to find out the value of one of the filter's parameters.
  32715. The host will expect the value returned to be between 0 and 1.0.
  32716. This could be called quite frequently, so try to make your code efficient.
  32717. It's also likely to be called by non-UI threads, so the code in here should
  32718. be thread-aware.
  32719. */
  32720. virtual float getParameter (int parameterIndex) = 0;
  32721. /** Returns the value of a parameter as a text string. */
  32722. virtual const String getParameterText (int parameterIndex) = 0;
  32723. /** The host will call this method to change the value of one of the filter's parameters.
  32724. The host may call this at any time, including during the audio processing
  32725. callback, so the filter has to process this very fast and avoid blocking.
  32726. If you want to set the value of a parameter internally, e.g. from your
  32727. editor component, then don't call this directly - instead, use the
  32728. setParameterNotifyingHost() method, which will also send a message to
  32729. the host telling it about the change. If the message isn't sent, the host
  32730. won't be able to automate your parameters properly.
  32731. The value passed will be between 0 and 1.0.
  32732. */
  32733. virtual void setParameter (int parameterIndex,
  32734. float newValue) = 0;
  32735. /** Your filter can call this when it needs to change one of its parameters.
  32736. This could happen when the editor or some other internal operation changes
  32737. a parameter. This method will call the setParameter() method to change the
  32738. value, and will then send a message to the host telling it about the change.
  32739. Note that to make sure the host correctly handles automation, you should call
  32740. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  32741. tell the host when the user has started and stopped changing the parameter.
  32742. */
  32743. void setParameterNotifyingHost (int parameterIndex,
  32744. float newValue);
  32745. /** Returns true if the host can automate this parameter.
  32746. By default, this returns true for all parameters.
  32747. */
  32748. virtual bool isParameterAutomatable (int parameterIndex) const;
  32749. /** Should return true if this parameter is a "meta" parameter.
  32750. A meta-parameter is a parameter that changes other params. It is used
  32751. by some hosts (e.g. AudioUnit hosts).
  32752. By default this returns false.
  32753. */
  32754. virtual bool isMetaParameter (int parameterIndex) const;
  32755. /** Sends a signal to the host to tell it that the user is about to start changing this
  32756. parameter.
  32757. This allows the host to know when a parameter is actively being held by the user, and
  32758. it may use this information to help it record automation.
  32759. If you call this, it must be matched by a later call to endParameterChangeGesture().
  32760. */
  32761. void beginParameterChangeGesture (int parameterIndex);
  32762. /** Tells the host that the user has finished changing this parameter.
  32763. This allows the host to know when a parameter is actively being held by the user, and
  32764. it may use this information to help it record automation.
  32765. A call to this method must follow a call to beginParameterChangeGesture().
  32766. */
  32767. void endParameterChangeGesture (int parameterIndex);
  32768. /** The filter can call this when something (apart from a parameter value) has changed.
  32769. It sends a hint to the host that something like the program, number of parameters,
  32770. etc, has changed, and that it should update itself.
  32771. */
  32772. void updateHostDisplay();
  32773. /** Returns the number of preset programs the filter supports.
  32774. The value returned must be valid as soon as this object is created, and
  32775. must not change over its lifetime.
  32776. This value shouldn't be less than 1.
  32777. */
  32778. virtual int getNumPrograms() = 0;
  32779. /** Returns the number of the currently active program.
  32780. */
  32781. virtual int getCurrentProgram() = 0;
  32782. /** Called by the host to change the current program.
  32783. */
  32784. virtual void setCurrentProgram (int index) = 0;
  32785. /** Must return the name of a given program. */
  32786. virtual const String getProgramName (int index) = 0;
  32787. /** Called by the host to rename a program.
  32788. */
  32789. virtual void changeProgramName (int index, const String& newName) = 0;
  32790. /** The host will call this method when it wants to save the filter's internal state.
  32791. This must copy any info about the filter's state into the block of memory provided,
  32792. so that the host can store this and later restore it using setStateInformation().
  32793. Note that there's also a getCurrentProgramStateInformation() method, which only
  32794. stores the current program, not the state of the entire filter.
  32795. See also the helper function copyXmlToBinary() for storing settings as XML.
  32796. @see getCurrentProgramStateInformation
  32797. */
  32798. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  32799. /** The host will call this method if it wants to save the state of just the filter's
  32800. current program.
  32801. Unlike getStateInformation, this should only return the current program's state.
  32802. Not all hosts support this, and if you don't implement it, the base class
  32803. method just calls getStateInformation() instead. If you do implement it, be
  32804. sure to also implement getCurrentProgramStateInformation.
  32805. @see getStateInformation, setCurrentProgramStateInformation
  32806. */
  32807. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  32808. /** This must restore the filter's state from a block of data previously created
  32809. using getStateInformation().
  32810. Note that there's also a setCurrentProgramStateInformation() method, which tries
  32811. to restore just the current program, not the state of the entire filter.
  32812. See also the helper function getXmlFromBinary() for loading settings as XML.
  32813. @see setCurrentProgramStateInformation
  32814. */
  32815. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  32816. /** The host will call this method if it wants to restore the state of just the filter's
  32817. current program.
  32818. Not all hosts support this, and if you don't implement it, the base class
  32819. method just calls setStateInformation() instead. If you do implement it, be
  32820. sure to also implement getCurrentProgramStateInformation.
  32821. @see setStateInformation, getCurrentProgramStateInformation
  32822. */
  32823. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  32824. /** Adds a listener that will be called when an aspect of this processor changes. */
  32825. void addListener (AudioProcessorListener* newListener);
  32826. /** Removes a previously added listener. */
  32827. void removeListener (AudioProcessorListener* listenerToRemove);
  32828. /** Tells the processor to use this playhead object.
  32829. The processor will not take ownership of the object, so the caller must delete it when
  32830. it is no longer being used.
  32831. */
  32832. void setPlayHead (AudioPlayHead* newPlayHead) noexcept;
  32833. /** Not for public use - this is called before deleting an editor component. */
  32834. void editorBeingDeleted (AudioProcessorEditor* editor) noexcept;
  32835. /** Not for public use - this is called to initialise the processor before playing. */
  32836. void setPlayConfigDetails (int numIns, int numOuts,
  32837. double sampleRate,
  32838. int blockSize) noexcept;
  32839. protected:
  32840. /** Helper function that just converts an xml element into a binary blob.
  32841. Use this in your filter's getStateInformation() method if you want to
  32842. store its state as xml.
  32843. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  32844. from a binary blob.
  32845. */
  32846. static void copyXmlToBinary (const XmlElement& xml,
  32847. JUCE_NAMESPACE::MemoryBlock& destData);
  32848. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  32849. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  32850. an XmlElement object that the caller must delete when no longer needed.
  32851. */
  32852. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  32853. /** @internal */
  32854. AudioPlayHead* playHead;
  32855. /** @internal */
  32856. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  32857. private:
  32858. Array <AudioProcessorListener*> listeners;
  32859. Component::SafePointer<AudioProcessorEditor> activeEditor;
  32860. double sampleRate;
  32861. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  32862. bool suspended, nonRealtime;
  32863. CriticalSection callbackLock, listenerLock;
  32864. #if JUCE_DEBUG
  32865. BigInteger changingParams;
  32866. #endif
  32867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  32868. };
  32869. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32870. /*** End of inlined file: juce_AudioProcessor.h ***/
  32871. /*** Start of inlined file: juce_PluginDescription.h ***/
  32872. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32873. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32874. /**
  32875. A small class to represent some facts about a particular type of plugin.
  32876. This class is for storing and managing the details about a plugin without
  32877. actually having to load an instance of it.
  32878. A KnownPluginList contains a list of PluginDescription objects.
  32879. @see KnownPluginList
  32880. */
  32881. class JUCE_API PluginDescription
  32882. {
  32883. public:
  32884. PluginDescription();
  32885. PluginDescription (const PluginDescription& other);
  32886. PluginDescription& operator= (const PluginDescription& other);
  32887. ~PluginDescription();
  32888. /** The name of the plugin. */
  32889. String name;
  32890. /** A more descriptive name for the plugin.
  32891. This may be the same as the 'name' field, but some plugins may provide an
  32892. alternative name.
  32893. */
  32894. String descriptiveName;
  32895. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  32896. */
  32897. String pluginFormatName;
  32898. /** A category, such as "Dynamics", "Reverbs", etc.
  32899. */
  32900. String category;
  32901. /** The manufacturer. */
  32902. String manufacturerName;
  32903. /** The version. This string doesn't have any particular format. */
  32904. String version;
  32905. /** Either the file containing the plugin module, or some other unique way
  32906. of identifying it.
  32907. E.g. for an AU, this would be an ID string that the component manager
  32908. could use to retrieve the plugin. For a VST, it's the file path.
  32909. */
  32910. String fileOrIdentifier;
  32911. /** The last time the plugin file was changed.
  32912. This is handy when scanning for new or changed plugins.
  32913. */
  32914. Time lastFileModTime;
  32915. /** A unique ID for the plugin.
  32916. Note that this might not be unique between formats, e.g. a VST and some
  32917. other format might actually have the same id.
  32918. @see createIdentifierString
  32919. */
  32920. int uid;
  32921. /** True if the plugin identifies itself as a synthesiser. */
  32922. bool isInstrument;
  32923. /** The number of inputs. */
  32924. int numInputChannels;
  32925. /** The number of outputs. */
  32926. int numOutputChannels;
  32927. /** Returns true if the two descriptions refer the the same plugin.
  32928. This isn't quite as simple as them just having the same file (because of
  32929. shell plugins).
  32930. */
  32931. bool isDuplicateOf (const PluginDescription& other) const;
  32932. /** Returns a string that can be saved and used to uniquely identify the
  32933. plugin again.
  32934. This contains less info than the XML encoding, and is independent of the
  32935. plugin's file location, so can be used to store a plugin ID for use
  32936. across different machines.
  32937. */
  32938. const String createIdentifierString() const;
  32939. /** Creates an XML object containing these details.
  32940. @see loadFromXml
  32941. */
  32942. XmlElement* createXml() const;
  32943. /** Reloads the info in this structure from an XML record that was previously
  32944. saved with createXML().
  32945. Returns true if the XML was a valid plugin description.
  32946. */
  32947. bool loadFromXml (const XmlElement& xml);
  32948. private:
  32949. JUCE_LEAK_DETECTOR (PluginDescription);
  32950. };
  32951. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32952. /*** End of inlined file: juce_PluginDescription.h ***/
  32953. /**
  32954. Base class for an active instance of a plugin.
  32955. This derives from the AudioProcessor class, and adds some extra functionality
  32956. that helps when wrapping dynamically loaded plugins.
  32957. @see AudioProcessor, AudioPluginFormat
  32958. */
  32959. class JUCE_API AudioPluginInstance : public AudioProcessor
  32960. {
  32961. public:
  32962. /** Destructor.
  32963. Make sure that you delete any UI components that belong to this plugin before
  32964. deleting the plugin.
  32965. */
  32966. virtual ~AudioPluginInstance();
  32967. /** Fills-in the appropriate parts of this plugin description object.
  32968. */
  32969. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  32970. /** Returns a pointer to some kind of platform-specific data about the plugin.
  32971. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  32972. cast to an AudioUnit handle.
  32973. */
  32974. virtual void* getPlatformSpecificData();
  32975. protected:
  32976. AudioPluginInstance();
  32977. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  32978. };
  32979. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32980. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  32981. class PluginDescription;
  32982. /**
  32983. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  32984. Use the static getNumFormats() and getFormat() calls to find the types
  32985. of format that are available.
  32986. */
  32987. class JUCE_API AudioPluginFormat
  32988. {
  32989. public:
  32990. /** Destructor. */
  32991. virtual ~AudioPluginFormat();
  32992. /** Returns the format name.
  32993. E.g. "VST", "AudioUnit", etc.
  32994. */
  32995. virtual const String getName() const = 0;
  32996. /** This tries to create descriptions for all the plugin types available in
  32997. a binary module file.
  32998. The file will be some kind of DLL or bundle.
  32999. Normally there will only be one type returned, but some plugins
  33000. (e.g. VST shells) can use a single DLL to create a set of different plugin
  33001. subtypes, so in that case, each subtype is returned as a separate object.
  33002. */
  33003. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  33004. const String& fileOrIdentifier) = 0;
  33005. /** Tries to recreate a type from a previously generated PluginDescription.
  33006. @see PluginDescription::createInstance
  33007. */
  33008. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  33009. /** Should do a quick check to see if this file or directory might be a plugin of
  33010. this format.
  33011. This is for searching for potential files, so it shouldn't actually try to
  33012. load the plugin or do anything time-consuming.
  33013. */
  33014. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  33015. /** Returns a readable version of the name of the plugin that this identifier refers to.
  33016. */
  33017. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  33018. /** Checks whether this plugin could possibly be loaded.
  33019. It doesn't actually need to load it, just to check whether the file or component
  33020. still exists.
  33021. */
  33022. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  33023. /** Searches a suggested set of directories for any plugins in this format.
  33024. The path might be ignored, e.g. by AUs, which are found by the OS rather
  33025. than manually.
  33026. */
  33027. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  33028. bool recursive) = 0;
  33029. /** Returns the typical places to look for this kind of plugin.
  33030. Note that if this returns no paths, it means that the format can't be scanned-for
  33031. (i.e. it's an internal format that doesn't live in files)
  33032. */
  33033. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  33034. protected:
  33035. AudioPluginFormat() noexcept;
  33036. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  33037. };
  33038. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33039. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  33040. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  33041. /**
  33042. Implements a plugin format manager for AudioUnits.
  33043. */
  33044. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  33045. {
  33046. public:
  33047. AudioUnitPluginFormat();
  33048. ~AudioUnitPluginFormat();
  33049. const String getName() const { return "AudioUnit"; }
  33050. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33051. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33052. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33053. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33054. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33055. bool doesPluginStillExist (const PluginDescription& desc);
  33056. const FileSearchPath getDefaultLocationsToSearch();
  33057. private:
  33058. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  33059. };
  33060. #endif
  33061. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33062. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  33063. #endif
  33064. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33065. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  33066. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33067. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33068. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  33069. // Sorry, this file is just a placeholder at the moment!...
  33070. /**
  33071. Implements a plugin format manager for DirectX plugins.
  33072. */
  33073. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  33074. {
  33075. public:
  33076. DirectXPluginFormat();
  33077. ~DirectXPluginFormat();
  33078. const String getName() const { return "DirectX"; }
  33079. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33080. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33081. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33082. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33083. const FileSearchPath getDefaultLocationsToSearch();
  33084. private:
  33085. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  33086. };
  33087. #endif
  33088. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33089. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  33090. #endif
  33091. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33092. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  33093. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33094. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33095. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  33096. // Sorry, this file is just a placeholder at the moment!...
  33097. /**
  33098. Implements a plugin format manager for DirectX plugins.
  33099. */
  33100. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  33101. {
  33102. public:
  33103. LADSPAPluginFormat();
  33104. ~LADSPAPluginFormat();
  33105. const String getName() const { return "LADSPA"; }
  33106. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33107. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33108. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33109. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33110. const FileSearchPath getDefaultLocationsToSearch();
  33111. private:
  33112. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  33113. };
  33114. #endif
  33115. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33116. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  33117. #endif
  33118. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33119. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  33120. #ifdef __aeffect__
  33121. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33122. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33123. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  33124. events to the list.
  33125. This is used by both the VST hosting code and the plugin wrapper.
  33126. */
  33127. class VSTMidiEventList
  33128. {
  33129. public:
  33130. VSTMidiEventList()
  33131. : numEventsUsed (0), numEventsAllocated (0)
  33132. {
  33133. }
  33134. ~VSTMidiEventList()
  33135. {
  33136. freeEvents();
  33137. }
  33138. void clear()
  33139. {
  33140. numEventsUsed = 0;
  33141. if (events != nullptr)
  33142. events->numEvents = 0;
  33143. }
  33144. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  33145. {
  33146. ensureSize (numEventsUsed + 1);
  33147. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  33148. events->numEvents = ++numEventsUsed;
  33149. if (numBytes <= 4)
  33150. {
  33151. if (e->type == kVstSysExType)
  33152. {
  33153. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33154. e->type = kVstMidiType;
  33155. e->byteSize = sizeof (VstMidiEvent);
  33156. e->noteLength = 0;
  33157. e->noteOffset = 0;
  33158. e->detune = 0;
  33159. e->noteOffVelocity = 0;
  33160. }
  33161. e->deltaFrames = frameOffset;
  33162. memcpy (e->midiData, midiData, numBytes);
  33163. }
  33164. else
  33165. {
  33166. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  33167. if (se->type == kVstSysExType)
  33168. delete[] se->sysexDump;
  33169. se->sysexDump = new char [numBytes];
  33170. memcpy (se->sysexDump, midiData, numBytes);
  33171. se->type = kVstSysExType;
  33172. se->byteSize = sizeof (VstMidiSysexEvent);
  33173. se->deltaFrames = frameOffset;
  33174. se->flags = 0;
  33175. se->dumpBytes = numBytes;
  33176. se->resvd1 = 0;
  33177. se->resvd2 = 0;
  33178. }
  33179. }
  33180. // Handy method to pull the events out of an event buffer supplied by the host
  33181. // or plugin.
  33182. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  33183. {
  33184. for (int i = 0; i < events->numEvents; ++i)
  33185. {
  33186. const VstEvent* const e = events->events[i];
  33187. if (e != nullptr)
  33188. {
  33189. if (e->type == kVstMidiType)
  33190. {
  33191. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  33192. 4, e->deltaFrames);
  33193. }
  33194. else if (e->type == kVstSysExType)
  33195. {
  33196. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  33197. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  33198. e->deltaFrames);
  33199. }
  33200. }
  33201. }
  33202. }
  33203. void ensureSize (int numEventsNeeded)
  33204. {
  33205. if (numEventsNeeded > numEventsAllocated)
  33206. {
  33207. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  33208. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  33209. if (events == nullptr)
  33210. events.calloc (size, 1);
  33211. else
  33212. events.realloc (size, 1);
  33213. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  33214. events->events[i] = allocateVSTEvent();
  33215. numEventsAllocated = numEventsNeeded;
  33216. }
  33217. }
  33218. void freeEvents()
  33219. {
  33220. if (events != nullptr)
  33221. {
  33222. for (int i = numEventsAllocated; --i >= 0;)
  33223. freeVSTEvent (events->events[i]);
  33224. events.free();
  33225. numEventsUsed = 0;
  33226. numEventsAllocated = 0;
  33227. }
  33228. }
  33229. HeapBlock <VstEvents> events;
  33230. private:
  33231. int numEventsUsed, numEventsAllocated;
  33232. static VstEvent* allocateVSTEvent()
  33233. {
  33234. VstEvent* const e = (VstEvent*) ::calloc (1, sizeof (VstMidiEvent) > sizeof (VstMidiSysexEvent) ? sizeof (VstMidiEvent)
  33235. : sizeof (VstMidiSysexEvent));
  33236. e->type = kVstMidiType;
  33237. e->byteSize = sizeof (VstMidiEvent);
  33238. return e;
  33239. }
  33240. static void freeVSTEvent (VstEvent* e)
  33241. {
  33242. if (e->type == kVstSysExType)
  33243. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33244. ::free (e);
  33245. }
  33246. };
  33247. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33248. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33249. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  33250. #endif
  33251. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33252. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  33253. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33254. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33255. #if JUCE_PLUGINHOST_VST
  33256. /**
  33257. Implements a plugin format manager for VSTs.
  33258. */
  33259. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  33260. {
  33261. public:
  33262. VSTPluginFormat();
  33263. ~VSTPluginFormat();
  33264. const String getName() const { return "VST"; }
  33265. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33266. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33267. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33268. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33269. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33270. bool doesPluginStillExist (const PluginDescription& desc);
  33271. const FileSearchPath getDefaultLocationsToSearch();
  33272. private:
  33273. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  33274. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  33275. };
  33276. #endif
  33277. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33278. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  33279. #endif
  33280. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33281. #endif
  33282. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33283. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  33284. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33285. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33286. /**
  33287. This maintains a list of known AudioPluginFormats.
  33288. @see AudioPluginFormat
  33289. */
  33290. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  33291. {
  33292. public:
  33293. AudioPluginFormatManager();
  33294. /** Destructor. */
  33295. ~AudioPluginFormatManager();
  33296. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  33297. /** Adds any formats that it knows about, e.g. VST.
  33298. */
  33299. void addDefaultFormats();
  33300. /** Returns the number of types of format that are available.
  33301. Use getFormat() to get one of them.
  33302. */
  33303. int getNumFormats();
  33304. /** Returns one of the available formats.
  33305. @see getNumFormats
  33306. */
  33307. AudioPluginFormat* getFormat (int index);
  33308. /** Adds a format to the list.
  33309. The object passed in will be owned and deleted by the manager.
  33310. */
  33311. void addFormat (AudioPluginFormat* format);
  33312. /** Tries to load the type for this description, by trying all the formats
  33313. that this manager knows about.
  33314. The caller is responsible for deleting the object that is returned.
  33315. If it can't load the plugin, it returns 0 and leaves a message in the
  33316. errorMessage string.
  33317. */
  33318. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  33319. String& errorMessage) const;
  33320. /** Checks that the file or component for this plugin actually still exists.
  33321. (This won't try to load the plugin)
  33322. */
  33323. bool doesPluginStillExist (const PluginDescription& description) const;
  33324. private:
  33325. OwnedArray <AudioPluginFormat> formats;
  33326. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  33327. };
  33328. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33329. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  33330. #endif
  33331. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33332. #endif
  33333. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33334. /*** Start of inlined file: juce_KnownPluginList.h ***/
  33335. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33336. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33337. /*** Start of inlined file: juce_PopupMenu.h ***/
  33338. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  33339. #define __JUCE_POPUPMENU_JUCEHEADER__
  33340. /** Creates and displays a popup-menu.
  33341. To show a popup-menu, you create one of these, add some items to it, then
  33342. call its show() method, which returns the id of the item the user selects.
  33343. E.g. @code
  33344. void MyWidget::mouseDown (const MouseEvent& e)
  33345. {
  33346. PopupMenu m;
  33347. m.addItem (1, "item 1");
  33348. m.addItem (2, "item 2");
  33349. const int result = m.show();
  33350. if (result == 0)
  33351. {
  33352. // user dismissed the menu without picking anything
  33353. }
  33354. else if (result == 1)
  33355. {
  33356. // user picked item 1
  33357. }
  33358. else if (result == 2)
  33359. {
  33360. // user picked item 2
  33361. }
  33362. }
  33363. @endcode
  33364. Submenus are easy too: @code
  33365. void MyWidget::mouseDown (const MouseEvent& e)
  33366. {
  33367. PopupMenu subMenu;
  33368. subMenu.addItem (1, "item 1");
  33369. subMenu.addItem (2, "item 2");
  33370. PopupMenu mainMenu;
  33371. mainMenu.addItem (3, "item 3");
  33372. mainMenu.addSubMenu ("other choices", subMenu);
  33373. const int result = m.show();
  33374. ...etc
  33375. }
  33376. @endcode
  33377. */
  33378. class JUCE_API PopupMenu
  33379. {
  33380. public:
  33381. /** Creates an empty popup menu. */
  33382. PopupMenu();
  33383. /** Creates a copy of another menu. */
  33384. PopupMenu (const PopupMenu& other);
  33385. /** Destructor. */
  33386. ~PopupMenu();
  33387. /** Copies this menu from another one. */
  33388. PopupMenu& operator= (const PopupMenu& other);
  33389. /** Resets the menu, removing all its items. */
  33390. void clear();
  33391. /** Appends a new text item for this menu to show.
  33392. @param itemResultId the number that will be returned from the show() method
  33393. if the user picks this item. The value should never be
  33394. zero, because that's used to indicate that the user didn't
  33395. select anything.
  33396. @param itemText the text to show.
  33397. @param isEnabled if false, the item will be shown 'greyed-out' and can't be picked
  33398. @param isTicked if true, the item will be shown with a tick next to it
  33399. @param iconToUse if this is non-zero, it should be an image that will be
  33400. displayed to the left of the item. This method will take its
  33401. own copy of the image passed-in, so there's no need to keep
  33402. it hanging around.
  33403. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  33404. */
  33405. void addItem (int itemResultId,
  33406. const String& itemText,
  33407. bool isEnabled = true,
  33408. bool isTicked = false,
  33409. const Image& iconToUse = Image::null);
  33410. /** Adds an item that represents one of the commands in a command manager object.
  33411. @param commandManager the manager to use to trigger the command and get information
  33412. about it
  33413. @param commandID the ID of the command
  33414. @param displayName if this is non-empty, then this string will be used instead of
  33415. the command's registered name
  33416. */
  33417. void addCommandItem (ApplicationCommandManager* commandManager,
  33418. int commandID,
  33419. const String& displayName = String::empty);
  33420. /** Appends a text item with a special colour.
  33421. This is the same as addItem(), but specifies a colour to use for the
  33422. text, which will override the default colours that are used by the
  33423. current look-and-feel. See addItem() for a description of the parameters.
  33424. */
  33425. void addColouredItem (int itemResultId,
  33426. const String& itemText,
  33427. const Colour& itemTextColour,
  33428. bool isEnabled = true,
  33429. bool isTicked = false,
  33430. const Image& iconToUse = Image::null);
  33431. /** Appends a custom menu item that can't be used to trigger a result.
  33432. This will add a user-defined component to use as a menu item. Unlike the
  33433. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  33434. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  33435. delete the component when it's finished, so it's the caller's responsibility
  33436. to manage the component that is passed-in.
  33437. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  33438. detection of a mouse-click on your component, and use that to trigger the
  33439. menu ID specified in itemResultId. If this is false, the menu item can't
  33440. be triggered, so itemResultId is not used.
  33441. @see CustomComponent
  33442. */
  33443. void addCustomItem (int itemResultId,
  33444. Component* customComponent,
  33445. int idealWidth, int idealHeight,
  33446. bool triggerMenuItemAutomaticallyWhenClicked);
  33447. /** Appends a sub-menu.
  33448. If the menu that's passed in is empty, it will appear as an inactive item.
  33449. */
  33450. void addSubMenu (const String& subMenuName,
  33451. const PopupMenu& subMenu,
  33452. bool isEnabled = true,
  33453. const Image& iconToUse = Image::null,
  33454. bool isTicked = false);
  33455. /** Appends a separator to the menu, to help break it up into sections.
  33456. The menu class is smart enough not to display separators at the top or bottom
  33457. of the menu, and it will replace mutliple adjacent separators with a single
  33458. one, so your code can be quite free and easy about adding these, and it'll
  33459. always look ok.
  33460. */
  33461. void addSeparator();
  33462. /** Adds a non-clickable text item to the menu.
  33463. This is a bold-font items which can be used as a header to separate the items
  33464. into named groups.
  33465. */
  33466. void addSectionHeader (const String& title);
  33467. /** Returns the number of items that the menu currently contains.
  33468. (This doesn't count separators).
  33469. */
  33470. int getNumItems() const noexcept;
  33471. /** Returns true if the menu contains a command item that triggers the given command. */
  33472. bool containsCommandItem (int commandID) const;
  33473. /** Returns true if the menu contains any items that can be used. */
  33474. bool containsAnyActiveItems() const noexcept;
  33475. /** Class used to create a set of options to pass to the show() method.
  33476. You can chain together a series of calls to this class's methods to create
  33477. a set of whatever options you want to specify.
  33478. E.g. @code
  33479. PopupMenu menu;
  33480. ...
  33481. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  33482. .withMaximumNumColumns (3)
  33483. .withTargetComponent (myComp));
  33484. @endcode
  33485. */
  33486. class JUCE_API Options
  33487. {
  33488. public:
  33489. Options();
  33490. const Options withTargetComponent (Component* targetComponent) const;
  33491. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  33492. const Options withMinimumWidth (int minWidth) const;
  33493. const Options withMaximumNumColumns (int maxNumColumns) const;
  33494. const Options withStandardItemHeight (int standardHeight) const;
  33495. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  33496. private:
  33497. friend class PopupMenu;
  33498. Rectangle<int> targetArea;
  33499. Component* targetComponent;
  33500. int visibleItemID, minWidth, maxColumns, standardHeight;
  33501. };
  33502. #if JUCE_MODAL_LOOPS_PERMITTED
  33503. /** Displays the menu and waits for the user to pick something.
  33504. This will display the menu modally, and return the ID of the item that the
  33505. user picks. If they click somewhere off the menu to get rid of it without
  33506. choosing anything, this will return 0.
  33507. The current location of the mouse will be used as the position to show the
  33508. menu - to explicitly set the menu's position, use showAt() instead. Depending
  33509. on where this point is on the screen, the menu will appear above, below or
  33510. to the side of the point.
  33511. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  33512. then when the menu first appears, it will make sure
  33513. that this item is visible. So if the menu has too many
  33514. items to fit on the screen, it will be scrolled to a
  33515. position where this item is visible.
  33516. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  33517. than this if some items are too long to fit.
  33518. @param maximumNumColumns if there are too many items to fit on-screen in a single
  33519. vertical column, the menu may be laid out as a series of
  33520. columns - this is the maximum number allowed. To use the
  33521. default value for this (probably about 7), you can pass
  33522. in zero.
  33523. @param standardItemHeight if this is non-zero, it will be used as the standard
  33524. height for menu items (apart from custom items)
  33525. @param callback if this is non-zero, the menu will be launched asynchronously,
  33526. returning immediately, and the callback will receive a
  33527. call when the menu is either dismissed or has an item
  33528. selected. This object will be owned and deleted by the
  33529. system, so make sure that it works safely and that any
  33530. pointers that it uses are safely within scope.
  33531. @see showAt
  33532. */
  33533. int show (int itemIdThatMustBeVisible = 0,
  33534. int minimumWidth = 0,
  33535. int maximumNumColumns = 0,
  33536. int standardItemHeight = 0,
  33537. ModalComponentManager::Callback* callback = nullptr);
  33538. /** Displays the menu at a specific location.
  33539. This is the same as show(), but uses a specific location (in global screen
  33540. co-ordinates) rather than the current mouse position.
  33541. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  33542. will be adjacent. Depending on where this is, the menu will decide which edge to
  33543. attach itself to, in order to fit itself fully on-screen. If you just want to
  33544. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  33545. with the position that you want.
  33546. @see show()
  33547. */
  33548. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  33549. int itemIdThatMustBeVisible = 0,
  33550. int minimumWidth = 0,
  33551. int maximumNumColumns = 0,
  33552. int standardItemHeight = 0,
  33553. ModalComponentManager::Callback* callback = nullptr);
  33554. /** Displays the menu as if it's attached to a component such as a button.
  33555. This is similar to showAt(), but will position it next to the given component, e.g.
  33556. so that the menu's edge is aligned with that of the component. This is intended for
  33557. things like buttons that trigger a pop-up menu.
  33558. */
  33559. int showAt (Component* componentToAttachTo,
  33560. int itemIdThatMustBeVisible = 0,
  33561. int minimumWidth = 0,
  33562. int maximumNumColumns = 0,
  33563. int standardItemHeight = 0,
  33564. ModalComponentManager::Callback* callback = nullptr);
  33565. /** Displays and runs the menu modally, with a set of options.
  33566. */
  33567. int showMenu (const Options& options);
  33568. #endif
  33569. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  33570. void showMenuAsync (const Options& options,
  33571. ModalComponentManager::Callback* callback);
  33572. /** Closes any menus that are currently open.
  33573. This might be useful if you have a situation where your window is being closed
  33574. by some means other than a user action, and you'd like to make sure that menus
  33575. aren't left hanging around.
  33576. */
  33577. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  33578. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  33579. This can be called before show() if you need a customised menu. Be careful
  33580. not to delete the LookAndFeel object before the menu has been deleted.
  33581. */
  33582. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  33583. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  33584. These constants can be used either via the LookAndFeel::setColour()
  33585. method for the look and feel that is set for this menu with setLookAndFeel()
  33586. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  33587. */
  33588. enum ColourIds
  33589. {
  33590. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  33591. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  33592. colour is specified when the item is added). */
  33593. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  33594. addSectionHeader() method). */
  33595. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  33596. highlighted menu item. */
  33597. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  33598. highlighted item. */
  33599. };
  33600. /**
  33601. Allows you to iterate through the items in a pop-up menu, and examine
  33602. their properties.
  33603. To use this, just create one and repeatedly call its next() method. When this
  33604. returns true, all the member variables of the iterator are filled-out with
  33605. information describing the menu item. When it returns false, the end of the
  33606. list has been reached.
  33607. */
  33608. class JUCE_API MenuItemIterator
  33609. {
  33610. public:
  33611. /** Creates an iterator that will scan through the items in the specified
  33612. menu.
  33613. Be careful not to add any items to a menu while it is being iterated,
  33614. or things could get out of step.
  33615. */
  33616. MenuItemIterator (const PopupMenu& menu);
  33617. /** Destructor. */
  33618. ~MenuItemIterator();
  33619. /** Returns true if there is another item, and sets up all this object's
  33620. member variables to reflect that item's properties.
  33621. */
  33622. bool next();
  33623. String itemName;
  33624. const PopupMenu* subMenu;
  33625. int itemId;
  33626. bool isSeparator;
  33627. bool isTicked;
  33628. bool isEnabled;
  33629. bool isCustomComponent;
  33630. bool isSectionHeader;
  33631. const Colour* customColour;
  33632. Image customImage;
  33633. ApplicationCommandManager* commandManager;
  33634. private:
  33635. const PopupMenu& menu;
  33636. int index;
  33637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  33638. };
  33639. /** A user-defined copmonent that can be used as an item in a popup menu.
  33640. @see PopupMenu::addCustomItem
  33641. */
  33642. class JUCE_API CustomComponent : public Component,
  33643. public SingleThreadedReferenceCountedObject
  33644. {
  33645. public:
  33646. /** Creates a custom item.
  33647. If isTriggeredAutomatically is true, then the menu will automatically detect
  33648. a mouse-click on this component and use that to invoke the menu item. If it's
  33649. false, then it's up to your class to manually trigger the item when it wants to.
  33650. */
  33651. CustomComponent (bool isTriggeredAutomatically = true);
  33652. /** Destructor. */
  33653. ~CustomComponent();
  33654. /** Returns a rectangle with the size that this component would like to have.
  33655. Note that the size which this method returns isn't necessarily the one that
  33656. the menu will give it, as the items will be stretched to have a uniform width.
  33657. */
  33658. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  33659. /** Dismisses the menu, indicating that this item has been chosen.
  33660. This will cause the menu to exit from its modal state, returning
  33661. this item's id as the result.
  33662. */
  33663. void triggerMenuItem();
  33664. /** Returns true if this item should be highlighted because the mouse is over it.
  33665. You can call this method in your paint() method to find out whether
  33666. to draw a highlight.
  33667. */
  33668. bool isItemHighlighted() const noexcept { return isHighlighted; }
  33669. /** @internal */
  33670. bool isTriggeredAutomatically() const noexcept { return triggeredAutomatically; }
  33671. /** @internal */
  33672. void setHighlighted (bool shouldBeHighlighted);
  33673. private:
  33674. bool isHighlighted, triggeredAutomatically;
  33675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  33676. };
  33677. /** Appends a custom menu item.
  33678. This will add a user-defined component to use as a menu item. The component
  33679. passed in will be deleted by this menu when it's no longer needed.
  33680. @see CustomComponent
  33681. */
  33682. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  33683. private:
  33684. class Item;
  33685. class ItemComponent;
  33686. class Window;
  33687. friend class MenuItemIterator;
  33688. friend class ItemComponent;
  33689. friend class Window;
  33690. friend class CustomComponent;
  33691. friend class MenuBarComponent;
  33692. friend class OwnedArray <Item>;
  33693. friend class OwnedArray <ItemComponent>;
  33694. friend class ScopedPointer <Window>;
  33695. OwnedArray <Item> items;
  33696. LookAndFeel* lookAndFeel;
  33697. bool separatorPending;
  33698. void addSeparatorIfPending();
  33699. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  33700. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  33701. JUCE_LEAK_DETECTOR (PopupMenu);
  33702. };
  33703. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  33704. /*** End of inlined file: juce_PopupMenu.h ***/
  33705. /**
  33706. Manages a list of plugin types.
  33707. This can be easily edited, saved and loaded, and used to create instances of
  33708. the plugin types in it.
  33709. @see PluginListComponent
  33710. */
  33711. class JUCE_API KnownPluginList : public ChangeBroadcaster
  33712. {
  33713. public:
  33714. /** Creates an empty list.
  33715. */
  33716. KnownPluginList();
  33717. /** Destructor. */
  33718. ~KnownPluginList();
  33719. /** Clears the list. */
  33720. void clear();
  33721. /** Returns the number of types currently in the list.
  33722. @see getType
  33723. */
  33724. int getNumTypes() const noexcept { return types.size(); }
  33725. /** Returns one of the types.
  33726. @see getNumTypes
  33727. */
  33728. PluginDescription* getType (int index) const noexcept { return types [index]; }
  33729. /** Looks for a type in the list which comes from this file.
  33730. */
  33731. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  33732. /** Looks for a type in the list which matches a plugin type ID.
  33733. The identifierString parameter must have been created by
  33734. PluginDescription::createIdentifierString().
  33735. */
  33736. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  33737. /** Adds a type manually from its description. */
  33738. bool addType (const PluginDescription& type);
  33739. /** Removes a type. */
  33740. void removeType (int index);
  33741. /** Looks for all types that can be loaded from a given file, and adds them
  33742. to the list.
  33743. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  33744. re-tested if it's not already in the list, or if the file's modification
  33745. time has changed since the list was created. If dontRescanIfAlreadyInList is
  33746. false, the file will always be reloaded and tested.
  33747. Returns true if any new types were added, and all the types found in this
  33748. file (even if it was already known and hasn't been re-scanned) get returned
  33749. in the array.
  33750. */
  33751. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  33752. bool dontRescanIfAlreadyInList,
  33753. OwnedArray <PluginDescription>& typesFound,
  33754. AudioPluginFormat& formatToUse);
  33755. /** Returns true if the specified file is already known about and if it
  33756. hasn't been modified since our entry was created.
  33757. */
  33758. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  33759. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  33760. If any types are found in the files, their descriptions are returned in the array.
  33761. */
  33762. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  33763. OwnedArray <PluginDescription>& typesFound);
  33764. /** Sort methods used to change the order of the plugins in the list.
  33765. */
  33766. enum SortMethod
  33767. {
  33768. defaultOrder = 0,
  33769. sortAlphabetically,
  33770. sortByCategory,
  33771. sortByManufacturer,
  33772. sortByFileSystemLocation
  33773. };
  33774. /** Adds all the plugin types to a popup menu so that the user can select one.
  33775. Depending on the sort method, it may add sub-menus for categories,
  33776. manufacturers, etc.
  33777. Use getIndexChosenByMenu() to find out the type that was chosen.
  33778. */
  33779. void addToMenu (PopupMenu& menu,
  33780. const SortMethod sortMethod) const;
  33781. /** Converts a menu item index that has been chosen into its index in this list.
  33782. Returns -1 if it's not an ID that was used.
  33783. @see addToMenu
  33784. */
  33785. int getIndexChosenByMenu (int menuResultCode) const;
  33786. /** Sorts the list. */
  33787. void sort (const SortMethod method);
  33788. /** Creates some XML that can be used to store the state of this list.
  33789. */
  33790. XmlElement* createXml() const;
  33791. /** Recreates the state of this list from its stored XML format.
  33792. */
  33793. void recreateFromXml (const XmlElement& xml);
  33794. private:
  33795. OwnedArray <PluginDescription> types;
  33796. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  33797. };
  33798. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33799. /*** End of inlined file: juce_KnownPluginList.h ***/
  33800. #endif
  33801. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33802. #endif
  33803. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33804. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  33805. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33806. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33807. /**
  33808. Scans a directory for plugins, and adds them to a KnownPluginList.
  33809. To use one of these, create it and call scanNextFile() repeatedly, until
  33810. it returns false.
  33811. */
  33812. class JUCE_API PluginDirectoryScanner
  33813. {
  33814. public:
  33815. /**
  33816. Creates a scanner.
  33817. @param listToAddResultsTo this will get the new types added to it.
  33818. @param formatToLookFor this is the type of format that you want to look for
  33819. @param directoriesToSearch the path to search
  33820. @param searchRecursively true to search recursively
  33821. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  33822. be used as a file to store the names of any plugins
  33823. that crash during initialisation. If there are
  33824. any plugins listed in it, then these will always
  33825. be scanned after all other possible files have
  33826. been tried - in this way, even if there's a few
  33827. dodgy plugins in your path, then a couple of rescans
  33828. will still manage to find all the proper plugins.
  33829. It's probably best to choose a file in the user's
  33830. application data directory (alongside your app's
  33831. settings file) for this. The file format it uses
  33832. is just a list of filenames of the modules that
  33833. failed.
  33834. */
  33835. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  33836. AudioPluginFormat& formatToLookFor,
  33837. FileSearchPath directoriesToSearch,
  33838. bool searchRecursively,
  33839. const File& deadMansPedalFile);
  33840. /** Destructor. */
  33841. ~PluginDirectoryScanner();
  33842. /** Tries the next likely-looking file.
  33843. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  33844. re-tested if it's not already in the list, or if the file's modification
  33845. time has changed since the list was created. If dontRescanIfAlreadyInList is
  33846. false, the file will always be reloaded and tested.
  33847. Returns false when there are no more files to try.
  33848. */
  33849. bool scanNextFile (bool dontRescanIfAlreadyInList);
  33850. /** Skips over the next file without scanning it.
  33851. Returns false when there are no more files to try.
  33852. */
  33853. bool skipNextFile();
  33854. /** Returns the description of the plugin that will be scanned during the next
  33855. call to scanNextFile().
  33856. This is handy if you want to show the user which file is currently getting
  33857. scanned.
  33858. */
  33859. const String getNextPluginFileThatWillBeScanned() const;
  33860. /** Returns the estimated progress, between 0 and 1.
  33861. */
  33862. float getProgress() const { return progress; }
  33863. /** This returns a list of all the filenames of things that looked like being
  33864. a plugin file, but which failed to open for some reason.
  33865. */
  33866. const StringArray& getFailedFiles() const noexcept { return failedFiles; }
  33867. private:
  33868. KnownPluginList& list;
  33869. AudioPluginFormat& format;
  33870. StringArray filesOrIdentifiersToScan;
  33871. File deadMansPedalFile;
  33872. StringArray failedFiles;
  33873. int nextIndex;
  33874. float progress;
  33875. StringArray getDeadMansPedalFile();
  33876. void setDeadMansPedalFile (const StringArray& newContents);
  33877. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  33878. };
  33879. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33880. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  33881. #endif
  33882. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33883. /*** Start of inlined file: juce_PluginListComponent.h ***/
  33884. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33885. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33886. /*** Start of inlined file: juce_ListBox.h ***/
  33887. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33888. #define __JUCE_LISTBOX_JUCEHEADER__
  33889. /*** Start of inlined file: juce_Viewport.h ***/
  33890. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  33891. #define __JUCE_VIEWPORT_JUCEHEADER__
  33892. /*** Start of inlined file: juce_ScrollBar.h ***/
  33893. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  33894. #define __JUCE_SCROLLBAR_JUCEHEADER__
  33895. /*** Start of inlined file: juce_Button.h ***/
  33896. #ifndef __JUCE_BUTTON_JUCEHEADER__
  33897. #define __JUCE_BUTTON_JUCEHEADER__
  33898. /*** Start of inlined file: juce_TooltipWindow.h ***/
  33899. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33900. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33901. /*** Start of inlined file: juce_TooltipClient.h ***/
  33902. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33903. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33904. /**
  33905. Components that want to use pop-up tooltips should implement this interface.
  33906. A TooltipWindow will wait for the mouse to hover over a component that
  33907. implements the TooltipClient interface, and when it finds one, it will display
  33908. the tooltip returned by its getTooltip() method.
  33909. @see TooltipWindow, SettableTooltipClient
  33910. */
  33911. class JUCE_API TooltipClient
  33912. {
  33913. public:
  33914. /** Destructor. */
  33915. virtual ~TooltipClient() {}
  33916. /** Returns the string that this object wants to show as its tooltip. */
  33917. virtual const String getTooltip() = 0;
  33918. };
  33919. /**
  33920. An implementation of TooltipClient that stores the tooltip string and a method
  33921. for changing it.
  33922. This makes it easy to add a tooltip to a custom component, by simply adding this
  33923. as a base class and calling setTooltip().
  33924. Many of the Juce widgets already use this as a base class to implement their
  33925. tooltips.
  33926. @see TooltipClient, TooltipWindow
  33927. */
  33928. class JUCE_API SettableTooltipClient : public TooltipClient
  33929. {
  33930. public:
  33931. /** Destructor. */
  33932. virtual ~SettableTooltipClient() {}
  33933. /** Assigns a new tooltip to this object. */
  33934. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  33935. /** Returns the tooltip assigned to this object. */
  33936. virtual const String getTooltip() { return tooltipString; }
  33937. protected:
  33938. SettableTooltipClient() {}
  33939. private:
  33940. String tooltipString;
  33941. };
  33942. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33943. /*** End of inlined file: juce_TooltipClient.h ***/
  33944. /**
  33945. A window that displays a pop-up tooltip when the mouse hovers over another component.
  33946. To enable tooltips in your app, just create a single instance of a TooltipWindow
  33947. object.
  33948. The TooltipWindow object will then stay invisible, waiting until the mouse
  33949. hovers for the specified length of time - it will then see if it's currently
  33950. over a component which implements the TooltipClient interface, and if so,
  33951. it will make itself visible to show the tooltip in the appropriate place.
  33952. @see TooltipClient, SettableTooltipClient
  33953. */
  33954. class JUCE_API TooltipWindow : public Component,
  33955. private Timer
  33956. {
  33957. public:
  33958. /** Creates a tooltip window.
  33959. Make sure your app only creates one instance of this class, otherwise you'll
  33960. get multiple overlaid tooltips appearing. The window will initially be invisible
  33961. and will make itself visible when it needs to display a tip.
  33962. To change the style of tooltips, see the LookAndFeel class for its tooltip
  33963. methods.
  33964. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  33965. otherwise the tooltip will be added to the given parent
  33966. component.
  33967. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  33968. before a tooltip will be shown
  33969. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  33970. */
  33971. explicit TooltipWindow (Component* parentComponent = nullptr,
  33972. int millisecondsBeforeTipAppears = 700);
  33973. /** Destructor. */
  33974. ~TooltipWindow();
  33975. /** Changes the time before the tip appears.
  33976. This lets you change the value that was set in the constructor.
  33977. */
  33978. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) noexcept;
  33979. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  33980. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33981. methods.
  33982. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33983. */
  33984. enum ColourIds
  33985. {
  33986. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  33987. textColourId = 0x1001c00, /**< The colour to use for the text. */
  33988. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  33989. };
  33990. private:
  33991. int millisecondsBeforeTipAppears;
  33992. Point<int> lastMousePos;
  33993. int mouseClicks;
  33994. unsigned int lastCompChangeTime, lastHideTime;
  33995. Component* lastComponentUnderMouse;
  33996. bool changedCompsSinceShown;
  33997. String tipShowing, lastTipUnderMouse;
  33998. void paint (Graphics& g);
  33999. void mouseEnter (const MouseEvent& e);
  34000. void timerCallback();
  34001. static String getTipFor (Component* c);
  34002. void showFor (const String& tip);
  34003. void hide();
  34004. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  34005. };
  34006. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  34007. /*** End of inlined file: juce_TooltipWindow.h ***/
  34008. #if JUCE_VC6
  34009. #define Listener ButtonListener
  34010. #endif
  34011. /**
  34012. A base class for buttons.
  34013. This contains all the logic for button behaviours such as enabling/disabling,
  34014. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  34015. and radio groups, etc.
  34016. @see TextButton, DrawableButton, ToggleButton
  34017. */
  34018. class JUCE_API Button : public Component,
  34019. public SettableTooltipClient,
  34020. public ApplicationCommandManagerListener,
  34021. public ValueListener,
  34022. private KeyListener
  34023. {
  34024. protected:
  34025. /** Creates a button.
  34026. @param buttonName the text to put in the button (the component's name is also
  34027. initially set to this string, but these can be changed later
  34028. using the setName() and setButtonText() methods)
  34029. */
  34030. explicit Button (const String& buttonName);
  34031. public:
  34032. /** Destructor. */
  34033. virtual ~Button();
  34034. /** Changes the button's text.
  34035. @see getButtonText
  34036. */
  34037. void setButtonText (const String& newText);
  34038. /** Returns the text displayed in the button.
  34039. @see setButtonText
  34040. */
  34041. const String getButtonText() const { return text; }
  34042. /** Returns true if the button is currently being held down by the mouse.
  34043. @see isOver
  34044. */
  34045. bool isDown() const noexcept;
  34046. /** Returns true if the mouse is currently over the button.
  34047. This will be also be true if the mouse is being held down.
  34048. @see isDown
  34049. */
  34050. bool isOver() const noexcept;
  34051. /** A button has an on/off state associated with it, and this changes that.
  34052. By default buttons are 'off' and for simple buttons that you click to perform
  34053. an action you won't change this. Toggle buttons, however will want to
  34054. change their state when turned on or off.
  34055. @param shouldBeOn whether to set the button's toggle state to be on or
  34056. off. If it's a member of a button group, this will
  34057. always try to turn it on, and to turn off any other
  34058. buttons in the group
  34059. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  34060. the button will be repainted but no notification will
  34061. be sent
  34062. @see getToggleState, setRadioGroupId
  34063. */
  34064. void setToggleState (bool shouldBeOn,
  34065. bool sendChangeNotification);
  34066. /** Returns true if the button in 'on'.
  34067. By default buttons are 'off' and for simple buttons that you click to perform
  34068. an action you won't change this. Toggle buttons, however will want to
  34069. change their state when turned on or off.
  34070. @see setToggleState
  34071. */
  34072. bool getToggleState() const noexcept { return isOn.getValue(); }
  34073. /** Returns the Value object that represents the botton's toggle state.
  34074. You can use this Value object to connect the button's state to external values or setters,
  34075. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34076. your own Value object.
  34077. @see getToggleState, Value
  34078. */
  34079. Value& getToggleStateValue() { return isOn; }
  34080. /** This tells the button to automatically flip the toggle state when
  34081. the button is clicked.
  34082. If set to true, then before the clicked() callback occurs, the toggle-state
  34083. of the button is flipped.
  34084. */
  34085. void setClickingTogglesState (bool shouldToggle) noexcept;
  34086. /** Returns true if this button is set to be an automatic toggle-button.
  34087. This returns the last value that was passed to setClickingTogglesState().
  34088. */
  34089. bool getClickingTogglesState() const noexcept;
  34090. /** Enables the button to act as a member of a mutually-exclusive group
  34091. of 'radio buttons'.
  34092. If the group ID is set to a non-zero number, then this button will
  34093. act as part of a group of buttons with the same ID, only one of
  34094. which can be 'on' at the same time. Note that when it's part of
  34095. a group, clicking a toggle-button that's 'on' won't turn it off.
  34096. To find other buttons with the same ID, this button will search through
  34097. its sibling components for ToggleButtons, so all the buttons for a
  34098. particular group must be placed inside the same parent component.
  34099. Set the group ID back to zero if you want it to act as a normal toggle
  34100. button again.
  34101. @see getRadioGroupId
  34102. */
  34103. void setRadioGroupId (int newGroupId);
  34104. /** Returns the ID of the group to which this button belongs.
  34105. (See setRadioGroupId() for an explanation of this).
  34106. */
  34107. int getRadioGroupId() const noexcept { return radioGroupId; }
  34108. /**
  34109. Used to receive callbacks when a button is clicked.
  34110. @see Button::addListener, Button::removeListener
  34111. */
  34112. class JUCE_API Listener
  34113. {
  34114. public:
  34115. /** Destructor. */
  34116. virtual ~Listener() {}
  34117. /** Called when the button is clicked. */
  34118. virtual void buttonClicked (Button* button) = 0;
  34119. /** Called when the button's state changes. */
  34120. virtual void buttonStateChanged (Button*) {}
  34121. };
  34122. /** Registers a listener to receive events when this button's state changes.
  34123. If the listener is already registered, this will not register it again.
  34124. @see removeListener
  34125. */
  34126. void addListener (Listener* newListener);
  34127. /** Removes a previously-registered button listener
  34128. @see addListener
  34129. */
  34130. void removeListener (Listener* listener);
  34131. /** Causes the button to act as if it's been clicked.
  34132. This will asynchronously make the button draw itself going down and up, and
  34133. will then call back the clicked() method as if mouse was clicked on it.
  34134. @see clicked
  34135. */
  34136. virtual void triggerClick();
  34137. /** Sets a command ID for this button to automatically invoke when it's clicked.
  34138. When the button is pressed, it will use the given manager to trigger the
  34139. command ID.
  34140. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  34141. before this button is. To disable the command triggering, call this method and
  34142. pass 0 for the parameters.
  34143. If generateTooltip is true, then the button's tooltip will be automatically
  34144. generated based on the name of this command and its current shortcut key.
  34145. @see addShortcut, getCommandID
  34146. */
  34147. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  34148. int commandID,
  34149. bool generateTooltip);
  34150. /** Returns the command ID that was set by setCommandToTrigger().
  34151. */
  34152. int getCommandID() const noexcept { return commandID; }
  34153. /** Assigns a shortcut key to trigger the button.
  34154. The button registers itself with its top-level parent component for keypresses.
  34155. Note that a different way of linking buttons to keypresses is by using the
  34156. setCommandToTrigger() method to invoke a command.
  34157. @see clearShortcuts
  34158. */
  34159. void addShortcut (const KeyPress& key);
  34160. /** Removes all key shortcuts that had been set for this button.
  34161. @see addShortcut
  34162. */
  34163. void clearShortcuts();
  34164. /** Returns true if the given keypress is a shortcut for this button.
  34165. @see addShortcut
  34166. */
  34167. bool isRegisteredForShortcut (const KeyPress& key) const;
  34168. /** Sets an auto-repeat speed for the button when it is held down.
  34169. (Auto-repeat is disabled by default).
  34170. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  34171. triggering the next click. If this is zero, auto-repeat
  34172. is disabled
  34173. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  34174. triggered
  34175. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  34176. get faster, the longer the button is held down, up to the
  34177. minimum interval specified here
  34178. */
  34179. void setRepeatSpeed (int initialDelayInMillisecs,
  34180. int repeatDelayInMillisecs,
  34181. int minimumDelayInMillisecs = -1) noexcept;
  34182. /** Sets whether the button click should happen when the mouse is pressed or released.
  34183. By default the button is only considered to have been clicked when the mouse is
  34184. released, but setting this to true will make it call the clicked() method as soon
  34185. as the button is pressed.
  34186. This is useful if the button is being used to show a pop-up menu, as it allows
  34187. the click to be used as a drag onto the menu.
  34188. */
  34189. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) noexcept;
  34190. /** Returns the number of milliseconds since the last time the button
  34191. went into the 'down' state.
  34192. */
  34193. uint32 getMillisecondsSinceButtonDown() const noexcept;
  34194. /** Sets the tooltip for this button.
  34195. @see TooltipClient, TooltipWindow
  34196. */
  34197. void setTooltip (const String& newTooltip);
  34198. // (implementation of the TooltipClient method)
  34199. const String getTooltip();
  34200. /** A combination of these flags are used by setConnectedEdges().
  34201. */
  34202. enum ConnectedEdgeFlags
  34203. {
  34204. ConnectedOnLeft = 1,
  34205. ConnectedOnRight = 2,
  34206. ConnectedOnTop = 4,
  34207. ConnectedOnBottom = 8
  34208. };
  34209. /** Hints about which edges of the button might be connected to adjoining buttons.
  34210. The value passed in is a bitwise combination of any of the values in the
  34211. ConnectedEdgeFlags enum.
  34212. E.g. if you are placing two buttons adjacent to each other, you could use this to
  34213. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  34214. without rounded corners on the edges that connect. It's only a hint, so the
  34215. LookAndFeel can choose to ignore it if it's not relevent for this type of
  34216. button.
  34217. */
  34218. void setConnectedEdges (int connectedEdgeFlags);
  34219. /** Returns the set of flags passed into setConnectedEdges(). */
  34220. int getConnectedEdgeFlags() const noexcept { return connectedEdgeFlags; }
  34221. /** Indicates whether the button adjoins another one on its left edge.
  34222. @see setConnectedEdges
  34223. */
  34224. bool isConnectedOnLeft() const noexcept { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  34225. /** Indicates whether the button adjoins another one on its right edge.
  34226. @see setConnectedEdges
  34227. */
  34228. bool isConnectedOnRight() const noexcept { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  34229. /** Indicates whether the button adjoins another one on its top edge.
  34230. @see setConnectedEdges
  34231. */
  34232. bool isConnectedOnTop() const noexcept { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  34233. /** Indicates whether the button adjoins another one on its bottom edge.
  34234. @see setConnectedEdges
  34235. */
  34236. bool isConnectedOnBottom() const noexcept { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  34237. /** Used by setState(). */
  34238. enum ButtonState
  34239. {
  34240. buttonNormal,
  34241. buttonOver,
  34242. buttonDown
  34243. };
  34244. /** Can be used to force the button into a particular state.
  34245. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  34246. from happening.
  34247. The state that you set here will only last until it is automatically changed when the mouse
  34248. enters or exits the button, or the mouse-button is pressed or released.
  34249. */
  34250. void setState (const ButtonState newState);
  34251. // These are deprecated - please use addListener() and removeListener() instead!
  34252. JUCE_DEPRECATED (void addButtonListener (Listener*));
  34253. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  34254. protected:
  34255. /** This method is called when the button has been clicked.
  34256. Subclasses can override this to perform whatever they actions they need
  34257. to do.
  34258. Alternatively, a ButtonListener can be added to the button, and these listeners
  34259. will be called when the click occurs.
  34260. @see triggerClick
  34261. */
  34262. virtual void clicked();
  34263. /** This method is called when the button has been clicked.
  34264. By default it just calls clicked(), but you might want to override it to handle
  34265. things like clicking when a modifier key is pressed, etc.
  34266. @see ModifierKeys
  34267. */
  34268. virtual void clicked (const ModifierKeys& modifiers);
  34269. /** Subclasses should override this to actually paint the button's contents.
  34270. It's better to use this than the paint method, because it gives you information
  34271. about the over/down state of the button.
  34272. @param g the graphics context to use
  34273. @param isMouseOverButton true if the button is either in the 'over' or
  34274. 'down' state
  34275. @param isButtonDown true if the button should be drawn in the 'down' position
  34276. */
  34277. virtual void paintButton (Graphics& g,
  34278. bool isMouseOverButton,
  34279. bool isButtonDown) = 0;
  34280. /** Called when the button's up/down/over state changes.
  34281. Subclasses can override this if they need to do something special when the button
  34282. goes up or down.
  34283. @see isDown, isOver
  34284. */
  34285. virtual void buttonStateChanged();
  34286. /** @internal */
  34287. virtual void internalClickCallback (const ModifierKeys& modifiers);
  34288. /** @internal */
  34289. void handleCommandMessage (int commandId);
  34290. /** @internal */
  34291. void mouseEnter (const MouseEvent& e);
  34292. /** @internal */
  34293. void mouseExit (const MouseEvent& e);
  34294. /** @internal */
  34295. void mouseDown (const MouseEvent& e);
  34296. /** @internal */
  34297. void mouseDrag (const MouseEvent& e);
  34298. /** @internal */
  34299. void mouseUp (const MouseEvent& e);
  34300. /** @internal */
  34301. bool keyPressed (const KeyPress& key);
  34302. /** @internal */
  34303. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  34304. /** @internal */
  34305. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  34306. /** @internal */
  34307. void paint (Graphics& g);
  34308. /** @internal */
  34309. void parentHierarchyChanged();
  34310. /** @internal */
  34311. void visibilityChanged();
  34312. /** @internal */
  34313. void focusGained (FocusChangeType cause);
  34314. /** @internal */
  34315. void focusLost (FocusChangeType cause);
  34316. /** @internal */
  34317. void enablementChanged();
  34318. /** @internal */
  34319. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  34320. /** @internal */
  34321. void applicationCommandListChanged();
  34322. /** @internal */
  34323. void valueChanged (Value& value);
  34324. private:
  34325. Array <KeyPress> shortcuts;
  34326. WeakReference<Component> keySource;
  34327. String text;
  34328. ListenerList <Listener> buttonListeners;
  34329. class RepeatTimer;
  34330. friend class RepeatTimer;
  34331. friend class ScopedPointer <RepeatTimer>;
  34332. ScopedPointer <RepeatTimer> repeatTimer;
  34333. uint32 buttonPressTime, lastRepeatTime;
  34334. ApplicationCommandManager* commandManagerToUse;
  34335. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  34336. int radioGroupId, commandID, connectedEdgeFlags;
  34337. ButtonState buttonState;
  34338. Value isOn;
  34339. bool lastToggleState : 1;
  34340. bool clickTogglesState : 1;
  34341. bool needsToRelease : 1;
  34342. bool needsRepainting : 1;
  34343. bool isKeyDown : 1;
  34344. bool triggerOnMouseDown : 1;
  34345. bool generateTooltip : 1;
  34346. void repeatTimerCallback();
  34347. RepeatTimer& getRepeatTimer();
  34348. ButtonState updateState();
  34349. ButtonState updateState (bool isOver, bool isDown);
  34350. bool isShortcutPressed() const;
  34351. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  34352. void flashButtonState();
  34353. void sendClickMessage (const ModifierKeys& modifiers);
  34354. void sendStateMessage();
  34355. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  34356. };
  34357. #ifndef DOXYGEN
  34358. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  34359. typedef Button::Listener ButtonListener;
  34360. #endif
  34361. #if JUCE_VC6
  34362. #undef Listener
  34363. #endif
  34364. #endif // __JUCE_BUTTON_JUCEHEADER__
  34365. /*** End of inlined file: juce_Button.h ***/
  34366. /**
  34367. A scrollbar component.
  34368. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  34369. sets the range of values it can represent. Then you can use setCurrentRange() to
  34370. change the position and size of the scrollbar's 'thumb'.
  34371. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  34372. the user moves it, and you can use the getCurrentRangeStart() to find out where
  34373. they moved it to.
  34374. The scrollbar will adjust its own visibility according to whether its thumb size
  34375. allows it to actually be scrolled.
  34376. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  34377. instead of handling a scrollbar directly.
  34378. @see ScrollBar::Listener
  34379. */
  34380. class JUCE_API ScrollBar : public Component,
  34381. public AsyncUpdater,
  34382. private Timer
  34383. {
  34384. public:
  34385. /** Creates a Scrollbar.
  34386. @param isVertical whether it should be a vertical or horizontal bar
  34387. @param buttonsAreVisible whether to show the up/down or left/right buttons
  34388. */
  34389. ScrollBar (bool isVertical,
  34390. bool buttonsAreVisible = true);
  34391. /** Destructor. */
  34392. ~ScrollBar();
  34393. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  34394. bool isVertical() const noexcept { return vertical; }
  34395. /** Changes the scrollbar's direction.
  34396. You'll also need to resize the bar appropriately - this just changes its internal
  34397. layout.
  34398. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  34399. */
  34400. void setOrientation (bool shouldBeVertical);
  34401. /** Shows or hides the scrollbar's buttons. */
  34402. void setButtonVisibility (bool buttonsAreVisible);
  34403. /** Tells the scrollbar whether to make itself invisible when not needed.
  34404. The default behaviour is for a scrollbar to become invisible when the thumb
  34405. fills the whole of its range (i.e. when it can't be moved). Setting this
  34406. value to false forces the bar to always be visible.
  34407. @see autoHides()
  34408. */
  34409. void setAutoHide (bool shouldHideWhenFullRange);
  34410. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  34411. as its maximum range.
  34412. @see setAutoHide
  34413. */
  34414. bool autoHides() const noexcept;
  34415. /** Sets the minimum and maximum values that the bar will move between.
  34416. The bar's thumb will always be constrained so that the entire thumb lies
  34417. within this range.
  34418. @see setCurrentRange
  34419. */
  34420. void setRangeLimits (const Range<double>& newRangeLimit);
  34421. /** Sets the minimum and maximum values that the bar will move between.
  34422. The bar's thumb will always be constrained so that the entire thumb lies
  34423. within this range.
  34424. @see setCurrentRange
  34425. */
  34426. void setRangeLimits (double minimum, double maximum);
  34427. /** Returns the current limits on the thumb position.
  34428. @see setRangeLimits
  34429. */
  34430. const Range<double> getRangeLimit() const noexcept { return totalRange; }
  34431. /** Returns the lower value that the thumb can be set to.
  34432. This is the value set by setRangeLimits().
  34433. */
  34434. double getMinimumRangeLimit() const noexcept { return totalRange.getStart(); }
  34435. /** Returns the upper value that the thumb can be set to.
  34436. This is the value set by setRangeLimits().
  34437. */
  34438. double getMaximumRangeLimit() const noexcept { return totalRange.getEnd(); }
  34439. /** Changes the position of the scrollbar's 'thumb'.
  34440. If this method call actually changes the scrollbar's position, it will trigger an
  34441. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34442. are registered.
  34443. @see getCurrentRange. setCurrentRangeStart
  34444. */
  34445. void setCurrentRange (const Range<double>& newRange);
  34446. /** Changes the position of the scrollbar's 'thumb'.
  34447. This sets both the position and size of the thumb - to just set the position without
  34448. changing the size, you can use setCurrentRangeStart().
  34449. If this method call actually changes the scrollbar's position, it will trigger an
  34450. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34451. are registered.
  34452. @param newStart the top (or left) of the thumb, in the range
  34453. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  34454. value is beyond these limits, it will be clipped.
  34455. @param newSize the size of the thumb, such that
  34456. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  34457. size is beyond these limits, it will be clipped.
  34458. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  34459. */
  34460. void setCurrentRange (double newStart, double newSize);
  34461. /** Moves the bar's thumb position.
  34462. This will move the thumb position without changing the thumb size. Note
  34463. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  34464. If this method call actually changes the scrollbar's position, it will trigger an
  34465. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34466. are registered.
  34467. @see setCurrentRange
  34468. */
  34469. void setCurrentRangeStart (double newStart);
  34470. /** Returns the current thumb range.
  34471. @see getCurrentRange, setCurrentRange
  34472. */
  34473. const Range<double> getCurrentRange() const noexcept { return visibleRange; }
  34474. /** Returns the position of the top of the thumb.
  34475. @see getCurrentRange, setCurrentRangeStart
  34476. */
  34477. double getCurrentRangeStart() const noexcept { return visibleRange.getStart(); }
  34478. /** Returns the current size of the thumb.
  34479. @see getCurrentRange, setCurrentRange
  34480. */
  34481. double getCurrentRangeSize() const noexcept { return visibleRange.getLength(); }
  34482. /** Sets the amount by which the up and down buttons will move the bar.
  34483. The value here is in terms of the total range, and is added or subtracted
  34484. from the thumb position when the user clicks an up/down (or left/right) button.
  34485. */
  34486. void setSingleStepSize (double newSingleStepSize);
  34487. /** Moves the scrollbar by a number of single-steps.
  34488. This will move the bar by a multiple of its single-step interval (as
  34489. specified using the setSingleStepSize() method).
  34490. A positive value here will move the bar down or to the right, a negative
  34491. value moves it up or to the left.
  34492. */
  34493. void moveScrollbarInSteps (int howManySteps);
  34494. /** Moves the scroll bar up or down in pages.
  34495. This will move the bar by a multiple of its current thumb size, effectively
  34496. doing a page-up or down.
  34497. A positive value here will move the bar down or to the right, a negative
  34498. value moves it up or to the left.
  34499. */
  34500. void moveScrollbarInPages (int howManyPages);
  34501. /** Scrolls to the top (or left).
  34502. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  34503. */
  34504. void scrollToTop();
  34505. /** Scrolls to the bottom (or right).
  34506. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  34507. */
  34508. void scrollToBottom();
  34509. /** Changes the delay before the up and down buttons autorepeat when they are held
  34510. down.
  34511. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  34512. @see Button::setRepeatSpeed
  34513. */
  34514. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  34515. int repeatDelayInMillisecs,
  34516. int minimumDelayInMillisecs = -1);
  34517. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34518. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34519. methods.
  34520. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34521. */
  34522. enum ColourIds
  34523. {
  34524. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  34525. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  34526. 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. */
  34527. };
  34528. /**
  34529. A class for receiving events from a ScrollBar.
  34530. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  34531. method, and it will be called when the bar's position changes.
  34532. @see ScrollBar::addListener, ScrollBar::removeListener
  34533. */
  34534. class JUCE_API Listener
  34535. {
  34536. public:
  34537. /** Destructor. */
  34538. virtual ~Listener() {}
  34539. /** Called when a ScrollBar is moved.
  34540. @param scrollBarThatHasMoved the bar that has moved
  34541. @param newRangeStart the new range start of this bar
  34542. */
  34543. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  34544. double newRangeStart) = 0;
  34545. };
  34546. /** Registers a listener that will be called when the scrollbar is moved. */
  34547. void addListener (Listener* listener);
  34548. /** Deregisters a previously-registered listener. */
  34549. void removeListener (Listener* listener);
  34550. /** @internal */
  34551. bool keyPressed (const KeyPress& key);
  34552. /** @internal */
  34553. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34554. /** @internal */
  34555. void lookAndFeelChanged();
  34556. /** @internal */
  34557. void handleAsyncUpdate();
  34558. /** @internal */
  34559. void mouseDown (const MouseEvent& e);
  34560. /** @internal */
  34561. void mouseDrag (const MouseEvent& e);
  34562. /** @internal */
  34563. void mouseUp (const MouseEvent& e);
  34564. /** @internal */
  34565. void paint (Graphics& g);
  34566. /** @internal */
  34567. void resized();
  34568. private:
  34569. Range <double> totalRange, visibleRange;
  34570. double singleStepSize, dragStartRange;
  34571. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  34572. int dragStartMousePos, lastMousePos;
  34573. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  34574. bool vertical, isDraggingThumb, autohides;
  34575. class ScrollbarButton;
  34576. friend class ScopedPointer<ScrollbarButton>;
  34577. ScopedPointer<ScrollbarButton> upButton, downButton;
  34578. ListenerList <Listener> listeners;
  34579. void updateThumbPosition();
  34580. void timerCallback();
  34581. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  34582. };
  34583. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  34584. typedef ScrollBar::Listener ScrollBarListener;
  34585. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  34586. /*** End of inlined file: juce_ScrollBar.h ***/
  34587. /**
  34588. A Viewport is used to contain a larger child component, and allows the child
  34589. to be automatically scrolled around.
  34590. To use a Viewport, just create one and set the component that goes inside it
  34591. using the setViewedComponent() method. When the child component changes size,
  34592. the Viewport will adjust its scrollbars accordingly.
  34593. A subclass of the viewport can be created which will receive calls to its
  34594. visibleAreaChanged() method when the subcomponent changes position or size.
  34595. */
  34596. class JUCE_API Viewport : public Component,
  34597. private ComponentListener,
  34598. private ScrollBar::Listener
  34599. {
  34600. public:
  34601. /** Creates a Viewport.
  34602. The viewport is initially empty - use the setViewedComponent() method to
  34603. add a child component for it to manage.
  34604. */
  34605. explicit Viewport (const String& componentName = String::empty);
  34606. /** Destructor. */
  34607. ~Viewport();
  34608. /** Sets the component that this viewport will contain and scroll around.
  34609. This will add the given component to this Viewport and position it at (0, 0).
  34610. (Don't add or remove any child components directly using the normal
  34611. Component::addChildComponent() methods).
  34612. @param newViewedComponent the component to add to this viewport, or null to remove
  34613. the current component.
  34614. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  34615. automatically when the viewport is deleted or when a different
  34616. component is added. If false, the caller must manage the lifetime
  34617. of the component
  34618. @see getViewedComponent
  34619. */
  34620. void setViewedComponent (Component* newViewedComponent,
  34621. bool deleteComponentWhenNoLongerNeeded = true);
  34622. /** Returns the component that's currently being used inside the Viewport.
  34623. @see setViewedComponent
  34624. */
  34625. Component* getViewedComponent() const noexcept { return contentComp; }
  34626. /** Changes the position of the viewed component.
  34627. The inner component will be moved so that the pixel at the top left of
  34628. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  34629. within the inner component.
  34630. This will update the scrollbars and might cause a call to visibleAreaChanged().
  34631. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  34632. */
  34633. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  34634. /** Changes the position of the viewed component.
  34635. The inner component will be moved so that the pixel at the top left of
  34636. the viewport will be the pixel at the specified coordinates within the
  34637. inner component.
  34638. This will update the scrollbars and might cause a call to visibleAreaChanged().
  34639. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  34640. */
  34641. void setViewPosition (const Point<int>& newPosition);
  34642. /** Changes the view position as a proportion of the distance it can move.
  34643. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  34644. visible area in the top-left, and (1, 1) would put it as far down and
  34645. to the right as it's possible to go whilst keeping the child component
  34646. on-screen.
  34647. */
  34648. void setViewPositionProportionately (double proportionX, double proportionY);
  34649. /** If the specified position is at the edges of the viewport, this method scrolls
  34650. the viewport to bring that position nearer to the centre.
  34651. Call this if you're dragging an object inside a viewport and want to make it scroll
  34652. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  34653. useful when auto-scrolling.
  34654. @param mouseX the x position, relative to the Viewport's top-left
  34655. @param mouseY the y position, relative to the Viewport's top-left
  34656. @param distanceFromEdge specifies how close to an edge the position needs to be
  34657. before the viewport should scroll in that direction
  34658. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  34659. to scroll by.
  34660. @returns true if the viewport was scrolled
  34661. */
  34662. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  34663. /** Returns the position within the child component of the top-left of its visible area.
  34664. */
  34665. const Point<int> getViewPosition() const noexcept { return lastVisibleArea.getPosition(); }
  34666. /** Returns the position within the child component of the top-left of its visible area.
  34667. @see getViewWidth, setViewPosition
  34668. */
  34669. int getViewPositionX() const noexcept { return lastVisibleArea.getX(); }
  34670. /** Returns the position within the child component of the top-left of its visible area.
  34671. @see getViewHeight, setViewPosition
  34672. */
  34673. int getViewPositionY() const noexcept { return lastVisibleArea.getY(); }
  34674. /** Returns the width of the visible area of the child component.
  34675. This may be less than the width of this Viewport if there's a vertical scrollbar
  34676. or if the child component is itself smaller.
  34677. */
  34678. int getViewWidth() const noexcept { return lastVisibleArea.getWidth(); }
  34679. /** Returns the height of the visible area of the child component.
  34680. This may be less than the height of this Viewport if there's a horizontal scrollbar
  34681. or if the child component is itself smaller.
  34682. */
  34683. int getViewHeight() const noexcept { return lastVisibleArea.getHeight(); }
  34684. /** Returns the width available within this component for the contents.
  34685. This will be the width of the viewport component minus the width of a
  34686. vertical scrollbar (if visible).
  34687. */
  34688. int getMaximumVisibleWidth() const;
  34689. /** Returns the height available within this component for the contents.
  34690. This will be the height of the viewport component minus the space taken up
  34691. by a horizontal scrollbar (if visible).
  34692. */
  34693. int getMaximumVisibleHeight() const;
  34694. /** Callback method that is called when the visible area changes.
  34695. This will be called when the visible area is moved either be scrolling or
  34696. by calls to setViewPosition(), etc.
  34697. */
  34698. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  34699. /** Turns scrollbars on or off.
  34700. If set to false, the scrollbars won't ever appear. When true (the default)
  34701. they will appear only when needed.
  34702. */
  34703. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  34704. bool showHorizontalScrollbarIfNeeded);
  34705. /** True if the vertical scrollbar is enabled.
  34706. @see setScrollBarsShown
  34707. */
  34708. bool isVerticalScrollBarShown() const noexcept { return showVScrollbar; }
  34709. /** True if the horizontal scrollbar is enabled.
  34710. @see setScrollBarsShown
  34711. */
  34712. bool isHorizontalScrollBarShown() const noexcept { return showHScrollbar; }
  34713. /** Changes the width of the scrollbars.
  34714. If this isn't specified, the default width from the LookAndFeel class will be used.
  34715. @see LookAndFeel::getDefaultScrollbarWidth
  34716. */
  34717. void setScrollBarThickness (int thickness);
  34718. /** Returns the thickness of the scrollbars.
  34719. @see setScrollBarThickness
  34720. */
  34721. int getScrollBarThickness() const;
  34722. /** Changes the distance that a single-step click on a scrollbar button
  34723. will move the viewport.
  34724. */
  34725. void setSingleStepSizes (int stepX, int stepY);
  34726. /** Shows or hides the buttons on any scrollbars that are used.
  34727. @see ScrollBar::setButtonVisibility
  34728. */
  34729. void setScrollBarButtonVisibility (bool buttonsVisible);
  34730. /** Returns a pointer to the scrollbar component being used.
  34731. Handy if you need to customise the bar somehow.
  34732. */
  34733. ScrollBar* getVerticalScrollBar() noexcept { return &verticalScrollBar; }
  34734. /** Returns a pointer to the scrollbar component being used.
  34735. Handy if you need to customise the bar somehow.
  34736. */
  34737. ScrollBar* getHorizontalScrollBar() noexcept { return &horizontalScrollBar; }
  34738. /** @internal */
  34739. void resized();
  34740. /** @internal */
  34741. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  34742. /** @internal */
  34743. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34744. /** @internal */
  34745. bool keyPressed (const KeyPress& key);
  34746. /** @internal */
  34747. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34748. /** @internal */
  34749. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34750. private:
  34751. WeakReference<Component> contentComp;
  34752. Rectangle<int> lastVisibleArea;
  34753. int scrollBarThickness;
  34754. int singleStepX, singleStepY;
  34755. bool showHScrollbar, showVScrollbar, deleteContent;
  34756. Component contentHolder;
  34757. ScrollBar verticalScrollBar;
  34758. ScrollBar horizontalScrollBar;
  34759. void updateVisibleArea();
  34760. void deleteContentComp();
  34761. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  34762. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  34763. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  34764. #endif
  34765. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  34766. };
  34767. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  34768. /*** End of inlined file: juce_Viewport.h ***/
  34769. class ListViewport;
  34770. /**
  34771. A subclass of this is used to drive a ListBox.
  34772. @see ListBox
  34773. */
  34774. class JUCE_API ListBoxModel
  34775. {
  34776. public:
  34777. /** Destructor. */
  34778. virtual ~ListBoxModel() {}
  34779. /** This has to return the number of items in the list.
  34780. @see ListBox::getNumRows()
  34781. */
  34782. virtual int getNumRows() = 0;
  34783. /** This method must be implemented to draw a row of the list.
  34784. */
  34785. virtual void paintListBoxItem (int rowNumber,
  34786. Graphics& g,
  34787. int width, int height,
  34788. bool rowIsSelected) = 0;
  34789. /** This is used to create or update a custom component to go in a row of the list.
  34790. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  34791. and handle mouse clicks with listBoxItemClicked().
  34792. This method will be called whenever a custom component might need to be updated - e.g.
  34793. when the table is changed, or TableListBox::updateContent() is called.
  34794. If you don't need a custom component for the specified row, then return 0.
  34795. If you do want a custom component, and the existingComponentToUpdate is null, then
  34796. this method must create a suitable new component and return it.
  34797. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34798. by this method. In this case, the method must either update it to make sure it's correctly representing
  34799. the given row (which may be different from the one that the component was created for), or it can
  34800. delete this component and return a new one.
  34801. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  34802. */
  34803. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  34804. Component* existingComponentToUpdate);
  34805. /** This can be overridden to react to the user clicking on a row.
  34806. @see listBoxItemDoubleClicked
  34807. */
  34808. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  34809. /** This can be overridden to react to the user double-clicking on a row.
  34810. @see listBoxItemClicked
  34811. */
  34812. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  34813. /** This can be overridden to react to the user double-clicking on a part of the list where
  34814. there are no rows.
  34815. @see listBoxItemClicked
  34816. */
  34817. virtual void backgroundClicked();
  34818. /** Override this to be informed when rows are selected or deselected.
  34819. This will be called whenever a row is selected or deselected. If a range of
  34820. rows is selected all at once, this will just be called once for that event.
  34821. @param lastRowSelected the last row that the user selected. If no
  34822. rows are currently selected, this may be -1.
  34823. */
  34824. virtual void selectedRowsChanged (int lastRowSelected);
  34825. /** Override this to be informed when the delete key is pressed.
  34826. If no rows are selected when they press the key, this won't be called.
  34827. @param lastRowSelected the last row that had been selected when they pressed the
  34828. key - if there are multiple selections, this might not be
  34829. very useful
  34830. */
  34831. virtual void deleteKeyPressed (int lastRowSelected);
  34832. /** Override this to be informed when the return key is pressed.
  34833. If no rows are selected when they press the key, this won't be called.
  34834. @param lastRowSelected the last row that had been selected when they pressed the
  34835. key - if there are multiple selections, this might not be
  34836. very useful
  34837. */
  34838. virtual void returnKeyPressed (int lastRowSelected);
  34839. /** Override this to be informed when the list is scrolled.
  34840. This might be caused by the user moving the scrollbar, or by programmatic changes
  34841. to the list position.
  34842. */
  34843. virtual void listWasScrolled();
  34844. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  34845. If this returns a non-null variant then when the user drags a row, the listbox will
  34846. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  34847. a drag-and-drop operation, using this string as the source description, with the listbox
  34848. itself as the source component.
  34849. @see DragAndDropContainer::startDragging
  34850. */
  34851. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34852. /** You can override this to provide tool tips for specific rows.
  34853. @see TooltipClient
  34854. */
  34855. virtual const String getTooltipForRow (int row);
  34856. };
  34857. /**
  34858. A list of items that can be scrolled vertically.
  34859. To create a list, you'll need to create a subclass of ListBoxModel. This can
  34860. either paint each row of the list and respond to events via callbacks, or for
  34861. more specialised tasks, it can supply a custom component to fill each row.
  34862. @see ComboBox, TableListBox
  34863. */
  34864. class JUCE_API ListBox : public Component,
  34865. public SettableTooltipClient
  34866. {
  34867. public:
  34868. /** Creates a ListBox.
  34869. The model pointer passed-in can be null, in which case you can set it later
  34870. with setModel().
  34871. */
  34872. ListBox (const String& componentName = String::empty,
  34873. ListBoxModel* model = 0);
  34874. /** Destructor. */
  34875. ~ListBox();
  34876. /** Changes the current data model to display. */
  34877. void setModel (ListBoxModel* newModel);
  34878. /** Returns the current list model. */
  34879. ListBoxModel* getModel() const noexcept { return model; }
  34880. /** Causes the list to refresh its content.
  34881. Call this when the number of rows in the list changes, or if you want it
  34882. to call refreshComponentForRow() on all the row components.
  34883. This must only be called from the main message thread.
  34884. */
  34885. void updateContent();
  34886. /** Turns on multiple-selection of rows.
  34887. By default this is disabled.
  34888. When your row component gets clicked you'll need to call the
  34889. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  34890. clicked and to get it to do the appropriate selection based on whether
  34891. the ctrl/shift keys are held down.
  34892. */
  34893. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  34894. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  34895. This function is here primarily for the ComboBox class to use, but might be
  34896. useful for some other purpose too.
  34897. */
  34898. void setMouseMoveSelectsRows (bool shouldSelect);
  34899. /** Selects a row.
  34900. If the row is already selected, this won't do anything.
  34901. @param rowNumber the row to select
  34902. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  34903. the selected row is off-screen, it'll scroll to make
  34904. sure that row is on-screen
  34905. @param deselectOthersFirst if true and there are multiple selections, these will
  34906. first be deselected before this item is selected
  34907. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  34908. deselectAllRows, selectRangeOfRows
  34909. */
  34910. void selectRow (int rowNumber,
  34911. bool dontScrollToShowThisRow = false,
  34912. bool deselectOthersFirst = true);
  34913. /** Selects a set of rows.
  34914. This will add these rows to the current selection, so you might need to
  34915. clear the current selection first with deselectAllRows()
  34916. @param firstRow the first row to select (inclusive)
  34917. @param lastRow the last row to select (inclusive)
  34918. */
  34919. void selectRangeOfRows (int firstRow,
  34920. int lastRow);
  34921. /** Deselects a row.
  34922. If it's not currently selected, this will do nothing.
  34923. @see selectRow, deselectAllRows
  34924. */
  34925. void deselectRow (int rowNumber);
  34926. /** Deselects any currently selected rows.
  34927. @see deselectRow
  34928. */
  34929. void deselectAllRows();
  34930. /** Selects or deselects a row.
  34931. If the row's currently selected, this deselects it, and vice-versa.
  34932. */
  34933. void flipRowSelection (int rowNumber);
  34934. /** Returns a sparse set indicating the rows that are currently selected.
  34935. @see setSelectedRows
  34936. */
  34937. const SparseSet<int> getSelectedRows() const;
  34938. /** Sets the rows that should be selected, based on an explicit set of ranges.
  34939. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  34940. method will be called. If it's false, no notification will be sent to the model.
  34941. @see getSelectedRows
  34942. */
  34943. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  34944. bool sendNotificationEventToModel = true);
  34945. /** Checks whether a row is selected.
  34946. */
  34947. bool isRowSelected (int rowNumber) const;
  34948. /** Returns the number of rows that are currently selected.
  34949. @see getSelectedRow, isRowSelected, getLastRowSelected
  34950. */
  34951. int getNumSelectedRows() const;
  34952. /** Returns the row number of a selected row.
  34953. This will return the row number of the Nth selected row. The row numbers returned will
  34954. be sorted in order from low to high.
  34955. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  34956. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  34957. selected
  34958. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  34959. */
  34960. int getSelectedRow (int index = 0) const;
  34961. /** Returns the last row that the user selected.
  34962. This isn't the same as the highest row number that is currently selected - if the user
  34963. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  34964. If nothing is selected, it will return -1.
  34965. */
  34966. int getLastRowSelected() const;
  34967. /** Multiply-selects rows based on the modifier keys.
  34968. If no modifier keys are down, this will select the given row and
  34969. deselect any others.
  34970. If the ctrl (or command on the Mac) key is down, it'll flip the
  34971. state of the selected row.
  34972. If the shift key is down, it'll select up to the given row from the
  34973. last row selected.
  34974. @see selectRow
  34975. */
  34976. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  34977. const ModifierKeys& modifiers,
  34978. bool isMouseUpEvent);
  34979. /** Scrolls the list to a particular position.
  34980. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  34981. 1.0 scrolls to the bottom.
  34982. If the total number of rows all fit onto the screen at once, then this
  34983. method won't do anything.
  34984. @see getVerticalPosition
  34985. */
  34986. void setVerticalPosition (double newProportion);
  34987. /** Returns the current vertical position as a proportion of the total.
  34988. This can be used in conjunction with setVerticalPosition() to save and restore
  34989. the list's position. It returns a value in the range 0 to 1.
  34990. @see setVerticalPosition
  34991. */
  34992. double getVerticalPosition() const;
  34993. /** Scrolls if necessary to make sure that a particular row is visible.
  34994. */
  34995. void scrollToEnsureRowIsOnscreen (int row);
  34996. /** Returns a pointer to the scrollbar.
  34997. (Unlikely to be useful for most people).
  34998. */
  34999. ScrollBar* getVerticalScrollBar() const noexcept;
  35000. /** Returns a pointer to the scrollbar.
  35001. (Unlikely to be useful for most people).
  35002. */
  35003. ScrollBar* getHorizontalScrollBar() const noexcept;
  35004. /** Finds the row index that contains a given x,y position.
  35005. The position is relative to the ListBox's top-left.
  35006. If no row exists at this position, the method will return -1.
  35007. @see getComponentForRowNumber
  35008. */
  35009. int getRowContainingPosition (int x, int y) const noexcept;
  35010. /** Finds a row index that would be the most suitable place to insert a new
  35011. item for a given position.
  35012. This is useful when the user is e.g. dragging and dropping onto the listbox,
  35013. because it lets you easily choose the best position to insert the item that
  35014. they drop, based on where they drop it.
  35015. If the position is out of range, this will return -1. If the position is
  35016. beyond the end of the list, it will return getNumRows() to indicate the end
  35017. of the list.
  35018. @see getComponentForRowNumber
  35019. */
  35020. int getInsertionIndexForPosition (int x, int y) const noexcept;
  35021. /** Returns the position of one of the rows, relative to the top-left of
  35022. the listbox.
  35023. This may be off-screen, and the range of the row number that is passed-in is
  35024. not checked to see if it's a valid row.
  35025. */
  35026. const Rectangle<int> getRowPosition (int rowNumber,
  35027. bool relativeToComponentTopLeft) const noexcept;
  35028. /** Finds the row component for a given row in the list.
  35029. The component returned will have been created using createRowComponent().
  35030. If the component for this row is off-screen or if the row is out-of-range,
  35031. this will return 0.
  35032. @see getRowContainingPosition
  35033. */
  35034. Component* getComponentForRowNumber (int rowNumber) const noexcept;
  35035. /** Returns the row number that the given component represents.
  35036. If the component isn't one of the list's rows, this will return -1.
  35037. */
  35038. int getRowNumberOfComponent (Component* rowComponent) const noexcept;
  35039. /** Returns the width of a row (which may be less than the width of this component
  35040. if there's a scrollbar).
  35041. */
  35042. int getVisibleRowWidth() const noexcept;
  35043. /** Sets the height of each row in the list.
  35044. The default height is 22 pixels.
  35045. @see getRowHeight
  35046. */
  35047. void setRowHeight (int newHeight);
  35048. /** Returns the height of a row in the list.
  35049. @see setRowHeight
  35050. */
  35051. int getRowHeight() const noexcept { return rowHeight; }
  35052. /** Returns the number of rows actually visible.
  35053. This is the number of whole rows which will fit on-screen, so the value might
  35054. be more than the actual number of rows in the list.
  35055. */
  35056. int getNumRowsOnScreen() const noexcept;
  35057. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35058. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35059. methods.
  35060. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35061. */
  35062. enum ColourIds
  35063. {
  35064. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35065. Make this transparent if you don't want the background to be filled. */
  35066. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35067. Make this transparent to not have an outline. */
  35068. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35069. };
  35070. /** Sets the thickness of a border that will be drawn around the box.
  35071. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35072. @see outlineColourId
  35073. */
  35074. void setOutlineThickness (int outlineThickness);
  35075. /** Returns the thickness of outline that will be drawn around the listbox.
  35076. @see setOutlineColour
  35077. */
  35078. int getOutlineThickness() const noexcept { return outlineThickness; }
  35079. /** Sets a component that the list should use as a header.
  35080. This will position the given component at the top of the list, maintaining the
  35081. height of the component passed-in, but rescaling it horizontally to match the
  35082. width of the items in the listbox.
  35083. The component will be deleted when setHeaderComponent() is called with a
  35084. different component, or when the listbox is deleted.
  35085. */
  35086. void setHeaderComponent (Component* newHeaderComponent);
  35087. /** Changes the width of the rows in the list.
  35088. This can be used to make the list's row components wider than the list itself - the
  35089. width of the rows will be either the width of the list or this value, whichever is
  35090. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35091. appear.
  35092. The default value for this is 0, which means that the rows will always
  35093. be the same width as the list.
  35094. */
  35095. void setMinimumContentWidth (int newMinimumWidth);
  35096. /** Returns the space currently available for the row items, taking into account
  35097. borders, scrollbars, etc.
  35098. */
  35099. int getVisibleContentWidth() const noexcept;
  35100. /** Repaints one of the rows.
  35101. This is a lightweight alternative to calling updateContent, and just causes a
  35102. repaint of the row's area.
  35103. */
  35104. void repaintRow (int rowNumber) noexcept;
  35105. /** This fairly obscure method creates an image that just shows the currently
  35106. selected row components.
  35107. It's a handy method for doing drag-and-drop, as it can be passed to the
  35108. DragAndDropContainer for use as the drag image.
  35109. Note that it will make the row components temporarily invisible, so if you're
  35110. using custom components this could affect them if they're sensitive to that
  35111. sort of thing.
  35112. @see Component::createComponentSnapshot
  35113. */
  35114. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35115. /** Returns the viewport that this ListBox uses.
  35116. You may need to use this to change parameters such as whether scrollbars
  35117. are shown, etc.
  35118. */
  35119. Viewport* getViewport() const noexcept;
  35120. /** @internal */
  35121. bool keyPressed (const KeyPress& key);
  35122. /** @internal */
  35123. bool keyStateChanged (bool isKeyDown);
  35124. /** @internal */
  35125. void paint (Graphics& g);
  35126. /** @internal */
  35127. void paintOverChildren (Graphics& g);
  35128. /** @internal */
  35129. void resized();
  35130. /** @internal */
  35131. void visibilityChanged();
  35132. /** @internal */
  35133. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35134. /** @internal */
  35135. void mouseMove (const MouseEvent&);
  35136. /** @internal */
  35137. void mouseExit (const MouseEvent&);
  35138. /** @internal */
  35139. void mouseUp (const MouseEvent&);
  35140. /** @internal */
  35141. void colourChanged();
  35142. /** @internal */
  35143. void startDragAndDrop (const MouseEvent& e, const var& dragDescription, bool allowDraggingToOtherWindows = true);
  35144. private:
  35145. friend class ListViewport;
  35146. friend class TableListBox;
  35147. ListBoxModel* model;
  35148. ScopedPointer<ListViewport> viewport;
  35149. ScopedPointer<Component> headerComponent;
  35150. int totalItems, rowHeight, minimumRowWidth;
  35151. int outlineThickness;
  35152. int lastRowSelected;
  35153. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35154. SparseSet <int> selected;
  35155. void selectRowInternal (int rowNumber,
  35156. bool dontScrollToShowThisRow,
  35157. bool deselectOthersFirst,
  35158. bool isMouseClick);
  35159. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35160. };
  35161. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35162. /*** End of inlined file: juce_ListBox.h ***/
  35163. /*** Start of inlined file: juce_TextButton.h ***/
  35164. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35165. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35166. /**
  35167. A button that uses the standard lozenge-shaped background with a line of
  35168. text on it.
  35169. @see Button, DrawableButton
  35170. */
  35171. class JUCE_API TextButton : public Button
  35172. {
  35173. public:
  35174. /** Creates a TextButton.
  35175. @param buttonName the text to put in the button (the component's name is also
  35176. initially set to this string, but these can be changed later
  35177. using the setName() and setButtonText() methods)
  35178. @param toolTip an optional string to use as a toolip
  35179. @see Button
  35180. */
  35181. TextButton (const String& buttonName = String::empty,
  35182. const String& toolTip = String::empty);
  35183. /** Destructor. */
  35184. ~TextButton();
  35185. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35186. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35187. methods.
  35188. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35189. */
  35190. enum ColourIds
  35191. {
  35192. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35193. 'off'). The look-and-feel class might re-interpret this to add
  35194. effects, etc. */
  35195. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35196. 'on'). The look-and-feel class might re-interpret this to add
  35197. effects, etc. */
  35198. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35199. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35200. };
  35201. /** Resizes the button to fit neatly around its current text.
  35202. If newHeight is >= 0, the button's height will be changed to this
  35203. value. If it's less than zero, its height will be unaffected.
  35204. */
  35205. void changeWidthToFitText (int newHeight = -1);
  35206. /** This can be overridden to use different fonts than the default one.
  35207. Note that you'll need to set the font's size appropriately, too.
  35208. */
  35209. virtual const Font getFont();
  35210. protected:
  35211. /** @internal */
  35212. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35213. /** @internal */
  35214. void colourChanged();
  35215. private:
  35216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35217. };
  35218. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35219. /*** End of inlined file: juce_TextButton.h ***/
  35220. /**
  35221. A component displaying a list of plugins, with options to scan for them,
  35222. add, remove and sort them.
  35223. */
  35224. class JUCE_API PluginListComponent : public Component,
  35225. public ListBoxModel,
  35226. public ChangeListener,
  35227. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35228. public Timer
  35229. {
  35230. public:
  35231. /**
  35232. Creates the list component.
  35233. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35234. The properties file, if supplied, is used to store the user's last search paths.
  35235. */
  35236. PluginListComponent (KnownPluginList& listToRepresent,
  35237. const File& deadMansPedalFile,
  35238. PropertiesFile* propertiesToUse);
  35239. /** Destructor. */
  35240. ~PluginListComponent();
  35241. /** @internal */
  35242. void resized();
  35243. /** @internal */
  35244. bool isInterestedInFileDrag (const StringArray& files);
  35245. /** @internal */
  35246. void filesDropped (const StringArray& files, int, int);
  35247. /** @internal */
  35248. int getNumRows();
  35249. /** @internal */
  35250. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35251. /** @internal */
  35252. void deleteKeyPressed (int lastRowSelected);
  35253. /** @internal */
  35254. void buttonClicked (Button* b);
  35255. /** @internal */
  35256. void changeListenerCallback (ChangeBroadcaster*);
  35257. /** @internal */
  35258. void timerCallback();
  35259. private:
  35260. KnownPluginList& list;
  35261. File deadMansPedalFile;
  35262. ListBox listBox;
  35263. TextButton optionsButton;
  35264. PropertiesFile* propertiesToUse;
  35265. int typeToScan;
  35266. void scanFor (AudioPluginFormat* format);
  35267. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35268. void optionsMenuCallback (int result);
  35269. void updateList();
  35270. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35271. };
  35272. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35273. /*** End of inlined file: juce_PluginListComponent.h ***/
  35274. #endif
  35275. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35276. #endif
  35277. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35278. #endif
  35279. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35280. #endif
  35281. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35282. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35283. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35284. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35285. /**
  35286. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35287. Use one of these objects if you want to wire-up a set of AudioProcessors
  35288. and play back the result.
  35289. Processors can be added to the graph as "nodes" using addNode(), and once
  35290. added, you can connect any of their input or output channels to other
  35291. nodes using addConnection().
  35292. To play back a graph through an audio device, you might want to use an
  35293. AudioProcessorPlayer object.
  35294. */
  35295. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35296. public AsyncUpdater
  35297. {
  35298. public:
  35299. /** Creates an empty graph.
  35300. */
  35301. AudioProcessorGraph();
  35302. /** Destructor.
  35303. Any processor objects that have been added to the graph will also be deleted.
  35304. */
  35305. ~AudioProcessorGraph();
  35306. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35307. To create a node, call AudioProcessorGraph::addNode().
  35308. */
  35309. class JUCE_API Node : public ReferenceCountedObject
  35310. {
  35311. public:
  35312. /** The ID number assigned to this node.
  35313. This is assigned by the graph that owns it, and can't be changed.
  35314. */
  35315. const uint32 nodeId;
  35316. /** The actual processor object that this node represents. */
  35317. AudioProcessor* getProcessor() const noexcept { return processor; }
  35318. /** A set of user-definable properties that are associated with this node.
  35319. This can be used to attach values to the node for whatever purpose seems
  35320. useful. For example, you might store an x and y position if your application
  35321. is displaying the nodes on-screen.
  35322. */
  35323. NamedValueSet properties;
  35324. /** A convenient typedef for referring to a pointer to a node object.
  35325. */
  35326. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35327. private:
  35328. friend class AudioProcessorGraph;
  35329. const ScopedPointer<AudioProcessor> processor;
  35330. bool isPrepared;
  35331. Node (uint32 nodeId, AudioProcessor* processor) noexcept;
  35332. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35333. void unprepare();
  35334. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35335. };
  35336. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35337. To create a connection, use AudioProcessorGraph::addConnection().
  35338. */
  35339. struct JUCE_API Connection
  35340. {
  35341. public:
  35342. Connection (uint32 sourceNodeId, int sourceChannelIndex,
  35343. uint32 destNodeId, int destChannelIndex) noexcept;
  35344. /** The ID number of the node which is the input source for this connection.
  35345. @see AudioProcessorGraph::getNodeForId
  35346. */
  35347. uint32 sourceNodeId;
  35348. /** The index of the output channel of the source node from which this
  35349. connection takes its data.
  35350. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35351. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35352. index of an audio output channel in the source node.
  35353. */
  35354. int sourceChannelIndex;
  35355. /** The ID number of the node which is the destination for this connection.
  35356. @see AudioProcessorGraph::getNodeForId
  35357. */
  35358. uint32 destNodeId;
  35359. /** The index of the input channel of the destination node to which this
  35360. connection delivers its data.
  35361. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35362. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35363. index of an audio input channel in the destination node.
  35364. */
  35365. int destChannelIndex;
  35366. private:
  35367. JUCE_LEAK_DETECTOR (Connection);
  35368. };
  35369. /** Deletes all nodes and connections from this graph.
  35370. Any processor objects in the graph will be deleted.
  35371. */
  35372. void clear();
  35373. /** Returns the number of nodes in the graph. */
  35374. int getNumNodes() const { return nodes.size(); }
  35375. /** Returns a pointer to one of the nodes in the graph.
  35376. This will return 0 if the index is out of range.
  35377. @see getNodeForId
  35378. */
  35379. Node* getNode (const int index) const { return nodes [index]; }
  35380. /** Searches the graph for a node with the given ID number and returns it.
  35381. If no such node was found, this returns 0.
  35382. @see getNode
  35383. */
  35384. Node* getNodeForId (const uint32 nodeId) const;
  35385. /** Adds a node to the graph.
  35386. This creates a new node in the graph, for the specified processor. Once you have
  35387. added a processor to the graph, the graph owns it and will delete it later when
  35388. it is no longer needed.
  35389. The optional nodeId parameter lets you specify an ID to use for the node, but
  35390. if the value is already in use, this new node will overwrite the old one.
  35391. If this succeeds, it returns a pointer to the newly-created node.
  35392. */
  35393. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35394. /** Deletes a node within the graph which has the specified ID.
  35395. This will also delete any connections that are attached to this node.
  35396. */
  35397. bool removeNode (uint32 nodeId);
  35398. /** Returns the number of connections in the graph. */
  35399. int getNumConnections() const { return connections.size(); }
  35400. /** Returns a pointer to one of the connections in the graph. */
  35401. const Connection* getConnection (int index) const { return connections [index]; }
  35402. /** Searches for a connection between some specified channels.
  35403. If no such connection is found, this returns 0.
  35404. */
  35405. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35406. int sourceChannelIndex,
  35407. uint32 destNodeId,
  35408. int destChannelIndex) const;
  35409. /** Returns true if there is a connection between any of the channels of
  35410. two specified nodes.
  35411. */
  35412. bool isConnected (uint32 possibleSourceNodeId,
  35413. uint32 possibleDestNodeId) const;
  35414. /** Returns true if it would be legal to connect the specified points.
  35415. */
  35416. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35417. uint32 destNodeId, int destChannelIndex) const;
  35418. /** Attempts to connect two specified channels of two nodes.
  35419. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35420. to an audio one or other such nonsense), then it'll return false.
  35421. */
  35422. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35423. uint32 destNodeId, int destChannelIndex);
  35424. /** Deletes the connection with the specified index.
  35425. Returns true if a connection was actually deleted.
  35426. */
  35427. void removeConnection (int index);
  35428. /** Deletes any connection between two specified points.
  35429. Returns true if a connection was actually deleted.
  35430. */
  35431. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35432. uint32 destNodeId, int destChannelIndex);
  35433. /** Removes all connections from the specified node.
  35434. */
  35435. bool disconnectNode (uint32 nodeId);
  35436. /** Performs a sanity checks of all the connections.
  35437. This might be useful if some of the processors are doing things like changing
  35438. their channel counts, which could render some connections obsolete.
  35439. */
  35440. bool removeIllegalConnections();
  35441. /** A special number that represents the midi channel of a node.
  35442. This is used as a channel index value if you want to refer to the midi input
  35443. or output instead of an audio channel.
  35444. */
  35445. static const int midiChannelIndex;
  35446. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35447. in order to use the audio that comes into and out of the graph itself.
  35448. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35449. node in the graph which delivers the audio that is coming into the parent
  35450. graph. This allows you to stream the data to other nodes and process the
  35451. incoming audio.
  35452. Likewise, one of these in "output" mode can be sent data which it will add to
  35453. the sum of data being sent to the graph's output.
  35454. @see AudioProcessorGraph
  35455. */
  35456. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  35457. {
  35458. public:
  35459. /** Specifies the mode in which this processor will operate.
  35460. */
  35461. enum IODeviceType
  35462. {
  35463. audioInputNode, /**< In this mode, the processor has output channels
  35464. representing all the audio input channels that are
  35465. coming into its parent audio graph. */
  35466. audioOutputNode, /**< In this mode, the processor has input channels
  35467. representing all the audio output channels that are
  35468. going out of its parent audio graph. */
  35469. midiInputNode, /**< In this mode, the processor has a midi output which
  35470. delivers the same midi data that is arriving at its
  35471. parent graph. */
  35472. midiOutputNode /**< In this mode, the processor has a midi input and
  35473. any data sent to it will be passed out of the parent
  35474. graph. */
  35475. };
  35476. /** Returns the mode of this processor. */
  35477. IODeviceType getType() const { return type; }
  35478. /** Returns the parent graph to which this processor belongs, or 0 if it
  35479. hasn't yet been added to one. */
  35480. AudioProcessorGraph* getParentGraph() const { return graph; }
  35481. /** True if this is an audio or midi input. */
  35482. bool isInput() const;
  35483. /** True if this is an audio or midi output. */
  35484. bool isOutput() const;
  35485. AudioGraphIOProcessor (const IODeviceType type);
  35486. ~AudioGraphIOProcessor();
  35487. const String getName() const;
  35488. void fillInPluginDescription (PluginDescription& d) const;
  35489. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35490. void releaseResources();
  35491. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35492. const String getInputChannelName (int channelIndex) const;
  35493. const String getOutputChannelName (int channelIndex) const;
  35494. bool isInputChannelStereoPair (int index) const;
  35495. bool isOutputChannelStereoPair (int index) const;
  35496. bool acceptsMidi() const;
  35497. bool producesMidi() const;
  35498. bool hasEditor() const;
  35499. AudioProcessorEditor* createEditor();
  35500. int getNumParameters();
  35501. const String getParameterName (int);
  35502. float getParameter (int);
  35503. const String getParameterText (int);
  35504. void setParameter (int, float);
  35505. int getNumPrograms();
  35506. int getCurrentProgram();
  35507. void setCurrentProgram (int);
  35508. const String getProgramName (int);
  35509. void changeProgramName (int, const String&);
  35510. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35511. void setStateInformation (const void* data, int sizeInBytes);
  35512. /** @internal */
  35513. void setParentGraph (AudioProcessorGraph* graph);
  35514. private:
  35515. const IODeviceType type;
  35516. AudioProcessorGraph* graph;
  35517. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  35518. };
  35519. // AudioProcessor methods:
  35520. const String getName() const;
  35521. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35522. void releaseResources();
  35523. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35524. const String getInputChannelName (int channelIndex) const;
  35525. const String getOutputChannelName (int channelIndex) const;
  35526. bool isInputChannelStereoPair (int index) const;
  35527. bool isOutputChannelStereoPair (int index) const;
  35528. bool acceptsMidi() const;
  35529. bool producesMidi() const;
  35530. bool hasEditor() const { return false; }
  35531. AudioProcessorEditor* createEditor() { return nullptr; }
  35532. int getNumParameters() { return 0; }
  35533. const String getParameterName (int) { return String::empty; }
  35534. float getParameter (int) { return 0; }
  35535. const String getParameterText (int) { return String::empty; }
  35536. void setParameter (int, float) { }
  35537. int getNumPrograms() { return 0; }
  35538. int getCurrentProgram() { return 0; }
  35539. void setCurrentProgram (int) { }
  35540. const String getProgramName (int) { return String::empty; }
  35541. void changeProgramName (int, const String&) { }
  35542. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35543. void setStateInformation (const void* data, int sizeInBytes);
  35544. /** @internal */
  35545. void handleAsyncUpdate();
  35546. private:
  35547. ReferenceCountedArray <Node> nodes;
  35548. OwnedArray <Connection> connections;
  35549. uint32 lastNodeId;
  35550. AudioSampleBuffer renderingBuffers;
  35551. OwnedArray <MidiBuffer> midiBuffers;
  35552. CriticalSection renderLock;
  35553. Array<void*> renderingOps;
  35554. friend class AudioGraphIOProcessor;
  35555. AudioSampleBuffer* currentAudioInputBuffer;
  35556. AudioSampleBuffer currentAudioOutputBuffer;
  35557. MidiBuffer* currentMidiInputBuffer;
  35558. MidiBuffer currentMidiOutputBuffer;
  35559. void clearRenderingSequence();
  35560. void buildRenderingSequence();
  35561. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  35562. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  35563. };
  35564. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35565. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  35566. #endif
  35567. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  35568. #endif
  35569. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35570. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  35571. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35572. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35573. /**
  35574. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  35575. To use one of these, just make it the callback used by your AudioIODevice, and
  35576. give it a processor to use by calling setProcessor().
  35577. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  35578. input to send both streams through the processor.
  35579. @see AudioProcessor, AudioProcessorGraph
  35580. */
  35581. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  35582. public MidiInputCallback
  35583. {
  35584. public:
  35585. /**
  35586. */
  35587. AudioProcessorPlayer();
  35588. /** Destructor. */
  35589. virtual ~AudioProcessorPlayer();
  35590. /** Sets the processor that should be played.
  35591. The processor that is passed in will not be deleted or owned by this object.
  35592. To stop anything playing, pass in 0 to this method.
  35593. */
  35594. void setProcessor (AudioProcessor* processorToPlay);
  35595. /** Returns the current audio processor that is being played.
  35596. */
  35597. AudioProcessor* getCurrentProcessor() const { return processor; }
  35598. /** Returns a midi message collector that you can pass midi messages to if you
  35599. want them to be injected into the midi stream that is being sent to the
  35600. processor.
  35601. */
  35602. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  35603. /** @internal */
  35604. void audioDeviceIOCallback (const float** inputChannelData,
  35605. int totalNumInputChannels,
  35606. float** outputChannelData,
  35607. int totalNumOutputChannels,
  35608. int numSamples);
  35609. /** @internal */
  35610. void audioDeviceAboutToStart (AudioIODevice* device);
  35611. /** @internal */
  35612. void audioDeviceStopped();
  35613. /** @internal */
  35614. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  35615. private:
  35616. AudioProcessor* processor;
  35617. CriticalSection lock;
  35618. double sampleRate;
  35619. int blockSize;
  35620. bool isPrepared;
  35621. int numInputChans, numOutputChans;
  35622. float* channels [128];
  35623. AudioSampleBuffer tempBuffer;
  35624. MidiBuffer incomingMidi;
  35625. MidiMessageCollector messageCollector;
  35626. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  35627. };
  35628. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35629. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  35630. #endif
  35631. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35632. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35633. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35634. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35635. /*** Start of inlined file: juce_PropertyPanel.h ***/
  35636. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35637. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  35638. /*** Start of inlined file: juce_PropertyComponent.h ***/
  35639. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35640. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35641. class EditableProperty;
  35642. /**
  35643. A base class for a component that goes in a PropertyPanel and displays one of
  35644. an item's properties.
  35645. Subclasses of this are used to display a property in various forms, e.g. a
  35646. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  35647. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  35648. A subclass must implement the refresh() method which will be called to tell the
  35649. component to update itself, and is also responsible for calling this it when the
  35650. item that it refers to is changed.
  35651. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  35652. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  35653. */
  35654. class JUCE_API PropertyComponent : public Component,
  35655. public SettableTooltipClient
  35656. {
  35657. public:
  35658. /** Creates a PropertyComponent.
  35659. @param propertyName the name is stored as this component's name, and is
  35660. used as the name displayed next to this component in
  35661. a property panel
  35662. @param preferredHeight the height that the component should be given - some
  35663. items may need to be larger than a normal row height.
  35664. This value can also be set if a subclass changes the
  35665. preferredHeight member variable.
  35666. */
  35667. PropertyComponent (const String& propertyName,
  35668. int preferredHeight = 25);
  35669. /** Destructor. */
  35670. ~PropertyComponent();
  35671. /** Returns this item's preferred height.
  35672. This value is specified either in the constructor or by a subclass changing the
  35673. preferredHeight member variable.
  35674. */
  35675. int getPreferredHeight() const noexcept { return preferredHeight; }
  35676. void setPreferredHeight (int newHeight) noexcept { preferredHeight = newHeight; }
  35677. /** Updates the property component if the item it refers to has changed.
  35678. A subclass must implement this method, and other objects may call it to
  35679. force it to refresh itself.
  35680. The subclass should be economical in the amount of work is done, so for
  35681. example it should check whether it really needs to do a repaint rather than
  35682. just doing one every time this method is called, as it may be called when
  35683. the value being displayed hasn't actually changed.
  35684. */
  35685. virtual void refresh() = 0;
  35686. /** The default paint method fills the background and draws a label for the
  35687. item's name.
  35688. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  35689. */
  35690. void paint (Graphics& g);
  35691. /** The default resize method positions any child component to the right of this
  35692. one, based on the look and feel's default label size.
  35693. */
  35694. void resized();
  35695. /** By default, this just repaints the component. */
  35696. void enablementChanged();
  35697. protected:
  35698. /** Used by the PropertyPanel to determine how high this component needs to be.
  35699. A subclass can update this value in its constructor but shouldn't alter it later
  35700. as changes won't necessarily be picked up.
  35701. */
  35702. int preferredHeight;
  35703. private:
  35704. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  35705. };
  35706. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35707. /*** End of inlined file: juce_PropertyComponent.h ***/
  35708. /**
  35709. A panel that holds a list of PropertyComponent objects.
  35710. This panel displays a list of PropertyComponents, and allows them to be organised
  35711. into collapsible sections.
  35712. To use, simply create one of these and add your properties to it with addProperties()
  35713. or addSection().
  35714. @see PropertyComponent
  35715. */
  35716. class JUCE_API PropertyPanel : public Component
  35717. {
  35718. public:
  35719. /** Creates an empty property panel. */
  35720. PropertyPanel();
  35721. /** Destructor. */
  35722. ~PropertyPanel();
  35723. /** Deletes all property components from the panel.
  35724. */
  35725. void clear();
  35726. /** Adds a set of properties to the panel.
  35727. The components in the list will be owned by this object and will be automatically
  35728. deleted later on when no longer needed.
  35729. These properties are added without them being inside a named section. If you
  35730. want them to be kept together in a collapsible section, use addSection() instead.
  35731. */
  35732. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  35733. /** Adds a set of properties to the panel.
  35734. These properties are added at the bottom of the list, under a section heading with
  35735. a plus/minus button that allows it to be opened and closed.
  35736. The components in the list will be owned by this object and will be automatically
  35737. deleted later on when no longer needed.
  35738. To add properies without them being in a section, use addProperties().
  35739. */
  35740. void addSection (const String& sectionTitle,
  35741. const Array <PropertyComponent*>& newPropertyComponents,
  35742. bool shouldSectionInitiallyBeOpen = true);
  35743. /** Calls the refresh() method of all PropertyComponents in the panel */
  35744. void refreshAll() const;
  35745. /** Returns a list of all the names of sections in the panel.
  35746. These are the sections that have been added with addSection().
  35747. */
  35748. StringArray getSectionNames() const;
  35749. /** Returns true if the section at this index is currently open.
  35750. The index is from 0 up to the number of items returned by getSectionNames().
  35751. */
  35752. bool isSectionOpen (int sectionIndex) const;
  35753. /** Opens or closes one of the sections.
  35754. The index is from 0 up to the number of items returned by getSectionNames().
  35755. */
  35756. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  35757. /** Enables or disables one of the sections.
  35758. The index is from 0 up to the number of items returned by getSectionNames().
  35759. */
  35760. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  35761. /** Saves the current state of open/closed sections so it can be restored later.
  35762. The caller is responsible for deleting the object that is returned.
  35763. To restore this state, use restoreOpennessState().
  35764. @see restoreOpennessState
  35765. */
  35766. XmlElement* getOpennessState() const;
  35767. /** Restores a previously saved arrangement of open/closed sections.
  35768. This will try to restore a snapshot of the panel's state that was created by
  35769. the getOpennessState() method. If any of the sections named in the original
  35770. XML aren't present, they will be ignored.
  35771. @see getOpennessState
  35772. */
  35773. void restoreOpennessState (const XmlElement& newState);
  35774. /** Sets a message to be displayed when there are no properties in the panel.
  35775. The default message is "nothing selected".
  35776. */
  35777. void setMessageWhenEmpty (const String& newMessage);
  35778. /** Returns the message that is displayed when there are no properties.
  35779. @see setMessageWhenEmpty
  35780. */
  35781. const String& getMessageWhenEmpty() const;
  35782. /** @internal */
  35783. void paint (Graphics& g);
  35784. /** @internal */
  35785. void resized();
  35786. private:
  35787. Viewport viewport;
  35788. class PropertyHolderComponent;
  35789. PropertyHolderComponent* propertyHolderComponent;
  35790. String messageWhenEmpty;
  35791. void updatePropHolderLayout() const;
  35792. void updatePropHolderLayout (int width) const;
  35793. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  35794. };
  35795. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  35796. /*** End of inlined file: juce_PropertyPanel.h ***/
  35797. /**
  35798. A type of UI component that displays the parameters of an AudioProcessor as
  35799. a simple list of sliders.
  35800. This can be used for showing an editor for a processor that doesn't supply
  35801. its own custom editor.
  35802. @see AudioProcessor
  35803. */
  35804. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  35805. {
  35806. public:
  35807. GenericAudioProcessorEditor (AudioProcessor* owner);
  35808. ~GenericAudioProcessorEditor();
  35809. void paint (Graphics& g);
  35810. void resized();
  35811. private:
  35812. PropertyPanel panel;
  35813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  35814. };
  35815. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35816. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35817. #endif
  35818. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35819. /*** Start of inlined file: juce_Sampler.h ***/
  35820. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35821. #define __JUCE_SAMPLER_JUCEHEADER__
  35822. /*** Start of inlined file: juce_Synthesiser.h ***/
  35823. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35824. #define __JUCE_SYNTHESISER_JUCEHEADER__
  35825. /**
  35826. Describes one of the sounds that a Synthesiser can play.
  35827. A synthesiser can contain one or more sounds, and a sound can choose which
  35828. midi notes and channels can trigger it.
  35829. The SynthesiserSound is a passive class that just describes what the sound is -
  35830. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  35831. more than one SynthesiserVoice to play the same sound at the same time.
  35832. @see Synthesiser, SynthesiserVoice
  35833. */
  35834. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  35835. {
  35836. protected:
  35837. SynthesiserSound();
  35838. public:
  35839. /** Destructor. */
  35840. virtual ~SynthesiserSound();
  35841. /** Returns true if this sound should be played when a given midi note is pressed.
  35842. The Synthesiser will use this information when deciding which sounds to trigger
  35843. for a given note.
  35844. */
  35845. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  35846. /** Returns true if the sound should be triggered by midi events on a given channel.
  35847. The Synthesiser will use this information when deciding which sounds to trigger
  35848. for a given note.
  35849. */
  35850. virtual bool appliesToChannel (const int midiChannel) = 0;
  35851. /**
  35852. */
  35853. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  35854. private:
  35855. JUCE_LEAK_DETECTOR (SynthesiserSound);
  35856. };
  35857. /**
  35858. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  35859. A voice plays a single sound at a time, and a synthesiser holds an array of
  35860. voices so that it can play polyphonically.
  35861. @see Synthesiser, SynthesiserSound
  35862. */
  35863. class JUCE_API SynthesiserVoice
  35864. {
  35865. public:
  35866. /** Creates a voice. */
  35867. SynthesiserVoice();
  35868. /** Destructor. */
  35869. virtual ~SynthesiserVoice();
  35870. /** Returns the midi note that this voice is currently playing.
  35871. Returns a value less than 0 if no note is playing.
  35872. */
  35873. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  35874. /** Returns the sound that this voice is currently playing.
  35875. Returns 0 if it's not playing.
  35876. */
  35877. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  35878. /** Must return true if this voice object is capable of playing the given sound.
  35879. If there are different classes of sound, and different classes of voice, a voice can
  35880. choose which ones it wants to take on.
  35881. A typical implementation of this method may just return true if there's only one type
  35882. of voice and sound, or it might check the type of the sound object passed-in and
  35883. see if it's one that it understands.
  35884. */
  35885. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  35886. /** Called to start a new note.
  35887. This will be called during the rendering callback, so must be fast and thread-safe.
  35888. */
  35889. virtual void startNote (const int midiNoteNumber,
  35890. const float velocity,
  35891. SynthesiserSound* sound,
  35892. const int currentPitchWheelPosition) = 0;
  35893. /** Called to stop a note.
  35894. This will be called during the rendering callback, so must be fast and thread-safe.
  35895. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  35896. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  35897. and allow the synth to reassign it another sound.
  35898. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  35899. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  35900. finishes playing (during the rendering callback), it must make sure that it calls
  35901. clearCurrentNote().
  35902. */
  35903. virtual void stopNote (const bool allowTailOff) = 0;
  35904. /** Called to let the voice know that the pitch wheel has been moved.
  35905. This will be called during the rendering callback, so must be fast and thread-safe.
  35906. */
  35907. virtual void pitchWheelMoved (const int newValue) = 0;
  35908. /** Called to let the voice know that a midi controller has been moved.
  35909. This will be called during the rendering callback, so must be fast and thread-safe.
  35910. */
  35911. virtual void controllerMoved (const int controllerNumber,
  35912. const int newValue) = 0;
  35913. /** Renders the next block of data for this voice.
  35914. The output audio data must be added to the current contents of the buffer provided.
  35915. Only the region of the buffer between startSample and (startSample + numSamples)
  35916. should be altered by this method.
  35917. If the voice is currently silent, it should just return without doing anything.
  35918. If the sound that the voice is playing finishes during the course of this rendered
  35919. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  35920. The size of the blocks that are rendered can change each time it is called, and may
  35921. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  35922. the voice's methods will be called to tell it about note and controller events.
  35923. */
  35924. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  35925. int startSample,
  35926. int numSamples) = 0;
  35927. /** Returns true if the voice is currently playing a sound which is mapped to the given
  35928. midi channel.
  35929. If it's not currently playing, this will return false.
  35930. */
  35931. bool isPlayingChannel (int midiChannel) const;
  35932. /** Changes the voice's reference sample rate.
  35933. The rate is set so that subclasses know the output rate and can set their pitch
  35934. accordingly.
  35935. This method is called by the synth, and subclasses can access the current rate with
  35936. the currentSampleRate member.
  35937. */
  35938. void setCurrentPlaybackSampleRate (double newRate);
  35939. protected:
  35940. /** Returns the current target sample rate at which rendering is being done.
  35941. This is available for subclasses so they can pitch things correctly.
  35942. */
  35943. double getSampleRate() const { return currentSampleRate; }
  35944. /** Resets the state of this voice after a sound has finished playing.
  35945. The subclass must call this when it finishes playing a note and becomes available
  35946. to play new ones.
  35947. It must either call it in the stopNote() method, or if the voice is tailing off,
  35948. then it should call it later during the renderNextBlock method, as soon as it
  35949. finishes its tail-off.
  35950. It can also be called at any time during the render callback if the sound happens
  35951. to have finished, e.g. if it's playing a sample and the sample finishes.
  35952. */
  35953. void clearCurrentNote();
  35954. private:
  35955. friend class Synthesiser;
  35956. double currentSampleRate;
  35957. int currentlyPlayingNote;
  35958. uint32 noteOnTime;
  35959. SynthesiserSound::Ptr currentlyPlayingSound;
  35960. bool keyIsDown; // the voice may still be playing when the key is not down (i.e. sustain pedal)
  35961. bool sostenutoPedalDown;
  35962. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  35963. };
  35964. /**
  35965. Base class for a musical device that can play sounds.
  35966. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  35967. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  35968. which can play back one of these sounds.
  35969. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  35970. set of sounds, and a set of voices it can use to play them. If you only give it
  35971. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  35972. have available.
  35973. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  35974. events that go in will be scanned for note on/off messages, and these are used to
  35975. start and stop the voices playing the appropriate sounds.
  35976. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  35977. noteOff() and other controller methods.
  35978. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  35979. what the target playback rate is. This value is passed on to the voices so that
  35980. they can pitch their output correctly.
  35981. */
  35982. class JUCE_API Synthesiser
  35983. {
  35984. public:
  35985. /** Creates a new synthesiser.
  35986. You'll need to add some sounds and voices before it'll make any sound..
  35987. */
  35988. Synthesiser();
  35989. /** Destructor. */
  35990. virtual ~Synthesiser();
  35991. /** Deletes all voices. */
  35992. void clearVoices();
  35993. /** Returns the number of voices that have been added. */
  35994. int getNumVoices() const { return voices.size(); }
  35995. /** Returns one of the voices that have been added. */
  35996. SynthesiserVoice* getVoice (int index) const;
  35997. /** Adds a new voice to the synth.
  35998. All the voices should be the same class of object and are treated equally.
  35999. The object passed in will be managed by the synthesiser, which will delete
  36000. it later on when no longer needed. The caller should not retain a pointer to the
  36001. voice.
  36002. */
  36003. void addVoice (SynthesiserVoice* newVoice);
  36004. /** Deletes one of the voices. */
  36005. void removeVoice (int index);
  36006. /** Deletes all sounds. */
  36007. void clearSounds();
  36008. /** Returns the number of sounds that have been added to the synth. */
  36009. int getNumSounds() const { return sounds.size(); }
  36010. /** Returns one of the sounds. */
  36011. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  36012. /** Adds a new sound to the synthesiser.
  36013. The object passed in is reference counted, so will be deleted when it is removed
  36014. from the synthesiser, and when no voices are still using it.
  36015. */
  36016. void addSound (const SynthesiserSound::Ptr& newSound);
  36017. /** Removes and deletes one of the sounds. */
  36018. void removeSound (int index);
  36019. /** If set to true, then the synth will try to take over an existing voice if
  36020. it runs out and needs to play another note.
  36021. The value of this boolean is passed into findFreeVoice(), so the result will
  36022. depend on the implementation of this method.
  36023. */
  36024. void setNoteStealingEnabled (bool shouldStealNotes);
  36025. /** Returns true if note-stealing is enabled.
  36026. @see setNoteStealingEnabled
  36027. */
  36028. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  36029. /** Triggers a note-on event.
  36030. The default method here will find all the sounds that want to be triggered by
  36031. this note/channel. For each sound, it'll try to find a free voice, and use the
  36032. voice to start playing the sound.
  36033. Subclasses might want to override this if they need a more complex algorithm.
  36034. This method will be called automatically according to the midi data passed into
  36035. renderNextBlock(), but may be called explicitly too.
  36036. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  36037. */
  36038. virtual void noteOn (int midiChannel,
  36039. int midiNoteNumber,
  36040. float velocity);
  36041. /** Triggers a note-off event.
  36042. This will turn off any voices that are playing a sound for the given note/channel.
  36043. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36044. (if they can do). If this is false, the notes will all be cut off immediately.
  36045. This method will be called automatically according to the midi data passed into
  36046. renderNextBlock(), but may be called explicitly too.
  36047. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  36048. */
  36049. virtual void noteOff (int midiChannel,
  36050. int midiNoteNumber,
  36051. bool allowTailOff);
  36052. /** Turns off all notes.
  36053. This will turn off any voices that are playing a sound on the given midi channel.
  36054. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36055. which channel they're playing. Otherwise it represents a valid midi channel, from
  36056. 1 to 16 inclusive.
  36057. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36058. (if they can do). If this is false, the notes will all be cut off immediately.
  36059. This method will be called automatically according to the midi data passed into
  36060. renderNextBlock(), but may be called explicitly too.
  36061. */
  36062. virtual void allNotesOff (int midiChannel,
  36063. bool allowTailOff);
  36064. /** Sends a pitch-wheel message.
  36065. This will send a pitch-wheel message to any voices that are playing sounds on
  36066. the given midi channel.
  36067. This method will be called automatically according to the midi data passed into
  36068. renderNextBlock(), but may be called explicitly too.
  36069. @param midiChannel the midi channel, from 1 to 16 inclusive
  36070. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36071. */
  36072. virtual void handlePitchWheel (int midiChannel,
  36073. int wheelValue);
  36074. /** Sends a midi controller message.
  36075. This will send a midi controller message to any voices that are playing sounds on
  36076. the given midi channel.
  36077. This method will be called automatically according to the midi data passed into
  36078. renderNextBlock(), but may be called explicitly too.
  36079. @param midiChannel the midi channel, from 1 to 16 inclusive
  36080. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36081. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36082. */
  36083. virtual void handleController (int midiChannel,
  36084. int controllerNumber,
  36085. int controllerValue);
  36086. virtual void handleSustainPedal (int midiChannel, bool isDown);
  36087. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  36088. virtual void handleSoftPedal (int midiChannel, bool isDown);
  36089. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36090. render.
  36091. This value is propagated to the voices so that they can use it to render the correct
  36092. pitches.
  36093. */
  36094. void setCurrentPlaybackSampleRate (double sampleRate);
  36095. /** Creates the next block of audio output.
  36096. This will process the next numSamples of data from all the voices, and add that output
  36097. to the audio block supplied, starting from the offset specified. Note that the
  36098. data will be added to the current contents of the buffer, so you should clear it
  36099. before calling this method if necessary.
  36100. The midi events in the inputMidi buffer are parsed for note and controller events,
  36101. and these are used to trigger the voices. Note that the startSample offset applies
  36102. both to the audio output buffer and the midi input buffer, so any midi events
  36103. with timestamps outside the specified region will be ignored.
  36104. */
  36105. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36106. const MidiBuffer& inputMidi,
  36107. int startSample,
  36108. int numSamples);
  36109. protected:
  36110. /** This is used to control access to the rendering callback and the note trigger methods. */
  36111. CriticalSection lock;
  36112. OwnedArray <SynthesiserVoice> voices;
  36113. ReferenceCountedArray <SynthesiserSound> sounds;
  36114. /** The last pitch-wheel values for each midi channel. */
  36115. int lastPitchWheelValues [16];
  36116. /** Searches through the voices to find one that's not currently playing, and which
  36117. can play the given sound.
  36118. Returns 0 if all voices are busy and stealing isn't enabled.
  36119. This can be overridden to implement custom voice-stealing algorithms.
  36120. */
  36121. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36122. const bool stealIfNoneAvailable) const;
  36123. /** Starts a specified voice playing a particular sound.
  36124. You'll probably never need to call this, it's used internally by noteOn(), but
  36125. may be needed by subclasses for custom behaviours.
  36126. */
  36127. void startVoice (SynthesiserVoice* voice,
  36128. SynthesiserSound* sound,
  36129. int midiChannel,
  36130. int midiNoteNumber,
  36131. float velocity);
  36132. private:
  36133. double sampleRate;
  36134. uint32 lastNoteOnCounter;
  36135. bool shouldStealNotes;
  36136. BigInteger sustainPedalsDown;
  36137. void handleMidiEvent (const MidiMessage& m);
  36138. void stopVoice (SynthesiserVoice* voice, bool allowTailOff);
  36139. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36140. // Note the new parameters for this method.
  36141. virtual int findFreeVoice (const bool) const { return 0; }
  36142. #endif
  36143. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36144. };
  36145. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36146. /*** End of inlined file: juce_Synthesiser.h ***/
  36147. /**
  36148. A subclass of SynthesiserSound that represents a sampled audio clip.
  36149. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36150. into memory.
  36151. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36152. give it some SampledSound objects to play.
  36153. @see SamplerVoice, Synthesiser, SynthesiserSound
  36154. */
  36155. class JUCE_API SamplerSound : public SynthesiserSound
  36156. {
  36157. public:
  36158. /** Creates a sampled sound from an audio reader.
  36159. This will attempt to load the audio from the source into memory and store
  36160. it in this object.
  36161. @param name a name for the sample
  36162. @param source the audio to load. This object can be safely deleted by the
  36163. caller after this constructor returns
  36164. @param midiNotes the set of midi keys that this sound should be played on. This
  36165. is used by the SynthesiserSound::appliesToNote() method
  36166. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36167. with its natural rate. All other notes will be pitched
  36168. up or down relative to this one
  36169. @param attackTimeSecs the attack (fade-in) time, in seconds
  36170. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36171. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36172. source, in seconds
  36173. */
  36174. SamplerSound (const String& name,
  36175. AudioFormatReader& source,
  36176. const BigInteger& midiNotes,
  36177. int midiNoteForNormalPitch,
  36178. double attackTimeSecs,
  36179. double releaseTimeSecs,
  36180. double maxSampleLengthSeconds);
  36181. /** Destructor. */
  36182. ~SamplerSound();
  36183. /** Returns the sample's name */
  36184. const String& getName() const { return name; }
  36185. /** Returns the audio sample data.
  36186. This could be 0 if there was a problem loading it.
  36187. */
  36188. AudioSampleBuffer* getAudioData() const { return data; }
  36189. bool appliesToNote (const int midiNoteNumber);
  36190. bool appliesToChannel (const int midiChannel);
  36191. private:
  36192. friend class SamplerVoice;
  36193. String name;
  36194. ScopedPointer <AudioSampleBuffer> data;
  36195. double sourceSampleRate;
  36196. BigInteger midiNotes;
  36197. int length, attackSamples, releaseSamples;
  36198. int midiRootNote;
  36199. JUCE_LEAK_DETECTOR (SamplerSound);
  36200. };
  36201. /**
  36202. A subclass of SynthesiserVoice that can play a SamplerSound.
  36203. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36204. give it some SampledSound objects to play.
  36205. @see SamplerSound, Synthesiser, SynthesiserVoice
  36206. */
  36207. class JUCE_API SamplerVoice : public SynthesiserVoice
  36208. {
  36209. public:
  36210. /** Creates a SamplerVoice.
  36211. */
  36212. SamplerVoice();
  36213. /** Destructor. */
  36214. ~SamplerVoice();
  36215. bool canPlaySound (SynthesiserSound* sound);
  36216. void startNote (const int midiNoteNumber,
  36217. const float velocity,
  36218. SynthesiserSound* sound,
  36219. const int currentPitchWheelPosition);
  36220. void stopNote (const bool allowTailOff);
  36221. void pitchWheelMoved (const int newValue);
  36222. void controllerMoved (const int controllerNumber,
  36223. const int newValue);
  36224. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36225. private:
  36226. double pitchRatio;
  36227. double sourceSamplePosition;
  36228. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36229. bool isInAttack, isInRelease;
  36230. JUCE_LEAK_DETECTOR (SamplerVoice);
  36231. };
  36232. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36233. /*** End of inlined file: juce_Sampler.h ***/
  36234. #endif
  36235. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36236. #endif
  36237. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36238. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36239. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36240. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36241. /** Manages a list of ActionListeners, and can send them messages.
  36242. To quickly add methods to your class that can add/remove action
  36243. listeners and broadcast to them, you can derive from this.
  36244. @see ActionListener, ChangeListener
  36245. */
  36246. class JUCE_API ActionBroadcaster
  36247. {
  36248. public:
  36249. /** Creates an ActionBroadcaster. */
  36250. ActionBroadcaster();
  36251. /** Destructor. */
  36252. virtual ~ActionBroadcaster();
  36253. /** Adds a listener to the list.
  36254. Trying to add a listener that's already on the list will have no effect.
  36255. */
  36256. void addActionListener (ActionListener* listener);
  36257. /** Removes a listener from the list.
  36258. If the listener isn't on the list, this won't have any effect.
  36259. */
  36260. void removeActionListener (ActionListener* listener);
  36261. /** Removes all listeners from the list. */
  36262. void removeAllActionListeners();
  36263. /** Broadcasts a message to all the registered listeners.
  36264. @see ActionListener::actionListenerCallback
  36265. */
  36266. void sendActionMessage (const String& message) const;
  36267. private:
  36268. class CallbackReceiver : public MessageListener
  36269. {
  36270. public:
  36271. CallbackReceiver();
  36272. void handleMessage (const Message&);
  36273. ActionBroadcaster* owner;
  36274. };
  36275. friend class CallbackReceiver;
  36276. CallbackReceiver callback;
  36277. SortedSet <ActionListener*> actionListeners;
  36278. CriticalSection actionListenerLock;
  36279. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36280. };
  36281. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36282. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36283. #endif
  36284. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36285. #endif
  36286. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36287. #endif
  36288. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36289. #endif
  36290. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36291. #endif
  36292. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36293. #endif
  36294. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36295. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36296. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36297. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36298. class InterprocessConnectionServer;
  36299. class MemoryBlock;
  36300. /**
  36301. Manages a simple two-way messaging connection to another process, using either
  36302. a socket or a named pipe as the transport medium.
  36303. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36304. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36305. and incoming messages will result in a callback via the messageReceived()
  36306. method.
  36307. To open a pipe and wait for another client to connect to it, use the createPipe()
  36308. method.
  36309. To act as a socket server and create connections for one or more client, see the
  36310. InterprocessConnectionServer class.
  36311. @see InterprocessConnectionServer, Socket, NamedPipe
  36312. */
  36313. class JUCE_API InterprocessConnection : public Thread,
  36314. private MessageListener
  36315. {
  36316. public:
  36317. /** Creates a connection.
  36318. Connections are created manually, connecting them with the connectToSocket()
  36319. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36320. when a client wants to connect.
  36321. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36322. connectionLost() and messageReceived() methods will
  36323. always be made using the message thread; if false,
  36324. these will be called immediately on the connection's
  36325. own thread.
  36326. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36327. validity of the data blocks being sent and received. This
  36328. can be any number, but the sender and receiver must obviously
  36329. use matching values or they won't recognise each other.
  36330. */
  36331. InterprocessConnection (bool callbacksOnMessageThread = true,
  36332. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36333. /** Destructor. */
  36334. ~InterprocessConnection();
  36335. /** Tries to connect this object to a socket.
  36336. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36337. object waiting to receive client connections on this port number.
  36338. @param hostName the host computer, either a network address or name
  36339. @param portNumber the socket port number to try to connect to
  36340. @param timeOutMillisecs how long to keep trying before giving up
  36341. @returns true if the connection is established successfully
  36342. @see Socket
  36343. */
  36344. bool connectToSocket (const String& hostName,
  36345. int portNumber,
  36346. int timeOutMillisecs);
  36347. /** Tries to connect the object to an existing named pipe.
  36348. For this to work, another process on the same computer must already have opened
  36349. an InterprocessConnection object and used createPipe() to create a pipe for this
  36350. to connect to.
  36351. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36352. @returns true if it connects successfully.
  36353. @see createPipe, NamedPipe
  36354. */
  36355. bool connectToPipe (const String& pipeName,
  36356. int pipeReceiveMessageTimeoutMs = -1);
  36357. /** Tries to create a new pipe for other processes to connect to.
  36358. This creates a pipe with the given name, so that other processes can use
  36359. connectToPipe() to connect to the other end.
  36360. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36361. If another process is already using this pipe, this will fail and return false.
  36362. */
  36363. bool createPipe (const String& pipeName,
  36364. int pipeReceiveMessageTimeoutMs = -1);
  36365. /** Disconnects and closes any currently-open sockets or pipes. */
  36366. void disconnect();
  36367. /** True if a socket or pipe is currently active. */
  36368. bool isConnected() const;
  36369. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36370. StreamingSocket* getSocket() const noexcept { return socket; }
  36371. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36372. NamedPipe* getPipe() const noexcept { return pipe; }
  36373. /** Returns the name of the machine at the other end of this connection.
  36374. This will return an empty string if the other machine isn't known for
  36375. some reason.
  36376. */
  36377. const String getConnectedHostName() const;
  36378. /** Tries to send a message to the other end of this connection.
  36379. This will fail if it's not connected, or if there's some kind of write error. If
  36380. it succeeds, the connection object at the other end will receive the message by
  36381. a callback to its messageReceived() method.
  36382. @see messageReceived
  36383. */
  36384. bool sendMessage (const MemoryBlock& message);
  36385. /** Called when the connection is first connected.
  36386. If the connection was created with the callbacksOnMessageThread flag set, then
  36387. this will be called on the message thread; otherwise it will be called on a server
  36388. thread.
  36389. */
  36390. virtual void connectionMade() = 0;
  36391. /** Called when the connection is broken.
  36392. If the connection was created with the callbacksOnMessageThread flag set, then
  36393. this will be called on the message thread; otherwise it will be called on a server
  36394. thread.
  36395. */
  36396. virtual void connectionLost() = 0;
  36397. /** Called when a message arrives.
  36398. When the object at the other end of this connection sends us a message with sendMessage(),
  36399. this callback is used to deliver it to us.
  36400. If the connection was created with the callbacksOnMessageThread flag set, then
  36401. this will be called on the message thread; otherwise it will be called on a server
  36402. thread.
  36403. @see sendMessage
  36404. */
  36405. virtual void messageReceived (const MemoryBlock& message) = 0;
  36406. private:
  36407. CriticalSection pipeAndSocketLock;
  36408. ScopedPointer <StreamingSocket> socket;
  36409. ScopedPointer <NamedPipe> pipe;
  36410. bool callbackConnectionState;
  36411. const bool useMessageThread;
  36412. const uint32 magicMessageHeader;
  36413. int pipeReceiveMessageTimeout;
  36414. friend class InterprocessConnectionServer;
  36415. void initialiseWithSocket (StreamingSocket* socket_);
  36416. void initialiseWithPipe (NamedPipe* pipe_);
  36417. void handleMessage (const Message& message);
  36418. void connectionMadeInt();
  36419. void connectionLostInt();
  36420. void deliverDataInt (const MemoryBlock& data);
  36421. bool readNextMessageInt();
  36422. void run();
  36423. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36424. };
  36425. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36426. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36427. #endif
  36428. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36429. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36430. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36431. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36432. /**
  36433. An object that waits for client sockets to connect to a port on this host, and
  36434. creates InterprocessConnection objects for each one.
  36435. To use this, create a class derived from it which implements the createConnectionObject()
  36436. method, so that it creates suitable connection objects for each client that tries
  36437. to connect.
  36438. @see InterprocessConnection
  36439. */
  36440. class JUCE_API InterprocessConnectionServer : private Thread
  36441. {
  36442. public:
  36443. /** Creates an uninitialised server object.
  36444. */
  36445. InterprocessConnectionServer();
  36446. /** Destructor. */
  36447. ~InterprocessConnectionServer();
  36448. /** Starts an internal thread which listens on the given port number.
  36449. While this is running, in another process tries to connect with the
  36450. InterprocessConnection::connectToSocket() method, this object will call
  36451. createConnectionObject() to create a connection to that client.
  36452. Use stop() to stop the thread running.
  36453. @see createConnectionObject, stop
  36454. */
  36455. bool beginWaitingForSocket (int portNumber);
  36456. /** Terminates the listener thread, if it's active.
  36457. @see beginWaitingForSocket
  36458. */
  36459. void stop();
  36460. protected:
  36461. /** Creates a suitable connection object for a client process that wants to
  36462. connect to this one.
  36463. This will be called by the listener thread when a client process tries
  36464. to connect, and must return a new InterprocessConnection object that will
  36465. then run as this end of the connection.
  36466. @see InterprocessConnection
  36467. */
  36468. virtual InterprocessConnection* createConnectionObject() = 0;
  36469. private:
  36470. ScopedPointer <StreamingSocket> socket;
  36471. void run();
  36472. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  36473. };
  36474. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36475. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  36476. #endif
  36477. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  36478. #endif
  36479. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  36480. #endif
  36481. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  36482. #endif
  36483. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36484. /*** Start of inlined file: juce_MessageManager.h ***/
  36485. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36486. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36487. class Component;
  36488. class MessageManagerLock;
  36489. class ThreadPoolJob;
  36490. class ActionListener;
  36491. class ActionBroadcaster;
  36492. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  36493. */
  36494. typedef void* (MessageCallbackFunction) (void* userData);
  36495. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  36496. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  36497. */
  36498. class JUCE_API MessageManager
  36499. {
  36500. public:
  36501. /** Returns the global instance of the MessageManager. */
  36502. static MessageManager* getInstance() noexcept;
  36503. /** Runs the event dispatch loop until a stop message is posted.
  36504. This method is only intended to be run by the application's startup routine,
  36505. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  36506. @see stopDispatchLoop
  36507. */
  36508. void runDispatchLoop();
  36509. /** Sends a signal that the dispatch loop should terminate.
  36510. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  36511. will be interrupted and will return.
  36512. @see runDispatchLoop
  36513. */
  36514. void stopDispatchLoop();
  36515. /** Returns true if the stopDispatchLoop() method has been called.
  36516. */
  36517. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  36518. #if JUCE_MODAL_LOOPS_PERMITTED
  36519. /** Synchronously dispatches messages until a given time has elapsed.
  36520. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  36521. otherwise returns true.
  36522. */
  36523. bool runDispatchLoopUntil (int millisecondsToRunFor);
  36524. #endif
  36525. /** Calls a function using the message-thread.
  36526. This can be used by any thread to cause this function to be called-back
  36527. by the message thread. If it's the message-thread that's calling this method,
  36528. then the function will just be called; if another thread is calling, a message
  36529. will be posted to the queue, and this method will block until that message
  36530. is delivered, the function is called, and the result is returned.
  36531. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  36532. thread has a critical section locked, which an unrelated message callback then tries to lock
  36533. before the message thread gets round to processing this callback.
  36534. @param callback the function to call - its signature must be @code
  36535. void* myCallbackFunction (void*) @endcode
  36536. @param userData a user-defined pointer that will be passed to the function that gets called
  36537. @returns the value that the callback function returns.
  36538. @see MessageManagerLock
  36539. */
  36540. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  36541. /** Returns true if the caller-thread is the message thread. */
  36542. bool isThisTheMessageThread() const noexcept;
  36543. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  36544. (Best to ignore this method unless you really know what you're doing..)
  36545. @see getCurrentMessageThread
  36546. */
  36547. void setCurrentThreadAsMessageThread();
  36548. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  36549. (Best to ignore this method unless you really know what you're doing..)
  36550. @see setCurrentMessageThread
  36551. */
  36552. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  36553. /** Returns true if the caller thread has currenltly got the message manager locked.
  36554. see the MessageManagerLock class for more info about this.
  36555. This will be true if the caller is the message thread, because that automatically
  36556. gains a lock while a message is being dispatched.
  36557. */
  36558. bool currentThreadHasLockedMessageManager() const noexcept;
  36559. /** Sends a message to all other JUCE applications that are running.
  36560. @param messageText the string that will be passed to the actionListenerCallback()
  36561. method of the broadcast listeners in the other app.
  36562. @see registerBroadcastListener, ActionListener
  36563. */
  36564. static void broadcastMessage (const String& messageText);
  36565. /** Registers a listener to get told about broadcast messages.
  36566. The actionListenerCallback() callback's string parameter
  36567. is the message passed into broadcastMessage().
  36568. @see broadcastMessage
  36569. */
  36570. void registerBroadcastListener (ActionListener* listener);
  36571. /** Deregisters a broadcast listener. */
  36572. void deregisterBroadcastListener (ActionListener* listener);
  36573. #ifndef DOXYGEN
  36574. // Internal methods - do not use!
  36575. void deliverMessage (Message*);
  36576. void deliverBroadcastMessage (const String&);
  36577. ~MessageManager() noexcept;
  36578. #endif
  36579. private:
  36580. MessageManager() noexcept;
  36581. friend class MessageListener;
  36582. friend class ChangeBroadcaster;
  36583. friend class ActionBroadcaster;
  36584. friend class CallbackMessage;
  36585. static MessageManager* instance;
  36586. SortedSet <const MessageListener*> messageListeners;
  36587. ScopedPointer <ActionBroadcaster> broadcaster;
  36588. friend class JUCEApplication;
  36589. bool quitMessagePosted, quitMessageReceived;
  36590. Thread::ThreadID messageThreadId;
  36591. friend class MessageManagerLock;
  36592. Thread::ThreadID volatile threadWithLock;
  36593. CriticalSection lockingLock;
  36594. void postMessageToQueue (Message* message);
  36595. static bool postMessageToSystemQueue (Message*);
  36596. static void* exitModalLoopCallback (void*);
  36597. static void doPlatformSpecificInitialisation();
  36598. static void doPlatformSpecificShutdown();
  36599. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  36600. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  36601. };
  36602. /** Used to make sure that the calling thread has exclusive access to the message loop.
  36603. Because it's not thread-safe to call any of the Component or other UI classes
  36604. from threads other than the message thread, one of these objects can be used to
  36605. lock the message loop and allow this to be done. The message thread will be
  36606. suspended for the lifetime of the MessageManagerLock object, so create one on
  36607. the stack like this: @code
  36608. void MyThread::run()
  36609. {
  36610. someData = 1234;
  36611. const MessageManagerLock mmLock;
  36612. // the event loop will now be locked so it's safe to make a few calls..
  36613. myComponent->setBounds (newBounds);
  36614. myComponent->repaint();
  36615. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  36616. }
  36617. @endcode
  36618. Obviously be careful not to create one of these and leave it lying around, or
  36619. your app will grind to a halt!
  36620. Another caveat is that using this in conjunction with other CriticalSections
  36621. can create lots of interesting ways of producing a deadlock! In particular, if
  36622. your message thread calls stopThread() for a thread that uses these locks,
  36623. you'll get an (occasional) deadlock..
  36624. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  36625. */
  36626. class JUCE_API MessageManagerLock
  36627. {
  36628. public:
  36629. /** Tries to acquire a lock on the message manager.
  36630. The constructor attempts to gain a lock on the message loop, and the lock will be
  36631. kept for the lifetime of this object.
  36632. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  36633. this method will keep checking whether the thread has been given the
  36634. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  36635. without gaining the lock. If you pass a thread, you must check whether the lock was
  36636. successful by calling lockWasGained(). If this is false, your thread is being told to
  36637. die, so you should take evasive action.
  36638. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  36639. careful when doing this, because it's very easy to deadlock if your message thread
  36640. attempts to call stopThread() on a thread just as that thread attempts to get the
  36641. message lock.
  36642. If the calling thread already has the lock, nothing will be done, so it's safe and
  36643. quick to use these locks recursively.
  36644. E.g.
  36645. @code
  36646. void run()
  36647. {
  36648. ...
  36649. while (! threadShouldExit())
  36650. {
  36651. MessageManagerLock mml (Thread::getCurrentThread());
  36652. if (! mml.lockWasGained())
  36653. return; // another thread is trying to kill us!
  36654. ..do some locked stuff here..
  36655. }
  36656. ..and now the MM is now unlocked..
  36657. }
  36658. @endcode
  36659. */
  36660. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  36661. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  36662. instead of a thread.
  36663. See the MessageManagerLock (Thread*) constructor for details on how this works.
  36664. */
  36665. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  36666. /** Releases the current thread's lock on the message manager.
  36667. Make sure this object is created and deleted by the same thread,
  36668. otherwise there are no guarantees what will happen!
  36669. */
  36670. ~MessageManagerLock() noexcept;
  36671. /** Returns true if the lock was successfully acquired.
  36672. (See the constructor that takes a Thread for more info).
  36673. */
  36674. bool lockWasGained() const noexcept { return locked; }
  36675. private:
  36676. class BlockingMessage;
  36677. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  36678. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  36679. bool locked;
  36680. void init (Thread* thread, ThreadPoolJob* job);
  36681. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  36682. };
  36683. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36684. /*** End of inlined file: juce_MessageManager.h ***/
  36685. #endif
  36686. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36687. /*** Start of inlined file: juce_MultiTimer.h ***/
  36688. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36689. #define __JUCE_MULTITIMER_JUCEHEADER__
  36690. /**
  36691. A type of timer class that can run multiple timers with different frequencies,
  36692. all of which share a single callback.
  36693. This class is very similar to the Timer class, but allows you run multiple
  36694. separate timers, where each one has a unique ID number. The methods in this
  36695. class are exactly equivalent to those in Timer, but with the addition of
  36696. this ID number.
  36697. To use it, you need to create a subclass of MultiTimer, implementing the
  36698. timerCallback() method. Then you can start timers with startTimer(), and
  36699. each time the callback is triggered, it passes in the ID of the timer that
  36700. caused it.
  36701. @see Timer
  36702. */
  36703. class JUCE_API MultiTimer
  36704. {
  36705. protected:
  36706. /** Creates a MultiTimer.
  36707. When created, no timers are running, so use startTimer() to start things off.
  36708. */
  36709. MultiTimer() noexcept;
  36710. /** Creates a copy of another timer.
  36711. Note that this timer will not contain any running timers, even if the one you're
  36712. copying from was running.
  36713. */
  36714. MultiTimer (const MultiTimer& other) noexcept;
  36715. public:
  36716. /** Destructor. */
  36717. virtual ~MultiTimer();
  36718. /** The user-defined callback routine that actually gets called by each of the
  36719. timers that are running.
  36720. It's perfectly ok to call startTimer() or stopTimer() from within this
  36721. callback to change the subsequent intervals.
  36722. */
  36723. virtual void timerCallback (int timerId) = 0;
  36724. /** Starts a timer and sets the length of interval required.
  36725. If the timer is already started, this will reset it, so the
  36726. time between calling this method and the next timer callback
  36727. will not be less than the interval length passed in.
  36728. @param timerId a unique Id number that identifies the timer to
  36729. start. This is the id that will be passed back
  36730. to the timerCallback() method when this timer is
  36731. triggered
  36732. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  36733. rounded up to 1)
  36734. */
  36735. void startTimer (int timerId, int intervalInMilliseconds) noexcept;
  36736. /** Stops a timer.
  36737. If a timer has been started with the given ID number, it will be cancelled.
  36738. No more callbacks will be made for the specified timer after this method returns.
  36739. If this is called from a different thread, any callbacks that may
  36740. be currently executing may be allowed to finish before the method
  36741. returns.
  36742. */
  36743. void stopTimer (int timerId) noexcept;
  36744. /** Checks whether a timer has been started for a specified ID.
  36745. @returns true if a timer with the given ID is running.
  36746. */
  36747. bool isTimerRunning (int timerId) const noexcept;
  36748. /** Returns the interval for a specified timer ID.
  36749. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  36750. is running for the ID number specified.
  36751. */
  36752. int getTimerInterval (int timerId) const noexcept;
  36753. private:
  36754. class MultiTimerCallback;
  36755. SpinLock timerListLock;
  36756. OwnedArray <MultiTimerCallback> timers;
  36757. MultiTimer& operator= (const MultiTimer&);
  36758. };
  36759. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  36760. /*** End of inlined file: juce_MultiTimer.h ***/
  36761. #endif
  36762. #ifndef __JUCE_TIMER_JUCEHEADER__
  36763. #endif
  36764. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36765. /*** Start of inlined file: juce_ArrowButton.h ***/
  36766. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36767. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  36768. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  36769. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36770. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36771. /**
  36772. An effect filter that adds a drop-shadow behind the image's content.
  36773. (This will only work on images/components that aren't opaque, of course).
  36774. When added to a component, this effect will draw a soft-edged
  36775. shadow based on what gets drawn inside it. The shadow will also
  36776. be applied to the component's children.
  36777. For speed, this doesn't use a proper gaussian blur, but cheats by
  36778. using a simple bilinear filter. If you need a really high-quality
  36779. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  36780. @see Component::setComponentEffect
  36781. */
  36782. class JUCE_API DropShadowEffect : public ImageEffectFilter
  36783. {
  36784. public:
  36785. /** Creates a default drop-shadow effect.
  36786. To customise the shadow's appearance, use the setShadowProperties()
  36787. method.
  36788. */
  36789. DropShadowEffect();
  36790. /** Destructor. */
  36791. ~DropShadowEffect();
  36792. /** Sets up parameters affecting the shadow's appearance.
  36793. @param newRadius the (approximate) radius of the blur used
  36794. @param newOpacity the opacity with which the shadow is rendered
  36795. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  36796. component's contents
  36797. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  36798. component's contents
  36799. */
  36800. void setShadowProperties (float newRadius,
  36801. float newOpacity,
  36802. int newShadowOffsetX,
  36803. int newShadowOffsetY);
  36804. /** @internal */
  36805. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  36806. private:
  36807. int offsetX, offsetY;
  36808. float radius, opacity;
  36809. JUCE_LEAK_DETECTOR (DropShadowEffect);
  36810. };
  36811. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36812. /*** End of inlined file: juce_DropShadowEffect.h ***/
  36813. /**
  36814. A button with an arrow in it.
  36815. @see Button
  36816. */
  36817. class JUCE_API ArrowButton : public Button
  36818. {
  36819. public:
  36820. /** Creates an ArrowButton.
  36821. @param buttonName the name to give the button
  36822. @param arrowDirection the direction the arrow should point in, where 0.0 is
  36823. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  36824. @param arrowColour the colour to use for the arrow
  36825. */
  36826. ArrowButton (const String& buttonName,
  36827. float arrowDirection,
  36828. const Colour& arrowColour);
  36829. /** Destructor. */
  36830. ~ArrowButton();
  36831. protected:
  36832. /** @internal */
  36833. void paintButton (Graphics& g,
  36834. bool isMouseOverButton,
  36835. bool isButtonDown);
  36836. /** @internal */
  36837. void buttonStateChanged();
  36838. private:
  36839. Colour colour;
  36840. DropShadowEffect shadow;
  36841. Path path;
  36842. int offset;
  36843. void updateShadowAndOffset();
  36844. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  36845. };
  36846. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  36847. /*** End of inlined file: juce_ArrowButton.h ***/
  36848. #endif
  36849. #ifndef __JUCE_BUTTON_JUCEHEADER__
  36850. #endif
  36851. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36852. /*** Start of inlined file: juce_DrawableButton.h ***/
  36853. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36854. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36855. /*** Start of inlined file: juce_Drawable.h ***/
  36856. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  36857. #define __JUCE_DRAWABLE_JUCEHEADER__
  36858. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  36859. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36860. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36861. /**
  36862. Expresses a coordinate as a dynamically evaluated expression.
  36863. @see RelativePoint, RelativeRectangle
  36864. */
  36865. class JUCE_API RelativeCoordinate
  36866. {
  36867. public:
  36868. /** Creates a zero coordinate. */
  36869. RelativeCoordinate();
  36870. RelativeCoordinate (const Expression& expression);
  36871. RelativeCoordinate (const RelativeCoordinate& other);
  36872. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  36873. /** Creates an absolute position from the parent origin on either the X or Y axis.
  36874. @param absoluteDistanceFromOrigin the distance from the origin
  36875. */
  36876. RelativeCoordinate (double absoluteDistanceFromOrigin);
  36877. /** Recreates a coordinate from a string description.
  36878. The string will be parsed by ExpressionParser::parse().
  36879. @param stringVersion the expression to use
  36880. @see toString
  36881. */
  36882. RelativeCoordinate (const String& stringVersion);
  36883. /** Destructor. */
  36884. ~RelativeCoordinate();
  36885. bool operator== (const RelativeCoordinate& other) const noexcept;
  36886. bool operator!= (const RelativeCoordinate& other) const noexcept;
  36887. /** Calculates the absolute position of this coordinate.
  36888. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36889. be needed to calculate the result.
  36890. */
  36891. double resolve (const Expression::Scope* evaluationScope) const;
  36892. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  36893. This will recursively check any coordinates upon which this one depends.
  36894. */
  36895. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  36896. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  36897. bool isRecursive (const Expression::Scope* evaluationScope) const;
  36898. /** Returns true if this coordinate depends on any other coordinates for its position. */
  36899. bool isDynamic() const;
  36900. /** Changes the value of this coord to make it resolve to the specified position.
  36901. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  36902. or relative position to whatever value is necessary to make its resultant position
  36903. match the position that is provided.
  36904. */
  36905. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  36906. /** Returns the expression that defines this coordinate. */
  36907. const Expression& getExpression() const { return term; }
  36908. /** Returns a string which represents this coordinate.
  36909. For details of the string syntax, see the constructor notes.
  36910. */
  36911. String toString() const;
  36912. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  36913. As well as avoiding using string literals in your code, using these preset values
  36914. has the advantage that all instances of the same string will share the same, reference-counted
  36915. String object, so if you have thousands of points which all refer to the same
  36916. anchor points, this can save a significant amount of memory allocation.
  36917. */
  36918. struct Strings
  36919. {
  36920. static const String parent; /**< "parent" */
  36921. static const String left; /**< "left" */
  36922. static const String right; /**< "right" */
  36923. static const String top; /**< "top" */
  36924. static const String bottom; /**< "bottom" */
  36925. static const String x; /**< "x" */
  36926. static const String y; /**< "y" */
  36927. static const String width; /**< "width" */
  36928. static const String height; /**< "height" */
  36929. };
  36930. struct StandardStrings
  36931. {
  36932. enum Type
  36933. {
  36934. left, right, top, bottom,
  36935. x, y, width, height,
  36936. parent,
  36937. unknown
  36938. };
  36939. static Type getTypeOf (const String& s) noexcept;
  36940. };
  36941. private:
  36942. Expression term;
  36943. };
  36944. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36945. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  36946. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  36947. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36948. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36949. /*** Start of inlined file: juce_RelativePoint.h ***/
  36950. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  36951. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  36952. /**
  36953. An X-Y position stored as a pair of RelativeCoordinate values.
  36954. @see RelativeCoordinate, RelativeRectangle
  36955. */
  36956. class JUCE_API RelativePoint
  36957. {
  36958. public:
  36959. /** Creates a point at the origin. */
  36960. RelativePoint();
  36961. /** Creates an absolute point, relative to the origin. */
  36962. RelativePoint (const Point<float>& absolutePoint);
  36963. /** Creates an absolute point, relative to the origin. */
  36964. RelativePoint (float absoluteX, float absoluteY);
  36965. /** Creates an absolute point from two coordinates. */
  36966. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  36967. /** Creates a point from a stringified representation.
  36968. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  36969. strings is explained in the RelativeCoordinate class.
  36970. @see toString
  36971. */
  36972. RelativePoint (const String& stringVersion);
  36973. bool operator== (const RelativePoint& other) const noexcept;
  36974. bool operator!= (const RelativePoint& other) const noexcept;
  36975. /** Calculates the absolute position of this point.
  36976. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36977. be needed to calculate the result.
  36978. */
  36979. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  36980. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  36981. Calling this will leave any anchor points unchanged, but will set any absolute
  36982. or relative positions to whatever values are necessary to make the resultant position
  36983. match the position that is provided.
  36984. */
  36985. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  36986. /** Returns a string which represents this point.
  36987. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  36988. coordinates, see the RelativeCoordinate constructor notes.
  36989. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  36990. */
  36991. String toString() const;
  36992. /** Returns true if this point depends on any other coordinates for its position. */
  36993. bool isDynamic() const;
  36994. // The actual X and Y coords...
  36995. RelativeCoordinate x, y;
  36996. };
  36997. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  36998. /*** End of inlined file: juce_RelativePoint.h ***/
  36999. /*** Start of inlined file: juce_MarkerList.h ***/
  37000. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  37001. #define __JUCE_MARKERLIST_JUCEHEADER__
  37002. class Component;
  37003. /**
  37004. Holds a set of named marker points along a one-dimensional axis.
  37005. This class is used to store sets of X and Y marker points in components.
  37006. @see Component::getMarkers().
  37007. */
  37008. class JUCE_API MarkerList
  37009. {
  37010. public:
  37011. /** Creates an empty marker list. */
  37012. MarkerList();
  37013. /** Creates a copy of another marker list. */
  37014. MarkerList (const MarkerList& other);
  37015. /** Copies another marker list to this one. */
  37016. MarkerList& operator= (const MarkerList& other);
  37017. /** Destructor. */
  37018. ~MarkerList();
  37019. /** Represents a marker in a MarkerList. */
  37020. class JUCE_API Marker
  37021. {
  37022. public:
  37023. /** Creates a copy of another Marker. */
  37024. Marker (const Marker& other);
  37025. /** Creates a Marker with a given name and position. */
  37026. Marker (const String& name, const RelativeCoordinate& position);
  37027. /** The marker's name. */
  37028. String name;
  37029. /** The marker's position.
  37030. The expression used to define the coordinate may use the names of other
  37031. markers, so that markers can be linked in arbitrary ways, but be careful
  37032. not to create recursive loops of markers whose positions are based on each
  37033. other! It can also refer to "parent.right" and "parent.bottom" so that you
  37034. can set markers which are relative to the size of the component that contains
  37035. them.
  37036. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  37037. */
  37038. RelativeCoordinate position;
  37039. /** Returns true if both the names and positions of these two markers match. */
  37040. bool operator== (const Marker&) const noexcept;
  37041. /** Returns true if either the name or position of these two markers differ. */
  37042. bool operator!= (const Marker&) const noexcept;
  37043. };
  37044. /** Returns the number of markers in the list. */
  37045. int getNumMarkers() const noexcept;
  37046. /** Returns one of the markers in the list, by its index. */
  37047. const Marker* getMarker (int index) const noexcept;
  37048. /** Returns a named marker, or 0 if no such name is found.
  37049. Note that name comparisons are case-sensitive.
  37050. */
  37051. const Marker* getMarker (const String& name) const noexcept;
  37052. /** Evaluates the given marker and returns its absolute position.
  37053. The parent component must be supplied in case the marker's expression refers to
  37054. the size of its parent component.
  37055. */
  37056. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  37057. /** Sets the position of a marker.
  37058. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  37059. new marker is added.
  37060. */
  37061. void setMarker (const String& name, const RelativeCoordinate& position);
  37062. /** Deletes the marker at the given list index. */
  37063. void removeMarker (int index);
  37064. /** Deletes the marker with the given name. */
  37065. void removeMarker (const String& name);
  37066. /** Returns true if all the markers in these two lists match exactly. */
  37067. bool operator== (const MarkerList& other) const noexcept;
  37068. /** Returns true if not all the markers in these two lists match exactly. */
  37069. bool operator!= (const MarkerList& other) const noexcept;
  37070. /**
  37071. A class for receiving events when changes are made to a MarkerList.
  37072. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37073. method, and it will be called when markers are moved, added, or deleted.
  37074. @see MarkerList::addListener, MarkerList::removeListener
  37075. */
  37076. class JUCE_API Listener
  37077. {
  37078. public:
  37079. /** Destructor. */
  37080. virtual ~Listener() {}
  37081. /** Called when something in the given marker list changes. */
  37082. virtual void markersChanged (MarkerList* markerList) = 0;
  37083. /** Called when the given marker list is being deleted. */
  37084. virtual void markerListBeingDeleted (MarkerList* markerList);
  37085. };
  37086. /** Registers a listener that will be called when the markers are changed. */
  37087. void addListener (Listener* listener);
  37088. /** Deregisters a previously-registered listener. */
  37089. void removeListener (Listener* listener);
  37090. /** Synchronously calls markersChanged() on all the registered listeners. */
  37091. void markersHaveChanged();
  37092. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37093. class ValueTreeWrapper
  37094. {
  37095. public:
  37096. ValueTreeWrapper (const ValueTree& state);
  37097. ValueTree& getState() noexcept { return state; }
  37098. int getNumMarkers() const;
  37099. const ValueTree getMarkerState (int index) const;
  37100. const ValueTree getMarkerState (const String& name) const;
  37101. bool containsMarker (const ValueTree& state) const;
  37102. const MarkerList::Marker getMarker (const ValueTree& state) const;
  37103. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37104. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37105. void applyTo (MarkerList& markerList);
  37106. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37107. static const Identifier markerTag, nameProperty, posProperty;
  37108. private:
  37109. ValueTree state;
  37110. };
  37111. private:
  37112. OwnedArray<Marker> markers;
  37113. ListenerList<Listener> listeners;
  37114. JUCE_LEAK_DETECTOR (MarkerList);
  37115. };
  37116. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37117. /*** End of inlined file: juce_MarkerList.h ***/
  37118. /**
  37119. Base class for Component::Positioners that are based upon relative coordinates.
  37120. */
  37121. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37122. public ComponentListener,
  37123. public MarkerList::Listener
  37124. {
  37125. public:
  37126. RelativeCoordinatePositionerBase (Component& component_);
  37127. ~RelativeCoordinatePositionerBase();
  37128. void componentMovedOrResized (Component&, bool, bool);
  37129. void componentParentHierarchyChanged (Component&);
  37130. void componentChildrenChanged (Component& component);
  37131. void componentBeingDeleted (Component& component);
  37132. void markersChanged (MarkerList*);
  37133. void markerListBeingDeleted (MarkerList* markerList);
  37134. void apply();
  37135. bool addCoordinate (const RelativeCoordinate& coord);
  37136. bool addPoint (const RelativePoint& point);
  37137. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37138. class ComponentScope : public Expression::Scope
  37139. {
  37140. public:
  37141. ComponentScope (Component& component_);
  37142. const Expression getSymbolValue (const String& symbol) const;
  37143. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37144. const String getScopeUID() const;
  37145. protected:
  37146. Component& component;
  37147. Component* findSiblingComponent (const String& componentID) const;
  37148. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37149. private:
  37150. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37151. };
  37152. protected:
  37153. virtual bool registerCoordinates() = 0;
  37154. virtual void applyToComponentBounds() = 0;
  37155. private:
  37156. class DependencyFinderScope;
  37157. friend class DependencyFinderScope;
  37158. Array <Component*> sourceComponents;
  37159. Array <MarkerList*> sourceMarkerLists;
  37160. bool registeredOk;
  37161. void registerComponentListener (Component& comp);
  37162. void registerMarkerListListener (MarkerList* const list);
  37163. void unregisterListeners();
  37164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37165. };
  37166. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37167. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37168. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37169. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37170. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37171. /**
  37172. Loads and maintains a tree of Components from a ValueTree that represents them.
  37173. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37174. this class lets you register a set of type-handlers for the different components that
  37175. are involved, and then uses these types to re-create a set of components from its
  37176. stored state.
  37177. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37178. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37179. all the items in your tree. Then you can call getComponent() to build the component.
  37180. Once you've got the component you can either take it and delete the ComponentBuilder
  37181. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37182. ValueTree and automatically update the component to reflect these changes.
  37183. */
  37184. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37185. {
  37186. public:
  37187. /** Creates a ComponentBuilder that will use the given state.
  37188. Once you've created your builder, you should use registerTypeHandler() to register some
  37189. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37190. to get the actual component.
  37191. */
  37192. explicit ComponentBuilder (const ValueTree& state);
  37193. /** Destructor. */
  37194. ~ComponentBuilder();
  37195. /** Returns the ValueTree that this builder is working with. */
  37196. ValueTree& getState() noexcept { return state; }
  37197. /** Returns the ValueTree that this builder is working with. */
  37198. const ValueTree& getState() const noexcept { return state; }
  37199. /** Returns the builder's component (creating it if necessary).
  37200. The first time that this method is called, the builder will attempt to create a component
  37201. from the ValueTree, so you must have registered some suitable type handlers before calling
  37202. this. If there's a problem and the component can't be created, this method returns 0.
  37203. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37204. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37205. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37206. call createComponent() instead.
  37207. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37208. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37209. as they may be changed or removed.
  37210. */
  37211. Component* getManagedComponent();
  37212. /** Creates and returns a new instance of the component that the ValueTree represents.
  37213. The caller is responsible for using and deleting the object that is returned. Unlike
  37214. getManagedComponent(), the component that is returned will not be updated by the builder.
  37215. */
  37216. Component* createComponent();
  37217. /**
  37218. The class is a base class for objects that manage the loading of a type of component
  37219. from a ValueTree.
  37220. To store and re-load a tree of components as a ValueTree, each component type must have
  37221. a TypeHandler to represent it.
  37222. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37223. */
  37224. class JUCE_API TypeHandler
  37225. {
  37226. public:
  37227. /** Creates a TypeHandler.
  37228. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37229. */
  37230. explicit TypeHandler (const Identifier& valueTreeType);
  37231. /** Destructor. */
  37232. virtual ~TypeHandler();
  37233. /** Returns the type of the ValueTrees that this handler can parse. */
  37234. const Identifier& getType() const noexcept { return valueTreeType; }
  37235. /** Returns the builder that this type is registered with. */
  37236. ComponentBuilder* getBuilder() const noexcept;
  37237. /** This method must create a new component from the given state, add it to the specified
  37238. parent component (which may be null), and return it.
  37239. The ValueTree will have been pre-checked to make sure that its type matches the type
  37240. that this handler supports.
  37241. There's no need to set the new Component's ID to match that of the state - the builder
  37242. will take care of that itself.
  37243. */
  37244. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37245. /** This method must update an existing component from a new ValueTree state.
  37246. A component that has been created with addNewComponentFromState() may need to be updated
  37247. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37248. whatever's necessary to update the component from the new state provided.
  37249. The ValueTree will have been pre-checked to make sure that its type matches the type
  37250. that this handler supports, and the component will have been created by this type's
  37251. addNewComponentFromState() method.
  37252. */
  37253. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37254. private:
  37255. friend class ComponentBuilder;
  37256. ComponentBuilder* builder;
  37257. const Identifier valueTreeType;
  37258. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37259. };
  37260. /** Adds a type handler that the builder can use when trying to load components.
  37261. @see Drawable::registerDrawableTypeHandlers()
  37262. */
  37263. void registerTypeHandler (TypeHandler* type);
  37264. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37265. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37266. /** Returns the number of registered type handlers.
  37267. @see getHandler, registerTypeHandler
  37268. */
  37269. int getNumHandlers() const noexcept;
  37270. /** Returns one of the registered type handlers.
  37271. @see getNumHandlers, registerTypeHandler
  37272. */
  37273. TypeHandler* getHandler (int index) const noexcept;
  37274. /** This class is used when references to images need to be stored in ValueTrees.
  37275. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37276. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37277. your app.
  37278. When you're loading components from a ValueTree that may need a way of loading images, you
  37279. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37280. trying to load the component.
  37281. @see ComponentBuilder::setImageProvider()
  37282. */
  37283. class JUCE_API ImageProvider
  37284. {
  37285. public:
  37286. ImageProvider() {}
  37287. virtual ~ImageProvider() {}
  37288. /** Retrieves the image associated with this identifier, which could be any
  37289. kind of string, number, filename, etc.
  37290. The image that is returned will be owned by the caller, but it may come
  37291. from the ImageCache.
  37292. */
  37293. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37294. /** Returns an identifier to be used to refer to a given image.
  37295. This is used when a reference to an image is stored in a ValueTree.
  37296. */
  37297. virtual const var getIdentifierForImage (const Image& image) = 0;
  37298. };
  37299. /** Gives the builder an ImageProvider object that the type handlers can use when
  37300. loading images from stored references.
  37301. The object that is passed in is not owned by the builder, so the caller must delete
  37302. it when it is no longer needed, but not while the builder may still be using it. To
  37303. clear the image provider, just call setImageProvider (nullptr).
  37304. */
  37305. void setImageProvider (ImageProvider* newImageProvider) noexcept;
  37306. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37307. ImageProvider* getImageProvider() const noexcept;
  37308. /** Updates the children of a parent component by updating them from the children of
  37309. a given ValueTree.
  37310. */
  37311. void updateChildComponents (Component& parent, const ValueTree& children);
  37312. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37313. for that component.
  37314. */
  37315. static const Identifier idProperty;
  37316. /** @internal */
  37317. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37318. /** @internal */
  37319. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37320. /** @internal */
  37321. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37322. /** @internal */
  37323. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37324. /** @internal */
  37325. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37326. private:
  37327. ValueTree state;
  37328. OwnedArray <TypeHandler> types;
  37329. ScopedPointer<Component> component;
  37330. ImageProvider* imageProvider;
  37331. #if JUCE_DEBUG
  37332. WeakReference<Component> componentRef;
  37333. #endif
  37334. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37335. };
  37336. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37337. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37338. class DrawableComposite;
  37339. /**
  37340. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37341. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37342. */
  37343. class JUCE_API Drawable : public Component
  37344. {
  37345. protected:
  37346. /** The base class can't be instantiated directly.
  37347. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37348. */
  37349. Drawable();
  37350. public:
  37351. /** Destructor. */
  37352. virtual ~Drawable();
  37353. /** Creates a deep copy of this Drawable object.
  37354. Use this to create a new copy of this and any sub-objects in the tree.
  37355. */
  37356. virtual Drawable* createCopy() const = 0;
  37357. /** Renders this Drawable object.
  37358. Note that the preferred way to render a drawable in future is by using it
  37359. as a component and adding it to a parent, so you might want to consider that
  37360. before using this method.
  37361. @see drawWithin
  37362. */
  37363. void draw (Graphics& g, float opacity,
  37364. const AffineTransform& transform = AffineTransform::identity) const;
  37365. /** Renders the Drawable at a given offset within the Graphics context.
  37366. The co-ordinates passed-in are used to translate the object relative to its own
  37367. origin before drawing it - this is basically a quick way of saying:
  37368. @code
  37369. draw (g, AffineTransform::translation (x, y)).
  37370. @endcode
  37371. Note that the preferred way to render a drawable in future is by using it
  37372. as a component and adding it to a parent, so you might want to consider that
  37373. before using this method.
  37374. */
  37375. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37376. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37377. changing its aspect-ratio.
  37378. The object can placed arbitrarily within the rectangle based on a Justification type,
  37379. and can either be made as big as possible, or just reduced to fit.
  37380. Note that the preferred way to render a drawable in future is by using it
  37381. as a component and adding it to a parent, so you might want to consider that
  37382. before using this method.
  37383. @param g the graphics context to render onto
  37384. @param destArea the target rectangle to fit the drawable into
  37385. @param placement defines the alignment and rescaling to use to fit
  37386. this object within the target rectangle.
  37387. @param opacity the opacity to use, in the range 0 to 1.0
  37388. */
  37389. void drawWithin (Graphics& g,
  37390. const Rectangle<float>& destArea,
  37391. const RectanglePlacement& placement,
  37392. float opacity) const;
  37393. /** Resets any transformations on this drawable, and positions its origin within
  37394. its parent component.
  37395. */
  37396. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37397. /** Sets a transform for this drawable that will position it within the specified
  37398. area of its parent component.
  37399. */
  37400. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37401. /** Returns the DrawableComposite that contains this object, if there is one. */
  37402. DrawableComposite* getParent() const;
  37403. /** Tries to turn some kind of image file into a drawable.
  37404. The data could be an image that the ImageFileFormat class understands, or it
  37405. could be SVG.
  37406. */
  37407. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37408. /** Tries to turn a stream containing some kind of image data into a drawable.
  37409. The data could be an image that the ImageFileFormat class understands, or it
  37410. could be SVG.
  37411. */
  37412. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37413. /** Tries to turn a file containing some kind of image data into a drawable.
  37414. The data could be an image that the ImageFileFormat class understands, or it
  37415. could be SVG.
  37416. */
  37417. static Drawable* createFromImageFile (const File& file);
  37418. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37419. into a Drawable tree.
  37420. The object returned must be deleted by the caller. If something goes wrong
  37421. while parsing, it may return 0.
  37422. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37423. implementation, but it can return the basic vector objects.
  37424. */
  37425. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37426. /** Tries to create a Drawable from a previously-saved ValueTree.
  37427. The ValueTree must have been created by the createValueTree() method.
  37428. If there are any images used within the drawable, you'll need to provide a valid
  37429. ImageProvider object that can be used to retrieve these images from whatever type
  37430. of identifier is used to represent them.
  37431. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37432. */
  37433. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37434. /** Creates a ValueTree to represent this Drawable.
  37435. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37436. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37437. object that can be used to create storable representations of them.
  37438. */
  37439. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37440. /** Returns the area that this drawble covers.
  37441. The result is expressed in this drawable's own coordinate space, and does not take
  37442. into account any transforms that may be applied to the component.
  37443. */
  37444. virtual const Rectangle<float> getDrawableBounds() const = 0;
  37445. /** Internal class used to manage ValueTrees that represent Drawables. */
  37446. class ValueTreeWrapperBase
  37447. {
  37448. public:
  37449. ValueTreeWrapperBase (const ValueTree& state);
  37450. ValueTree& getState() noexcept { return state; }
  37451. const String getID() const;
  37452. void setID (const String& newID);
  37453. ValueTree state;
  37454. };
  37455. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37456. load all the different Drawable types from a saved state.
  37457. @see ComponentBuilder::registerTypeHandler()
  37458. */
  37459. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37460. protected:
  37461. friend class DrawableComposite;
  37462. friend class DrawableShape;
  37463. /** @internal */
  37464. void transformContextToCorrectOrigin (Graphics& g);
  37465. /** @internal */
  37466. void parentHierarchyChanged();
  37467. /** @internal */
  37468. void setBoundsToEnclose (const Rectangle<float>& area);
  37469. Point<int> originRelativeToComponent;
  37470. #ifndef DOXYGEN
  37471. /** Internal utility class used by Drawables. */
  37472. template <class DrawableType>
  37473. class Positioner : public RelativeCoordinatePositionerBase
  37474. {
  37475. public:
  37476. Positioner (DrawableType& component_)
  37477. : RelativeCoordinatePositionerBase (component_),
  37478. owner (component_)
  37479. {}
  37480. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  37481. void applyToComponentBounds()
  37482. {
  37483. ComponentScope scope (getComponent());
  37484. owner.recalculateCoordinates (&scope);
  37485. }
  37486. void applyNewBounds (const Rectangle<int>&)
  37487. {
  37488. jassertfalse; // drawables can't be resized directly!
  37489. }
  37490. private:
  37491. DrawableType& owner;
  37492. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  37493. };
  37494. #endif
  37495. private:
  37496. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  37497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  37498. };
  37499. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  37500. /*** End of inlined file: juce_Drawable.h ***/
  37501. /**
  37502. A button that displays a Drawable.
  37503. Up to three Drawable objects can be given to this button, to represent the
  37504. 'normal', 'over' and 'down' states.
  37505. @see Button
  37506. */
  37507. class JUCE_API DrawableButton : public Button
  37508. {
  37509. public:
  37510. enum ButtonStyle
  37511. {
  37512. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  37513. ImageRaw, /**< The button will just display the images in their normal size and position.
  37514. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  37515. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  37516. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  37517. };
  37518. /** Creates a DrawableButton.
  37519. After creating one of these, use setImages() to specify the drawables to use.
  37520. @param buttonName the name to give the component
  37521. @param buttonStyle the layout to use
  37522. @see ButtonStyle, setButtonStyle, setImages
  37523. */
  37524. DrawableButton (const String& buttonName,
  37525. ButtonStyle buttonStyle);
  37526. /** Destructor. */
  37527. ~DrawableButton();
  37528. /** Sets up the images to draw for the various button states.
  37529. The button will keep its own internal copies of these drawables.
  37530. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  37531. will be made of the object passed-in if it is non-zero.
  37532. @param overImage the thing to draw for the button's 'over' state - if this is
  37533. zero, the button's normal image will be used when the mouse is
  37534. over it. An internal copy will be made of the object passed-in
  37535. if it is non-zero.
  37536. @param downImage the thing to draw for the button's 'down' state - if this is
  37537. zero, the 'over' image will be used instead (or the normal image
  37538. as a last resort). An internal copy will be made of the object
  37539. passed-in if it is non-zero.
  37540. @param disabledImage an image to draw when the button is disabled. If this is zero,
  37541. the normal image will be drawn with a reduced opacity instead.
  37542. An internal copy will be made of the object passed-in if it is
  37543. non-zero.
  37544. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  37545. state is 'on'. If this is 0, the normal image is used instead
  37546. @param overImageOn same as the overImage, but this is used when the button's toggle
  37547. state is 'on'. If this is 0, the normalImageOn is drawn instead
  37548. @param downImageOn same as the downImage, but this is used when the button's toggle
  37549. state is 'on'. If this is 0, the overImageOn is drawn instead
  37550. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  37551. state is 'on'. If this is 0, the normal image will be drawn instead
  37552. with a reduced opacity
  37553. */
  37554. void setImages (const Drawable* normalImage,
  37555. const Drawable* overImage = nullptr,
  37556. const Drawable* downImage = nullptr,
  37557. const Drawable* disabledImage = nullptr,
  37558. const Drawable* normalImageOn = nullptr,
  37559. const Drawable* overImageOn = nullptr,
  37560. const Drawable* downImageOn = nullptr,
  37561. const Drawable* disabledImageOn = nullptr);
  37562. /** Changes the button's style.
  37563. @see ButtonStyle
  37564. */
  37565. void setButtonStyle (ButtonStyle newStyle);
  37566. /** Changes the button's background colours.
  37567. The toggledOffColour is the colour to use when the button's toggle state
  37568. is off, and toggledOnColour when it's on.
  37569. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  37570. used to fill the background of the component.
  37571. For an ImageOnButtonBackground style, the colour is used to draw the
  37572. button's lozenge shape and exactly how the colour's used will depend
  37573. on the LookAndFeel.
  37574. */
  37575. void setBackgroundColours (const Colour& toggledOffColour,
  37576. const Colour& toggledOnColour);
  37577. /** Returns the current background colour being used.
  37578. @see setBackgroundColour
  37579. */
  37580. const Colour& getBackgroundColour() const noexcept;
  37581. /** Gives the button an optional amount of space around the edge of the drawable.
  37582. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  37583. ones on a button background. If the button is too small for the given gap, a
  37584. smaller gap will be used.
  37585. By default there's a gap of about 3 pixels.
  37586. */
  37587. void setEdgeIndent (int numPixelsIndent);
  37588. /** Returns the image that the button is currently displaying. */
  37589. Drawable* getCurrentImage() const noexcept;
  37590. Drawable* getNormalImage() const noexcept;
  37591. Drawable* getOverImage() const noexcept;
  37592. Drawable* getDownImage() const noexcept;
  37593. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37594. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37595. methods.
  37596. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37597. */
  37598. enum ColourIds
  37599. {
  37600. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  37601. };
  37602. protected:
  37603. /** @internal */
  37604. void paintButton (Graphics& g,
  37605. bool isMouseOverButton,
  37606. bool isButtonDown);
  37607. /** @internal */
  37608. void buttonStateChanged();
  37609. /** @internal */
  37610. void resized();
  37611. private:
  37612. ButtonStyle style;
  37613. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  37614. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  37615. Drawable* currentImage;
  37616. Colour backgroundOff, backgroundOn;
  37617. int edgeIndent;
  37618. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  37619. };
  37620. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37621. /*** End of inlined file: juce_DrawableButton.h ***/
  37622. #endif
  37623. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37624. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  37625. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37626. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37627. /**
  37628. A button showing an underlined weblink, that will launch the link
  37629. when it's clicked.
  37630. @see Button
  37631. */
  37632. class JUCE_API HyperlinkButton : public Button
  37633. {
  37634. public:
  37635. /** Creates a HyperlinkButton.
  37636. @param linkText the text that will be displayed in the button - this is
  37637. also set as the Component's name, but the text can be
  37638. changed later with the Button::getButtonText() method
  37639. @param linkURL the URL to launch when the user clicks the button
  37640. */
  37641. HyperlinkButton (const String& linkText,
  37642. const URL& linkURL);
  37643. /** Destructor. */
  37644. ~HyperlinkButton();
  37645. /** Changes the font to use for the text.
  37646. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  37647. to match the size of the component.
  37648. */
  37649. void setFont (const Font& newFont,
  37650. bool resizeToMatchComponentHeight,
  37651. const Justification& justificationType = Justification::horizontallyCentred);
  37652. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37653. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37654. methods.
  37655. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37656. */
  37657. enum ColourIds
  37658. {
  37659. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  37660. };
  37661. /** Changes the URL that the button will trigger. */
  37662. void setURL (const URL& newURL) noexcept;
  37663. /** Returns the URL that the button will trigger. */
  37664. const URL& getURL() const noexcept { return url; }
  37665. /** Resizes the button horizontally to fit snugly around the text.
  37666. This won't affect the button's height.
  37667. */
  37668. void changeWidthToFitText();
  37669. protected:
  37670. /** @internal */
  37671. void clicked();
  37672. /** @internal */
  37673. void colourChanged();
  37674. /** @internal */
  37675. void paintButton (Graphics& g,
  37676. bool isMouseOverButton,
  37677. bool isButtonDown);
  37678. private:
  37679. URL url;
  37680. Font font;
  37681. bool resizeFont;
  37682. Justification justification;
  37683. Font getFontToUse() const;
  37684. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  37685. };
  37686. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37687. /*** End of inlined file: juce_HyperlinkButton.h ***/
  37688. #endif
  37689. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37690. /*** Start of inlined file: juce_ImageButton.h ***/
  37691. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37692. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  37693. /**
  37694. As the title suggests, this is a button containing an image.
  37695. The colour and transparency of the image can be set to vary when the
  37696. button state changes.
  37697. @see Button, ShapeButton, TextButton
  37698. */
  37699. class JUCE_API ImageButton : public Button
  37700. {
  37701. public:
  37702. /** Creates an ImageButton.
  37703. Use setImage() to specify the image to use. The colours and opacities that
  37704. are specified here can be changed later using setDrawingOptions().
  37705. @param name the name to give the component
  37706. */
  37707. explicit ImageButton (const String& name);
  37708. /** Destructor. */
  37709. ~ImageButton();
  37710. /** Sets up the images to draw in various states.
  37711. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  37712. resized to the same dimensions as the normal image
  37713. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  37714. button when the button's size changes
  37715. @param preserveImageProportions if true then any rescaling of the image to fit
  37716. the button will keep the image's x and y proportions
  37717. correct - i.e. it won't distort its shape, although
  37718. this might create gaps around the edges
  37719. @param normalImage the image to use when the button is in its normal state.
  37720. button no longer needs it.
  37721. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  37722. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  37723. normal image - if this colour is transparent, no overlay
  37724. will be drawn. The overlay will be drawn over the top of the
  37725. image, so you can basically add a solid or semi-transparent
  37726. colour to the image to brighten or darken it
  37727. @param overImage the image to use when the mouse is over the button. If
  37728. you want to use the same image as was set in the normalImage
  37729. parameter, this value can be a null image.
  37730. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  37731. is over the button
  37732. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  37733. image when the mouse is over - if this colour is transparent,
  37734. no overlay will be drawn
  37735. @param downImage an image to use when the button is pressed down. If set
  37736. to a null image, the 'over' image will be drawn instead (or the
  37737. normal image if there isn't an 'over' image either).
  37738. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  37739. is pressed
  37740. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  37741. image when the button is pressed down - if this colour is
  37742. transparent, no overlay will be drawn
  37743. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  37744. whenever it's inside the button's bounding rectangle. If
  37745. set to values higher than 0, the mouse will only be
  37746. considered to be over the image when the value of the
  37747. image's alpha channel at that position is greater than
  37748. this level.
  37749. */
  37750. void setImages (bool resizeButtonNowToFitThisImage,
  37751. bool rescaleImagesWhenButtonSizeChanges,
  37752. bool preserveImageProportions,
  37753. const Image& normalImage,
  37754. float imageOpacityWhenNormal,
  37755. const Colour& overlayColourWhenNormal,
  37756. const Image& overImage,
  37757. float imageOpacityWhenOver,
  37758. const Colour& overlayColourWhenOver,
  37759. const Image& downImage,
  37760. float imageOpacityWhenDown,
  37761. const Colour& overlayColourWhenDown,
  37762. float hitTestAlphaThreshold = 0.0f);
  37763. /** Returns the currently set 'normal' image. */
  37764. Image getNormalImage() const;
  37765. /** Returns the image that's drawn when the mouse is over the button.
  37766. If a valid 'over' image has been set, this will return it; otherwise it'll
  37767. just return the normal image.
  37768. */
  37769. Image getOverImage() const;
  37770. /** Returns the image that's drawn when the button is held down.
  37771. If a valid 'down' image has been set, this will return it; otherwise it'll
  37772. return the 'over' image or normal image, depending on what's available.
  37773. */
  37774. Image getDownImage() const;
  37775. protected:
  37776. /** @internal */
  37777. bool hitTest (int x, int y);
  37778. /** @internal */
  37779. void paintButton (Graphics& g,
  37780. bool isMouseOverButton,
  37781. bool isButtonDown);
  37782. private:
  37783. bool scaleImageToFit, preserveProportions;
  37784. unsigned char alphaThreshold;
  37785. int imageX, imageY, imageW, imageH;
  37786. Image normalImage, overImage, downImage;
  37787. float normalOpacity, overOpacity, downOpacity;
  37788. Colour normalOverlay, overOverlay, downOverlay;
  37789. Image getCurrentImage() const;
  37790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  37791. };
  37792. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  37793. /*** End of inlined file: juce_ImageButton.h ***/
  37794. #endif
  37795. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37796. /*** Start of inlined file: juce_ShapeButton.h ***/
  37797. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37798. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  37799. /**
  37800. A button that contains a filled shape.
  37801. @see Button, ImageButton, TextButton, ArrowButton
  37802. */
  37803. class JUCE_API ShapeButton : public Button
  37804. {
  37805. public:
  37806. /** Creates a ShapeButton.
  37807. @param name a name to give the component - see Component::setName()
  37808. @param normalColour the colour to fill the shape with when the mouse isn't over
  37809. @param overColour the colour to use when the mouse is over the shape
  37810. @param downColour the colour to use when the button is in the pressed-down state
  37811. */
  37812. ShapeButton (const String& name,
  37813. const Colour& normalColour,
  37814. const Colour& overColour,
  37815. const Colour& downColour);
  37816. /** Destructor. */
  37817. ~ShapeButton();
  37818. /** Sets the shape to use.
  37819. @param newShape the shape to use
  37820. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  37821. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  37822. the button is resized
  37823. @param hasDropShadow if true, the button will be given a drop-shadow effect
  37824. */
  37825. void setShape (const Path& newShape,
  37826. bool resizeNowToFitThisShape,
  37827. bool maintainShapeProportions,
  37828. bool hasDropShadow);
  37829. /** Set the colours to use for drawing the shape.
  37830. @param normalColour the colour to fill the shape with when the mouse isn't over
  37831. @param overColour the colour to use when the mouse is over the shape
  37832. @param downColour the colour to use when the button is in the pressed-down state
  37833. */
  37834. void setColours (const Colour& normalColour,
  37835. const Colour& overColour,
  37836. const Colour& downColour);
  37837. /** Sets up an outline to draw around the shape.
  37838. @param outlineColour the colour to use
  37839. @param outlineStrokeWidth the thickness of line to draw
  37840. */
  37841. void setOutline (const Colour& outlineColour,
  37842. float outlineStrokeWidth);
  37843. protected:
  37844. /** @internal */
  37845. void paintButton (Graphics& g,
  37846. bool isMouseOverButton,
  37847. bool isButtonDown);
  37848. private:
  37849. Colour normalColour, overColour, downColour, outlineColour;
  37850. DropShadowEffect shadow;
  37851. Path shape;
  37852. bool maintainShapeProportions;
  37853. float outlineWidth;
  37854. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  37855. };
  37856. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  37857. /*** End of inlined file: juce_ShapeButton.h ***/
  37858. #endif
  37859. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  37860. #endif
  37861. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37862. /*** Start of inlined file: juce_ToggleButton.h ***/
  37863. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37864. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37865. /**
  37866. A button that can be toggled on/off.
  37867. All buttons can be toggle buttons, but this lets you create one of the
  37868. standard ones which has a tick-box and a text label next to it.
  37869. @see Button, DrawableButton, TextButton
  37870. */
  37871. class JUCE_API ToggleButton : public Button
  37872. {
  37873. public:
  37874. /** Creates a ToggleButton.
  37875. @param buttonText the text to put in the button (the component's name is also
  37876. initially set to this string, but these can be changed later
  37877. using the setName() and setButtonText() methods)
  37878. */
  37879. explicit ToggleButton (const String& buttonText = String::empty);
  37880. /** Destructor. */
  37881. ~ToggleButton();
  37882. /** Resizes the button to fit neatly around its current text.
  37883. The button's height won't be affected, only its width.
  37884. */
  37885. void changeWidthToFitText();
  37886. /** A set of colour IDs to use to change the colour of various aspects of the button.
  37887. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37888. methods.
  37889. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37890. */
  37891. enum ColourIds
  37892. {
  37893. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  37894. };
  37895. protected:
  37896. /** @internal */
  37897. void paintButton (Graphics& g,
  37898. bool isMouseOverButton,
  37899. bool isButtonDown);
  37900. /** @internal */
  37901. void colourChanged();
  37902. private:
  37903. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  37904. };
  37905. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37906. /*** End of inlined file: juce_ToggleButton.h ***/
  37907. #endif
  37908. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37909. /*** Start of inlined file: juce_ToolbarButton.h ***/
  37910. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37911. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37912. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  37913. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37914. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37915. /*** Start of inlined file: juce_Toolbar.h ***/
  37916. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37917. #define __JUCE_TOOLBAR_JUCEHEADER__
  37918. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  37919. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37920. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37921. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  37922. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37923. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37924. /**
  37925. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  37926. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  37927. derive your component from this class, and make sure that it is somewhere inside a
  37928. DragAndDropContainer component.
  37929. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37930. the operating system onto your component, you don't need any of these classes: instead
  37931. see the FileDragAndDropTarget class.
  37932. @see DragAndDropContainer, FileDragAndDropTarget
  37933. */
  37934. class JUCE_API DragAndDropTarget
  37935. {
  37936. public:
  37937. /** Destructor. */
  37938. virtual ~DragAndDropTarget() {}
  37939. /** Contains details about the source of a drag-and-drop operation.
  37940. The contents of this
  37941. */
  37942. class JUCE_API SourceDetails
  37943. {
  37944. public:
  37945. /** Creates a SourceDetails object from its various settings. */
  37946. SourceDetails (const var& description, Component* sourceComponent, const Point<int>& localPosition) noexcept;
  37947. /** A descriptor for the drag - this is set DragAndDropContainer::startDragging(). */
  37948. var description;
  37949. /** The component from the drag operation was started. */
  37950. WeakReference<Component> sourceComponent;
  37951. /** The local position of the mouse, relative to the target component.
  37952. Note that for calls such as isInterestedInDragSource(), this may be a null position.
  37953. */
  37954. Point<int> localPosition;
  37955. };
  37956. /** Callback to check whether this target is interested in the type of object being
  37957. dragged.
  37958. @param dragSourceDetails contains information about the source of the drag operation.
  37959. @returns true if this component wants to receive the other callbacks regarging this
  37960. type of object; if it returns false, no other callbacks will be made.
  37961. */
  37962. virtual bool isInterestedInDragSource (const SourceDetails& dragSourceDetails) = 0;
  37963. /** Callback to indicate that something is being dragged over this component.
  37964. This gets called when the user moves the mouse into this component while dragging
  37965. something.
  37966. Use this callback as a trigger to make your component repaint itself to give the
  37967. user feedback about whether the item can be dropped here or not.
  37968. @param dragSourceDetails contains information about the source of the drag operation.
  37969. @see itemDragExit
  37970. */
  37971. virtual void itemDragEnter (const SourceDetails& dragSourceDetails);
  37972. /** Callback to indicate that the user is dragging something over this component.
  37973. This gets called when the user moves the mouse over this component while dragging
  37974. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  37975. this lets you know what happens in-between.
  37976. @param dragSourceDetails contains information about the source of the drag operation.
  37977. */
  37978. virtual void itemDragMove (const SourceDetails& dragSourceDetails);
  37979. /** Callback to indicate that something has been dragged off the edge of this component.
  37980. This gets called when the user moves the mouse out of this component while dragging
  37981. something.
  37982. If you've used itemDragEnter() to repaint your component and give feedback, use this
  37983. as a signal to repaint it in its normal state.
  37984. @param dragSourceDetails contains information about the source of the drag operation.
  37985. @see itemDragEnter
  37986. */
  37987. virtual void itemDragExit (const SourceDetails& dragSourceDetails);
  37988. /** Callback to indicate that the user has dropped something onto this component.
  37989. When the user drops an item this get called, and you can use the description to
  37990. work out whether your object wants to deal with it or not.
  37991. Note that after this is called, the itemDragExit method may not be called, so you should
  37992. clean up in here if there's anything you need to do when the drag finishes.
  37993. @param dragSourceDetails contains information about the source of the drag operation.
  37994. */
  37995. virtual void itemDropped (const SourceDetails& dragSourceDetails) = 0;
  37996. /** Overriding this allows the target to tell the drag container whether to
  37997. draw the drag image while the cursor is over it.
  37998. By default it returns true, but if you return false, then the normal drag
  37999. image will not be shown when the cursor is over this target.
  38000. */
  38001. virtual bool shouldDrawDragImageWhenOver();
  38002. private:
  38003. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  38004. // The parameters for these methods have changed - please update your code!
  38005. virtual void isInterestedInDragSource (const String&, Component*) {}
  38006. virtual int itemDragEnter (const String&, Component*, int, int) { return 0; }
  38007. virtual int itemDragMove (const String&, Component*, int, int) { return 0; }
  38008. virtual int itemDragExit (const String&, Component*) { return 0; }
  38009. virtual int itemDropped (const String&, Component*, int, int) { return 0; }
  38010. #endif
  38011. };
  38012. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38013. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  38014. /**
  38015. Enables drag-and-drop behaviour for a component and all its sub-components.
  38016. For a component to be able to make or receive drag-and-drop events, one of its parent
  38017. components must derive from this class. It's probably best for the top-level
  38018. component to implement it.
  38019. Then to start a drag operation, any sub-component can just call the startDragging()
  38020. method, and this object will take over, tracking the mouse and sending appropriate
  38021. callbacks to any child components derived from DragAndDropTarget which the mouse
  38022. moves over.
  38023. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38024. the operating system onto your component, you don't need any of these classes: you can do this
  38025. simply by overriding Component::filesDropped().
  38026. @see DragAndDropTarget
  38027. */
  38028. class JUCE_API DragAndDropContainer
  38029. {
  38030. public:
  38031. /** Creates a DragAndDropContainer.
  38032. The object that derives from this class must also be a Component.
  38033. */
  38034. DragAndDropContainer();
  38035. /** Destructor. */
  38036. virtual ~DragAndDropContainer();
  38037. /** Begins a drag-and-drop operation.
  38038. This starts a drag-and-drop operation - call it when the user drags the
  38039. mouse in your drag-source component, and this object will track mouse
  38040. movements until the user lets go of the mouse button, and will send
  38041. appropriate messages to DragAndDropTarget objects that the mouse moves
  38042. over.
  38043. findParentDragContainerFor() is a handy method to call to find the
  38044. drag container to use for a component.
  38045. @param sourceDescription a string or value to use as the description of the thing being dragged -
  38046. this will be passed to the objects that might be dropped-onto so they can
  38047. decide whether they want to handle it
  38048. @param sourceComponent the component that is being dragged
  38049. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  38050. a snapshot of the sourceComponent will be used instead.
  38051. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  38052. window, and can be dragged to DragAndDropTargets that are the
  38053. children of components other than this one.
  38054. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  38055. at which the image should be drawn from the mouse. If it isn't
  38056. specified, then the image will be centred around the mouse. If
  38057. an image hasn't been passed-in, this will be ignored.
  38058. */
  38059. void startDragging (const var& sourceDescription,
  38060. Component* sourceComponent,
  38061. const Image& dragImage = Image::null,
  38062. bool allowDraggingToOtherJuceWindows = false,
  38063. const Point<int>* imageOffsetFromMouse = nullptr);
  38064. /** Returns true if something is currently being dragged. */
  38065. bool isDragAndDropActive() const;
  38066. /** Returns the description of the thing that's currently being dragged.
  38067. If nothing's being dragged, this will return an empty string, otherwise it's the
  38068. string that was passed into startDragging().
  38069. @see startDragging
  38070. */
  38071. const String getCurrentDragDescription() const;
  38072. /** Utility to find the DragAndDropContainer for a given Component.
  38073. This will search up this component's parent hierarchy looking for the first
  38074. parent component which is a DragAndDropContainer.
  38075. It's useful when a component wants to call startDragging but doesn't know
  38076. the DragAndDropContainer it should to use.
  38077. Obviously this may return 0 if it doesn't find a suitable component.
  38078. */
  38079. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38080. /** This performs a synchronous drag-and-drop of a set of files to some external
  38081. application.
  38082. You can call this function in response to a mouseDrag callback, and it will
  38083. block, running its own internal message loop and tracking the mouse, while it
  38084. uses a native operating system drag-and-drop operation to move or copy some
  38085. files to another application.
  38086. @param files a list of filenames to drag
  38087. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38088. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38089. @returns true if the files were successfully dropped somewhere, or false if it
  38090. was interrupted
  38091. @see performExternalDragDropOfText
  38092. */
  38093. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38094. /** This performs a synchronous drag-and-drop of a block of text to some external
  38095. application.
  38096. You can call this function in response to a mouseDrag callback, and it will
  38097. block, running its own internal message loop and tracking the mouse, while it
  38098. uses a native operating system drag-and-drop operation to move or copy some
  38099. text to another application.
  38100. @param text the text to copy
  38101. @returns true if the text was successfully dropped somewhere, or false if it
  38102. was interrupted
  38103. @see performExternalDragDropOfFiles
  38104. */
  38105. static bool performExternalDragDropOfText (const String& text);
  38106. protected:
  38107. /** Override this if you want to be able to perform an external drag a set of files
  38108. when the user drags outside of this container component.
  38109. This method will be called when a drag operation moves outside the Juce-based window,
  38110. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38111. to the array passed in, and return true.
  38112. @param sourceDetails information about the source of the drag operation
  38113. @param files on return, the filenames you want to drag
  38114. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38115. it must make a copy of them (see the performExternalDragDropOfFiles() method)
  38116. @see performExternalDragDropOfFiles
  38117. */
  38118. virtual bool shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails& sourceDetails,
  38119. StringArray& files, bool& canMoveFiles);
  38120. private:
  38121. friend class DragImageComponent;
  38122. ScopedPointer <Component> dragImageComponent;
  38123. String currentDragDesc;
  38124. JUCE_DEPRECATED (virtual bool shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)) { return false; }
  38125. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38126. };
  38127. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38128. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38129. class ToolbarItemComponent;
  38130. class ToolbarItemFactory;
  38131. /**
  38132. A toolbar component.
  38133. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38134. and looks after their order and layout.
  38135. Items (icon buttons or other custom components) are added to a toolbar using a
  38136. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38137. toolbar might contain more than one instance of a particular item type.
  38138. Toolbars can be interactively customised, allowing the user to drag the items
  38139. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38140. component as a source of new items.
  38141. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38142. */
  38143. class JUCE_API Toolbar : public Component,
  38144. public DragAndDropContainer,
  38145. public DragAndDropTarget,
  38146. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38147. {
  38148. public:
  38149. /** Creates an empty toolbar component.
  38150. To add some icons or other components to your toolbar, you'll need to
  38151. create a ToolbarItemFactory class that can create a suitable set of
  38152. ToolbarItemComponents.
  38153. @see ToolbarItemFactory, ToolbarItemComponents
  38154. */
  38155. Toolbar();
  38156. /** Destructor.
  38157. Any items on the bar will be deleted when the toolbar is deleted.
  38158. */
  38159. ~Toolbar();
  38160. /** Changes the bar's orientation.
  38161. @see isVertical
  38162. */
  38163. void setVertical (bool shouldBeVertical);
  38164. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38165. You can change the bar's orientation with setVertical().
  38166. */
  38167. bool isVertical() const noexcept { return vertical; }
  38168. /** Returns the depth of the bar.
  38169. If the bar is horizontal, this will return its height; if it's vertical, it
  38170. will return its width.
  38171. @see getLength
  38172. */
  38173. int getThickness() const noexcept;
  38174. /** Returns the length of the bar.
  38175. If the bar is horizontal, this will return its width; if it's vertical, it
  38176. will return its height.
  38177. @see getThickness
  38178. */
  38179. int getLength() const noexcept;
  38180. /** Deletes all items from the bar.
  38181. */
  38182. void clear();
  38183. /** Adds an item to the toolbar.
  38184. The factory's ToolbarItemFactory::createItem() will be called by this method
  38185. to create the component that will actually be added to the bar.
  38186. The new item will be inserted at the specified index (if the index is -1, it
  38187. will be added to the right-hand or bottom end of the bar).
  38188. Once added, the component will be automatically deleted by this object when it
  38189. is no longer needed.
  38190. @see ToolbarItemFactory
  38191. */
  38192. void addItem (ToolbarItemFactory& factory,
  38193. int itemId,
  38194. int insertIndex = -1);
  38195. /** Deletes one of the items from the bar.
  38196. */
  38197. void removeToolbarItem (int itemIndex);
  38198. /** Returns the number of items currently on the toolbar.
  38199. @see getItemId, getItemComponent
  38200. */
  38201. int getNumItems() const noexcept;
  38202. /** Returns the ID of the item with the given index.
  38203. If the index is less than zero or greater than the number of items,
  38204. this will return 0.
  38205. @see getNumItems
  38206. */
  38207. int getItemId (int itemIndex) const noexcept;
  38208. /** Returns the component being used for the item with the given index.
  38209. If the index is less than zero or greater than the number of items,
  38210. this will return 0.
  38211. @see getNumItems
  38212. */
  38213. ToolbarItemComponent* getItemComponent (int itemIndex) const noexcept;
  38214. /** Clears this toolbar and adds to it the default set of items that the specified
  38215. factory creates.
  38216. @see ToolbarItemFactory::getDefaultItemSet
  38217. */
  38218. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38219. /** Options for the way items should be displayed.
  38220. @see setStyle, getStyle
  38221. */
  38222. enum ToolbarItemStyle
  38223. {
  38224. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38225. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38226. textOnly /**< Means that the toolbar only display text labels for each item. */
  38227. };
  38228. /** Returns the toolbar's current style.
  38229. @see ToolbarItemStyle, setStyle
  38230. */
  38231. ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38232. /** Changes the toolbar's current style.
  38233. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38234. */
  38235. void setStyle (const ToolbarItemStyle& newStyle);
  38236. /** Flags used by the showCustomisationDialog() method. */
  38237. enum CustomisationFlags
  38238. {
  38239. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38240. show the "icons only" option on its choice of toolbar styles. */
  38241. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38242. show the "icons with text" option on its choice of toolbar styles. */
  38243. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38244. show the "text only" option on its choice of toolbar styles. */
  38245. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38246. show a button to reset the toolbar to its default set of items. */
  38247. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38248. };
  38249. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38250. The dialog contains a ToolbarItemPalette and various controls for editing other
  38251. aspects of the toolbar. This method will block and run the dialog box modally,
  38252. returning when the user closes it.
  38253. The factory is used to determine the set of items that will be shown on the
  38254. palette.
  38255. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38256. enum.
  38257. @see ToolbarItemPalette
  38258. */
  38259. void showCustomisationDialog (ToolbarItemFactory& factory,
  38260. int optionFlags = allCustomisationOptionsEnabled);
  38261. /** Turns on or off the toolbar's editing mode, in which its items can be
  38262. rearranged by the user.
  38263. (In most cases it's easier just to use showCustomisationDialog() instead of
  38264. trying to enable editing directly).
  38265. @see ToolbarItemPalette
  38266. */
  38267. void setEditingActive (bool editingEnabled);
  38268. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38269. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38270. methods.
  38271. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38272. */
  38273. enum ColourIds
  38274. {
  38275. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38276. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38277. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38278. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38279. over them. */
  38280. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38281. held down on them. */
  38282. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38283. when the style is set to iconsWithText or textOnly. */
  38284. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38285. the customisation dialog is active and the mouse moves over them. */
  38286. };
  38287. /** Returns a string that represents the toolbar's current set of items.
  38288. This lets you later restore the same item layout using restoreFromString().
  38289. @see restoreFromString
  38290. */
  38291. const String toString() const;
  38292. /** Restores a set of items that was previously stored in a string by the toString()
  38293. method.
  38294. The factory object is used to create any item components that are needed.
  38295. @see toString
  38296. */
  38297. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38298. const String& savedVersion);
  38299. /** @internal */
  38300. void paint (Graphics& g);
  38301. /** @internal */
  38302. void resized();
  38303. /** @internal */
  38304. void buttonClicked (Button*);
  38305. /** @internal */
  38306. void mouseDown (const MouseEvent&);
  38307. /** @internal */
  38308. bool isInterestedInDragSource (const SourceDetails&);
  38309. /** @internal */
  38310. void itemDragMove (const SourceDetails&);
  38311. /** @internal */
  38312. void itemDragExit (const SourceDetails&);
  38313. /** @internal */
  38314. void itemDropped (const SourceDetails&);
  38315. /** @internal */
  38316. void updateAllItemPositions (bool animate);
  38317. /** @internal */
  38318. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38319. private:
  38320. ScopedPointer<Button> missingItemsButton;
  38321. bool vertical, isEditingActive;
  38322. ToolbarItemStyle toolbarStyle;
  38323. class MissingItemsComponent;
  38324. friend class MissingItemsComponent;
  38325. OwnedArray <ToolbarItemComponent> items;
  38326. friend class ItemDragAndDropOverlayComponent;
  38327. static const char* const toolbarDragDescriptor;
  38328. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38329. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38331. };
  38332. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38333. /*** End of inlined file: juce_Toolbar.h ***/
  38334. class ItemDragAndDropOverlayComponent;
  38335. /**
  38336. A component that can be used as one of the items in a Toolbar.
  38337. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38338. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38339. class for further info about creating them.
  38340. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38341. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38342. calling the constructor, and override contentAreaChanged(), in which you can position
  38343. any sub-components you need to add.
  38344. To add basic buttons without writing a special subclass, have a look at the
  38345. ToolbarButton class.
  38346. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38347. */
  38348. class JUCE_API ToolbarItemComponent : public Button
  38349. {
  38350. public:
  38351. /** Constructor.
  38352. @param itemId the ID of the type of toolbar item which this represents
  38353. @param labelText the text to display if the toolbar's style is set to
  38354. Toolbar::iconsWithText or Toolbar::textOnly
  38355. @param isBeingUsedAsAButton set this to false if you don't want the button
  38356. to draw itself with button over/down states when the mouse
  38357. moves over it or clicks
  38358. */
  38359. ToolbarItemComponent (int itemId,
  38360. const String& labelText,
  38361. bool isBeingUsedAsAButton);
  38362. /** Destructor. */
  38363. ~ToolbarItemComponent();
  38364. /** Returns the item type ID that this component represents.
  38365. This value is in the constructor.
  38366. */
  38367. int getItemId() const noexcept { return itemId; }
  38368. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38369. inside one.
  38370. */
  38371. Toolbar* getToolbar() const;
  38372. /** Returns true if this component is currently inside a toolbar which is vertical.
  38373. @see Toolbar::isVertical
  38374. */
  38375. bool isToolbarVertical() const;
  38376. /** Returns the current style setting of this item.
  38377. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38378. @see setStyle, Toolbar::getStyle
  38379. */
  38380. Toolbar::ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38381. /** Changes the current style setting of this item.
  38382. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38383. by the toolbar that holds this item.
  38384. @see setStyle, Toolbar::setStyle
  38385. */
  38386. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38387. /** Returns the area of the component that should be used to display the button image or
  38388. other contents of the item.
  38389. This content area may change when the item's style changes, and may leave a space around the
  38390. edge of the component where the text label can be shown.
  38391. @see contentAreaChanged
  38392. */
  38393. const Rectangle<int> getContentArea() const noexcept { return contentArea; }
  38394. /** This method must return the size criteria for this item, based on a given toolbar
  38395. size and orientation.
  38396. The preferredSize, minSize and maxSize values must all be set by your implementation
  38397. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38398. toolbar, they refer to the item's height.
  38399. The preferredSize is the size that the component would like to be, and this must be
  38400. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38401. the same value.
  38402. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38403. Toolbar::getThickness().
  38404. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38405. vertically.
  38406. */
  38407. virtual bool getToolbarItemSizes (int toolbarThickness,
  38408. bool isToolbarVertical,
  38409. int& preferredSize,
  38410. int& minSize,
  38411. int& maxSize) = 0;
  38412. /** Your subclass should use this method to draw its content area.
  38413. The graphics object that is passed-in will have been clipped and had its origin
  38414. moved to fit the content area as specified get getContentArea(). The width and height
  38415. parameters are the width and height of the content area.
  38416. If the component you're writing isn't a button, you can just do nothing in this method.
  38417. */
  38418. virtual void paintButtonArea (Graphics& g,
  38419. int width, int height,
  38420. bool isMouseOver, bool isMouseDown) = 0;
  38421. /** Callback to indicate that the content area of this item has changed.
  38422. This might be because the component was resized, or because the style changed and
  38423. the space needed for the text label is different.
  38424. See getContentArea() for a description of what the area is.
  38425. */
  38426. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38427. /** Editing modes.
  38428. These are used by setEditingMode(), but will be rarely needed in user code.
  38429. */
  38430. enum ToolbarEditingMode
  38431. {
  38432. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38433. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38434. customisation mode, and the items can be dragged around. */
  38435. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38436. dragged onto a toolbar to add it to that bar.*/
  38437. };
  38438. /** Changes the editing mode of this component.
  38439. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38440. and is unlikely to be of much use in end-user-code.
  38441. */
  38442. void setEditingMode (const ToolbarEditingMode newMode);
  38443. /** Returns the current editing mode of this component.
  38444. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38445. and is unlikely to be of much use in end-user-code.
  38446. */
  38447. ToolbarEditingMode getEditingMode() const noexcept { return mode; }
  38448. /** @internal */
  38449. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38450. /** @internal */
  38451. void resized();
  38452. private:
  38453. friend class Toolbar;
  38454. friend class ItemDragAndDropOverlayComponent;
  38455. const int itemId;
  38456. ToolbarEditingMode mode;
  38457. Toolbar::ToolbarItemStyle toolbarStyle;
  38458. ScopedPointer <Component> overlayComp;
  38459. int dragOffsetX, dragOffsetY;
  38460. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38461. Rectangle<int> contentArea;
  38462. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38463. };
  38464. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38465. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38466. /**
  38467. A type of button designed to go on a toolbar.
  38468. This simple button can have two Drawable objects specified - one for normal
  38469. use and another one (optionally) for the button's "on" state if it's a
  38470. toggle button.
  38471. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38472. */
  38473. class JUCE_API ToolbarButton : public ToolbarItemComponent
  38474. {
  38475. public:
  38476. /** Creates a ToolbarButton.
  38477. @param itemId the ID for this toolbar item type. This is passed through to the
  38478. ToolbarItemComponent constructor
  38479. @param labelText the text to display on the button (if the toolbar is using a style
  38480. that shows text labels). This is passed through to the
  38481. ToolbarItemComponent constructor
  38482. @param normalImage a drawable object that the button should use as its icon. The object
  38483. that is passed-in here will be kept by this object and will be
  38484. deleted when no longer needed or when this button is deleted.
  38485. @param toggledOnImage a drawable object that the button can use as its icon if the button
  38486. is in a toggled-on state (see the Button::getToggleState() method). If
  38487. 0 is passed-in here, then the normal image will be used instead, regardless
  38488. of the toggle state. The object that is passed-in here will be kept by
  38489. this object and will be deleted when no longer needed or when this button
  38490. is deleted.
  38491. */
  38492. ToolbarButton (int itemId,
  38493. const String& labelText,
  38494. Drawable* normalImage,
  38495. Drawable* toggledOnImage);
  38496. /** Destructor. */
  38497. ~ToolbarButton();
  38498. /** @internal */
  38499. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  38500. int& minSize, int& maxSize);
  38501. /** @internal */
  38502. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  38503. /** @internal */
  38504. void contentAreaChanged (const Rectangle<int>& newBounds);
  38505. /** @internal */
  38506. void buttonStateChanged();
  38507. /** @internal */
  38508. void resized();
  38509. /** @internal */
  38510. void enablementChanged();
  38511. private:
  38512. ScopedPointer<Drawable> normalImage, toggledOnImage;
  38513. Drawable* currentImage;
  38514. void updateDrawable();
  38515. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  38516. };
  38517. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38518. /*** End of inlined file: juce_ToolbarButton.h ***/
  38519. #endif
  38520. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38521. /*** Start of inlined file: juce_CodeDocument.h ***/
  38522. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38523. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  38524. class CodeDocumentLine;
  38525. /**
  38526. A class for storing and manipulating a source code file.
  38527. When using a CodeEditorComponent, it takes one of these as its source object.
  38528. The CodeDocument stores its content as an array of lines, which makes it
  38529. quick to insert and delete.
  38530. @see CodeEditorComponent
  38531. */
  38532. class JUCE_API CodeDocument
  38533. {
  38534. public:
  38535. /** Creates a new, empty document.
  38536. */
  38537. CodeDocument();
  38538. /** Destructor. */
  38539. ~CodeDocument();
  38540. /** A position in a code document.
  38541. Using this class you can find a position in a code document and quickly get its
  38542. character position, line, and index. By calling setPositionMaintained (true), the
  38543. position is automatically updated when text is inserted or deleted in the document,
  38544. so that it maintains its original place in the text.
  38545. */
  38546. class JUCE_API Position
  38547. {
  38548. public:
  38549. /** Creates an uninitialised postion.
  38550. Don't attempt to call any methods on this until you've given it an owner document
  38551. to refer to!
  38552. */
  38553. Position() noexcept;
  38554. /** Creates a position based on a line and index in a document.
  38555. Note that this index is NOT the column number, it's the number of characters from the
  38556. start of the line. The "column" number isn't quite the same, because if the line
  38557. contains any tab characters, the relationship of the index to its visual column depends on
  38558. the number of spaces per tab being used!
  38559. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38560. they will be adjusted to keep them within its limits.
  38561. */
  38562. Position (const CodeDocument* ownerDocument,
  38563. int line, int indexInLine) noexcept;
  38564. /** Creates a position based on a character index in a document.
  38565. This position is placed at the specified number of characters from the start of the
  38566. document. The line and column are auto-calculated.
  38567. If the position is beyond the range of the document, it'll be adjusted to keep it
  38568. inside.
  38569. */
  38570. Position (const CodeDocument* ownerDocument,
  38571. int charactersFromStartOfDocument) noexcept;
  38572. /** Creates a copy of another position.
  38573. This will copy the position, but the new object will not be set to maintain its position,
  38574. even if the source object was set to do so.
  38575. */
  38576. Position (const Position& other) noexcept;
  38577. /** Destructor. */
  38578. ~Position();
  38579. Position& operator= (const Position& other);
  38580. bool operator== (const Position& other) const noexcept;
  38581. bool operator!= (const Position& other) const noexcept;
  38582. /** Points this object at a new position within the document.
  38583. If the position is beyond the range of the document, it'll be adjusted to keep it
  38584. inside.
  38585. @see getPosition, setLineAndIndex
  38586. */
  38587. void setPosition (int charactersFromStartOfDocument);
  38588. /** Returns the position as the number of characters from the start of the document.
  38589. @see setPosition, getLineNumber, getIndexInLine
  38590. */
  38591. int getPosition() const noexcept { return characterPos; }
  38592. /** Moves the position to a new line and index within the line.
  38593. Note that the index is NOT the column at which the position appears in an editor.
  38594. If the line contains any tab characters, the relationship of the index to its
  38595. visual position depends on the number of spaces per tab being used!
  38596. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38597. they will be adjusted to keep them within its limits.
  38598. */
  38599. void setLineAndIndex (int newLine, int newIndexInLine);
  38600. /** Returns the line number of this position.
  38601. The first line in the document is numbered zero, not one!
  38602. */
  38603. int getLineNumber() const noexcept { return line; }
  38604. /** Returns the number of characters from the start of the line.
  38605. Note that this value is NOT the column at which the position appears in an editor.
  38606. If the line contains any tab characters, the relationship of the index to its
  38607. visual position depends on the number of spaces per tab being used!
  38608. */
  38609. int getIndexInLine() const noexcept { return indexInLine; }
  38610. /** Allows the position to be automatically updated when the document changes.
  38611. If this is set to true, the positon will register with its document so that
  38612. when the document has text inserted or deleted, this position will be automatically
  38613. moved to keep it at the same position in the text.
  38614. */
  38615. void setPositionMaintained (bool isMaintained);
  38616. /** Moves the position forwards or backwards by the specified number of characters.
  38617. @see movedBy
  38618. */
  38619. void moveBy (int characterDelta);
  38620. /** Returns a position which is the same as this one, moved by the specified number of
  38621. characters.
  38622. @see moveBy
  38623. */
  38624. const Position movedBy (int characterDelta) const;
  38625. /** Returns a position which is the same as this one, moved up or down by the specified
  38626. number of lines.
  38627. @see movedBy
  38628. */
  38629. const Position movedByLines (int deltaLines) const;
  38630. /** Returns the character in the document at this position.
  38631. @see getLineText
  38632. */
  38633. const juce_wchar getCharacter() const;
  38634. /** Returns the line from the document that this position is within.
  38635. @see getCharacter, getLineNumber
  38636. */
  38637. const String getLineText() const;
  38638. private:
  38639. CodeDocument* owner;
  38640. int characterPos, line, indexInLine;
  38641. bool positionMaintained;
  38642. };
  38643. /** Returns the full text of the document. */
  38644. const String getAllContent() const;
  38645. /** Returns a section of the document's text. */
  38646. const String getTextBetween (const Position& start, const Position& end) const;
  38647. /** Returns a line from the document. */
  38648. const String getLine (int lineIndex) const noexcept;
  38649. /** Returns the number of characters in the document. */
  38650. int getNumCharacters() const noexcept;
  38651. /** Returns the number of lines in the document. */
  38652. int getNumLines() const noexcept { return lines.size(); }
  38653. /** Returns the number of characters in the longest line of the document. */
  38654. int getMaximumLineLength() noexcept;
  38655. /** Deletes a section of the text.
  38656. This operation is undoable.
  38657. */
  38658. void deleteSection (const Position& startPosition, const Position& endPosition);
  38659. /** Inserts some text into the document at a given position.
  38660. This operation is undoable.
  38661. */
  38662. void insertText (const Position& position, const String& text);
  38663. /** Clears the document and replaces it with some new text.
  38664. This operation is undoable - if you're trying to completely reset the document, you
  38665. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  38666. */
  38667. void replaceAllContent (const String& newContent);
  38668. /** Replaces the editor's contents with the contents of a stream.
  38669. This will also reset the undo history and save point marker.
  38670. */
  38671. bool loadFromStream (InputStream& stream);
  38672. /** Writes the editor's current contents to a stream. */
  38673. bool writeToStream (OutputStream& stream);
  38674. /** Returns the preferred new-line characters for the document.
  38675. This will be either "\n", "\r\n", or (rarely) "\r".
  38676. @see setNewLineCharacters
  38677. */
  38678. const String getNewLineCharacters() const noexcept { return newLineChars; }
  38679. /** Sets the new-line characters that the document should use.
  38680. The string must be either "\n", "\r\n", or (rarely) "\r".
  38681. @see getNewLineCharacters
  38682. */
  38683. void setNewLineCharacters (const String& newLine) noexcept;
  38684. /** Begins a new undo transaction.
  38685. The document itself will not call this internally, so relies on whatever is using the
  38686. document to periodically call this to break up the undo sequence into sensible chunks.
  38687. @see UndoManager::beginNewTransaction
  38688. */
  38689. void newTransaction();
  38690. /** Undo the last operation.
  38691. @see UndoManager::undo
  38692. */
  38693. void undo();
  38694. /** Redo the last operation.
  38695. @see UndoManager::redo
  38696. */
  38697. void redo();
  38698. /** Clears the undo history.
  38699. @see UndoManager::clearUndoHistory
  38700. */
  38701. void clearUndoHistory();
  38702. /** Returns the document's UndoManager */
  38703. UndoManager& getUndoManager() noexcept { return undoManager; }
  38704. /** Makes a note that the document's current state matches the one that is saved.
  38705. After this has been called, hasChangedSinceSavePoint() will return false until
  38706. the document has been altered, and then it'll start returning true. If the document is
  38707. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  38708. will again return false.
  38709. @see hasChangedSinceSavePoint
  38710. */
  38711. void setSavePoint() noexcept;
  38712. /** Returns true if the state of the document differs from the state it was in when
  38713. setSavePoint() was last called.
  38714. @see setSavePoint
  38715. */
  38716. bool hasChangedSinceSavePoint() const noexcept;
  38717. /** Searches for a word-break. */
  38718. const Position findWordBreakAfter (const Position& position) const noexcept;
  38719. /** Searches for a word-break. */
  38720. const Position findWordBreakBefore (const Position& position) const noexcept;
  38721. /** An object that receives callbacks from the CodeDocument when its text changes.
  38722. @see CodeDocument::addListener, CodeDocument::removeListener
  38723. */
  38724. class JUCE_API Listener
  38725. {
  38726. public:
  38727. Listener() {}
  38728. virtual ~Listener() {}
  38729. /** Called by a CodeDocument when it is altered.
  38730. */
  38731. virtual void codeDocumentChanged (const Position& affectedTextStart,
  38732. const Position& affectedTextEnd) = 0;
  38733. };
  38734. /** Registers a listener object to receive callbacks when the document changes.
  38735. If the listener is already registered, this method has no effect.
  38736. @see removeListener
  38737. */
  38738. void addListener (Listener* listener) noexcept;
  38739. /** Deregisters a listener.
  38740. @see addListener
  38741. */
  38742. void removeListener (Listener* listener) noexcept;
  38743. /** Iterates the text in a CodeDocument.
  38744. This class lets you read characters from a CodeDocument. It's designed to be used
  38745. by a SyntaxAnalyser object.
  38746. @see CodeDocument, SyntaxAnalyser
  38747. */
  38748. class JUCE_API Iterator
  38749. {
  38750. public:
  38751. Iterator (CodeDocument* document);
  38752. Iterator (const Iterator& other);
  38753. Iterator& operator= (const Iterator& other) noexcept;
  38754. ~Iterator() noexcept;
  38755. /** Reads the next character and returns it.
  38756. @see peekNextChar
  38757. */
  38758. juce_wchar nextChar();
  38759. /** Reads the next character without advancing the current position. */
  38760. juce_wchar peekNextChar() const;
  38761. /** Advances the position by one character. */
  38762. void skip();
  38763. /** Returns the position of the next character as its position within the
  38764. whole document.
  38765. */
  38766. int getPosition() const noexcept { return position; }
  38767. /** Skips over any whitespace characters until the next character is non-whitespace. */
  38768. void skipWhitespace();
  38769. /** Skips forward until the next character will be the first character on the next line */
  38770. void skipToEndOfLine();
  38771. /** Returns the line number of the next character. */
  38772. int getLine() const noexcept { return line; }
  38773. /** Returns true if the iterator has reached the end of the document. */
  38774. bool isEOF() const noexcept;
  38775. private:
  38776. CodeDocument* document;
  38777. mutable String::CharPointerType charPointer;
  38778. int line, position;
  38779. };
  38780. private:
  38781. friend class CodeDocumentInsertAction;
  38782. friend class CodeDocumentDeleteAction;
  38783. friend class Iterator;
  38784. friend class Position;
  38785. OwnedArray <CodeDocumentLine> lines;
  38786. Array <Position*> positionsToMaintain;
  38787. UndoManager undoManager;
  38788. int currentActionIndex, indexOfSavedState;
  38789. int maximumLineLength;
  38790. ListenerList <Listener> listeners;
  38791. String newLineChars;
  38792. void sendListenerChangeMessage (int startLine, int endLine);
  38793. void insert (const String& text, int insertPos, bool undoable);
  38794. void remove (int startPos, int endPos, bool undoable);
  38795. void checkLastLineStatus();
  38796. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  38797. };
  38798. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  38799. /*** End of inlined file: juce_CodeDocument.h ***/
  38800. #endif
  38801. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38802. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  38803. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38804. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38805. /*** Start of inlined file: juce_TextInputTarget.h ***/
  38806. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38807. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38808. /**
  38809. An abstract base class which can be implemented by components that function as
  38810. text editors.
  38811. This class allows different types of text editor component to provide a uniform
  38812. interface, which can be used by things like OS-specific input methods, on-screen
  38813. keyboards, etc.
  38814. */
  38815. class JUCE_API TextInputTarget
  38816. {
  38817. public:
  38818. /** */
  38819. TextInputTarget() {}
  38820. /** Destructor. */
  38821. virtual ~TextInputTarget() {}
  38822. /** Returns true if this input target is currently accepting input.
  38823. For example, a text editor might return false if it's in read-only mode.
  38824. */
  38825. virtual bool isTextInputActive() const = 0;
  38826. /** Returns the extents of the selected text region, or an empty range if
  38827. nothing is selected,
  38828. */
  38829. virtual const Range<int> getHighlightedRegion() const = 0;
  38830. /** Sets the currently-selected text region. */
  38831. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  38832. /** Sets a number of temporarily underlined sections.
  38833. This is needed by MS Windows input method UI.
  38834. */
  38835. virtual void setTemporaryUnderlining (const Array <Range<int> >& underlinedRegions) = 0;
  38836. /** Returns a specified sub-section of the text. */
  38837. virtual const String getTextInRange (const Range<int>& range) const = 0;
  38838. /** Inserts some text, overwriting the selected text region, if there is one. */
  38839. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  38840. /** Returns the position of the caret, relative to the component's origin. */
  38841. virtual const Rectangle<int> getCaretRectangle() = 0;
  38842. };
  38843. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38844. /*** End of inlined file: juce_TextInputTarget.h ***/
  38845. /*** Start of inlined file: juce_CaretComponent.h ***/
  38846. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  38847. #define __JUCE_CARETCOMPONENT_JUCEHEADER__
  38848. /**
  38849. */
  38850. class JUCE_API CaretComponent : public Component,
  38851. public Timer
  38852. {
  38853. public:
  38854. /** Creates the caret component.
  38855. The keyFocusOwner is an optional component which the caret will check, making
  38856. itself visible only when the keyFocusOwner has keyboard focus.
  38857. */
  38858. CaretComponent (Component* keyFocusOwner);
  38859. /** Destructor. */
  38860. ~CaretComponent();
  38861. /** Sets the caret's position to place it next to the given character.
  38862. The area is the rectangle containing the entire character that the caret is
  38863. positioned on, so by default a vertical-line caret may choose to just show itself
  38864. at the left of this area. You can override this method to customise its size.
  38865. This method will also force the caret to reset its timer and become visible (if
  38866. appropriate), so that as it moves, you can see where it is.
  38867. */
  38868. virtual void setCaretPosition (const Rectangle<int>& characterArea);
  38869. /** A set of colour IDs to use to change the colour of various aspects of the caret.
  38870. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38871. methods.
  38872. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38873. */
  38874. enum ColourIds
  38875. {
  38876. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  38877. };
  38878. /** @internal */
  38879. void paint (Graphics& g);
  38880. /** @internal */
  38881. void timerCallback();
  38882. private:
  38883. Component* owner;
  38884. bool shouldBeShown() const;
  38885. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  38886. };
  38887. #endif // __JUCE_CARETCOMPONENT_JUCEHEADER__
  38888. /*** End of inlined file: juce_CaretComponent.h ***/
  38889. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  38890. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38891. #define __JUCE_CODETOKENISER_JUCEHEADER__
  38892. /**
  38893. A base class for tokenising code so that the syntax can be displayed in a
  38894. code editor.
  38895. @see CodeDocument, CodeEditorComponent
  38896. */
  38897. class JUCE_API CodeTokeniser
  38898. {
  38899. public:
  38900. CodeTokeniser() {}
  38901. virtual ~CodeTokeniser() {}
  38902. /** Reads the next token from the source and returns its token type.
  38903. This must leave the source pointing to the first character in the
  38904. next token.
  38905. */
  38906. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  38907. /** Returns a list of the names of the token types this analyser uses.
  38908. The index in this list must match the token type numbers that are
  38909. returned by readNextToken().
  38910. */
  38911. virtual const StringArray getTokenTypes() = 0;
  38912. /** Returns a suggested syntax highlighting colour for a specified
  38913. token type.
  38914. */
  38915. virtual const Colour getDefaultColour (int tokenType) = 0;
  38916. private:
  38917. JUCE_LEAK_DETECTOR (CodeTokeniser);
  38918. };
  38919. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  38920. /*** End of inlined file: juce_CodeTokeniser.h ***/
  38921. /**
  38922. A text editor component designed specifically for source code.
  38923. This is designed to handle syntax highlighting and fast editing of very large
  38924. files.
  38925. */
  38926. class JUCE_API CodeEditorComponent : public Component,
  38927. public TextInputTarget,
  38928. public Timer,
  38929. public ScrollBar::Listener,
  38930. public CodeDocument::Listener,
  38931. public AsyncUpdater
  38932. {
  38933. public:
  38934. /** Creates an editor for a document.
  38935. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  38936. The object that you pass in is not owned or deleted by the editor - you must
  38937. make sure that it doesn't get deleted while this component is still using it.
  38938. @see CodeDocument
  38939. */
  38940. CodeEditorComponent (CodeDocument& document,
  38941. CodeTokeniser* codeTokeniser);
  38942. /** Destructor. */
  38943. ~CodeEditorComponent();
  38944. /** Returns the code document that this component is editing. */
  38945. CodeDocument& getDocument() const noexcept { return document; }
  38946. /** Loads the given content into the document.
  38947. This will completely reset the CodeDocument object, clear its undo history,
  38948. and fill it with this text.
  38949. */
  38950. void loadContent (const String& newContent);
  38951. /** Returns the standard character width. */
  38952. float getCharWidth() const noexcept { return charWidth; }
  38953. /** Returns the height of a line of text, in pixels. */
  38954. int getLineHeight() const noexcept { return lineHeight; }
  38955. /** Returns the number of whole lines visible on the screen,
  38956. This doesn't include a cut-off line that might be visible at the bottom if the
  38957. component's height isn't an exact multiple of the line-height.
  38958. */
  38959. int getNumLinesOnScreen() const noexcept { return linesOnScreen; }
  38960. /** Returns the number of whole columns visible on the screen.
  38961. This doesn't include any cut-off columns at the right-hand edge.
  38962. */
  38963. int getNumColumnsOnScreen() const noexcept { return columnsOnScreen; }
  38964. /** Returns the current caret position. */
  38965. const CodeDocument::Position getCaretPos() const { return caretPos; }
  38966. /** Returns the position of the caret, relative to the editor's origin. */
  38967. const Rectangle<int> getCaretRectangle();
  38968. /** Moves the caret.
  38969. If selecting is true, the section of the document between the current
  38970. caret position and the new one will become selected. If false, any currently
  38971. selected region will be deselected.
  38972. */
  38973. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  38974. /** Returns the on-screen position of a character in the document.
  38975. The rectangle returned is relative to this component's top-left origin.
  38976. */
  38977. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  38978. /** Finds the character at a given on-screen position.
  38979. The co-ordinates are relative to this component's top-left origin.
  38980. */
  38981. const CodeDocument::Position getPositionAt (int x, int y);
  38982. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  38983. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  38984. bool moveCaretUp (bool selecting);
  38985. bool moveCaretDown (bool selecting);
  38986. bool scrollDown();
  38987. bool scrollUp();
  38988. bool pageUp (bool selecting);
  38989. bool pageDown (bool selecting);
  38990. bool moveCaretToTop (bool selecting);
  38991. bool moveCaretToStartOfLine (bool selecting);
  38992. bool moveCaretToEnd (bool selecting);
  38993. bool moveCaretToEndOfLine (bool selecting);
  38994. bool deleteBackwards (bool moveInWholeWordSteps);
  38995. bool deleteForwards (bool moveInWholeWordSteps);
  38996. bool copyToClipboard();
  38997. bool cutToClipboard();
  38998. bool pasteFromClipboard();
  38999. bool undo();
  39000. bool redo();
  39001. bool selectAll();
  39002. void deselectAll();
  39003. void scrollToLine (int newFirstLineOnScreen);
  39004. void scrollBy (int deltaLines);
  39005. void scrollToColumn (int newFirstColumnOnScreen);
  39006. void scrollToKeepCaretOnScreen();
  39007. void insertTextAtCaret (const String& textToInsert);
  39008. void insertTabAtCaret();
  39009. const Range<int> getHighlightedRegion() const;
  39010. void setHighlightedRegion (const Range<int>& newRange);
  39011. const String getTextInRange (const Range<int>& range) const;
  39012. /** Changes the current tab settings.
  39013. This lets you change the tab size and whether pressing the tab key inserts a
  39014. tab character, or its equivalent number of spaces.
  39015. */
  39016. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  39017. /** Returns the current number of spaces per tab.
  39018. @see setTabSize
  39019. */
  39020. int getTabSize() const noexcept { return spacesPerTab; }
  39021. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  39022. @see setTabSize
  39023. */
  39024. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  39025. /** Changes the font.
  39026. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  39027. */
  39028. void setFont (const Font& newFont);
  39029. /** Returns the font that the editor is using. */
  39030. const Font& getFont() const noexcept { return font; }
  39031. /** Resets the syntax highlighting colours to the default ones provided by the
  39032. code tokeniser.
  39033. @see CodeTokeniser::getDefaultColour
  39034. */
  39035. void resetToDefaultColours();
  39036. /** Changes one of the syntax highlighting colours.
  39037. The token type values are dependent on the tokeniser being used - use
  39038. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39039. @see getColourForTokenType
  39040. */
  39041. void setColourForTokenType (int tokenType, const Colour& colour);
  39042. /** Returns one of the syntax highlighting colours.
  39043. The token type values are dependent on the tokeniser being used - use
  39044. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39045. @see setColourForTokenType
  39046. */
  39047. const Colour getColourForTokenType (int tokenType) const;
  39048. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39049. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39050. methods.
  39051. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39052. */
  39053. enum ColourIds
  39054. {
  39055. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  39056. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  39057. selected text. */
  39058. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  39059. enabled. */
  39060. };
  39061. /** Changes the size of the scrollbars. */
  39062. void setScrollbarThickness (int thickness);
  39063. /** Returns the thickness of the scrollbars. */
  39064. int getScrollbarThickness() const noexcept { return scrollbarThickness; }
  39065. /** @internal */
  39066. void resized();
  39067. /** @internal */
  39068. void paint (Graphics& g);
  39069. /** @internal */
  39070. bool keyPressed (const KeyPress& key);
  39071. /** @internal */
  39072. void mouseDown (const MouseEvent& e);
  39073. /** @internal */
  39074. void mouseDrag (const MouseEvent& e);
  39075. /** @internal */
  39076. void mouseUp (const MouseEvent& e);
  39077. /** @internal */
  39078. void mouseDoubleClick (const MouseEvent& e);
  39079. /** @internal */
  39080. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39081. /** @internal */
  39082. void focusGained (FocusChangeType cause);
  39083. /** @internal */
  39084. void focusLost (FocusChangeType cause);
  39085. /** @internal */
  39086. void timerCallback();
  39087. /** @internal */
  39088. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  39089. /** @internal */
  39090. void handleAsyncUpdate();
  39091. /** @internal */
  39092. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  39093. const CodeDocument::Position& affectedTextEnd);
  39094. /** @internal */
  39095. bool isTextInputActive() const;
  39096. /** @internal */
  39097. void setTemporaryUnderlining (const Array <Range<int> >&);
  39098. private:
  39099. CodeDocument& document;
  39100. Font font;
  39101. int firstLineOnScreen, gutter, spacesPerTab;
  39102. float charWidth;
  39103. int lineHeight, linesOnScreen, columnsOnScreen;
  39104. int scrollbarThickness, columnToTryToMaintain;
  39105. bool useSpacesForTabs;
  39106. double xOffset;
  39107. CodeDocument::Position caretPos;
  39108. CodeDocument::Position selectionStart, selectionEnd;
  39109. ScopedPointer<CaretComponent> caret;
  39110. ScrollBar verticalScrollBar, horizontalScrollBar;
  39111. enum DragType
  39112. {
  39113. notDragging,
  39114. draggingSelectionStart,
  39115. draggingSelectionEnd
  39116. };
  39117. DragType dragType;
  39118. CodeTokeniser* codeTokeniser;
  39119. Array <Colour> coloursForTokenCategories;
  39120. class CodeEditorLine;
  39121. OwnedArray <CodeEditorLine> lines;
  39122. void rebuildLineTokens();
  39123. OwnedArray <CodeDocument::Iterator> cachedIterators;
  39124. void clearCachedIterators (int firstLineToBeInvalid);
  39125. void updateCachedIterators (int maxLineNum);
  39126. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  39127. void moveLineDelta (int delta, bool selecting);
  39128. void updateCaretPosition();
  39129. void updateScrollBars();
  39130. void scrollToLineInternal (int line);
  39131. void scrollToColumnInternal (double column);
  39132. void newTransaction();
  39133. void cut();
  39134. int indexToColumn (int line, int index) const noexcept;
  39135. int columnToIndex (int line, int column) const noexcept;
  39136. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  39137. };
  39138. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39139. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  39140. #endif
  39141. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39142. #endif
  39143. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39144. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39145. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39146. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39147. /**
  39148. A simple lexical analyser for syntax colouring of C++ code.
  39149. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  39150. */
  39151. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  39152. {
  39153. public:
  39154. CPlusPlusCodeTokeniser();
  39155. ~CPlusPlusCodeTokeniser();
  39156. enum TokenType
  39157. {
  39158. tokenType_error = 0,
  39159. tokenType_comment,
  39160. tokenType_builtInKeyword,
  39161. tokenType_identifier,
  39162. tokenType_integerLiteral,
  39163. tokenType_floatLiteral,
  39164. tokenType_stringLiteral,
  39165. tokenType_operator,
  39166. tokenType_bracket,
  39167. tokenType_punctuation,
  39168. tokenType_preprocessor
  39169. };
  39170. int readNextToken (CodeDocument::Iterator& source);
  39171. const StringArray getTokenTypes();
  39172. const Colour getDefaultColour (int tokenType);
  39173. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39174. static bool isReservedKeyword (const String& token) noexcept;
  39175. private:
  39176. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39177. };
  39178. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39179. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39180. #endif
  39181. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39182. /*** Start of inlined file: juce_ComboBox.h ***/
  39183. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39184. #define __JUCE_COMBOBOX_JUCEHEADER__
  39185. /*** Start of inlined file: juce_Label.h ***/
  39186. #ifndef __JUCE_LABEL_JUCEHEADER__
  39187. #define __JUCE_LABEL_JUCEHEADER__
  39188. /*** Start of inlined file: juce_TextEditor.h ***/
  39189. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  39190. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  39191. /**
  39192. A component containing text that can be edited.
  39193. A TextEditor can either be in single- or multi-line mode, and supports mixed
  39194. fonts and colours.
  39195. @see TextEditor::Listener, Label
  39196. */
  39197. class JUCE_API TextEditor : public Component,
  39198. public TextInputTarget,
  39199. public SettableTooltipClient
  39200. {
  39201. public:
  39202. /** Creates a new, empty text editor.
  39203. @param componentName the name to pass to the component for it to use as its name
  39204. @param passwordCharacter if this is not zero, this character will be used as a replacement
  39205. for all characters that are drawn on screen - e.g. to create
  39206. a password-style textbox containing circular blobs instead of text,
  39207. you could set this value to 0x25cf, which is the unicode character
  39208. for a black splodge (not all fonts include this, though), or 0x2022,
  39209. which is a bullet (probably the best choice for linux).
  39210. */
  39211. explicit TextEditor (const String& componentName = String::empty,
  39212. juce_wchar passwordCharacter = 0);
  39213. /** Destructor. */
  39214. virtual ~TextEditor();
  39215. /** Puts the editor into either multi- or single-line mode.
  39216. By default, the editor will be in single-line mode, so use this if you need a multi-line
  39217. editor.
  39218. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  39219. on if you want a multi-line editor with line-breaks.
  39220. @see isMultiLine, setReturnKeyStartsNewLine
  39221. */
  39222. void setMultiLine (bool shouldBeMultiLine,
  39223. bool shouldWordWrap = true);
  39224. /** Returns true if the editor is in multi-line mode.
  39225. */
  39226. bool isMultiLine() const;
  39227. /** Changes the behaviour of the return key.
  39228. If set to true, the return key will insert a new-line into the text; if false
  39229. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  39230. method. By default this is set to false, and when true it will only insert
  39231. new-lines when in multi-line mode (see setMultiLine()).
  39232. */
  39233. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  39234. /** Returns the value set by setReturnKeyStartsNewLine().
  39235. See setReturnKeyStartsNewLine() for more info.
  39236. */
  39237. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  39238. /** Indicates whether the tab key should be accepted and used to input a tab character,
  39239. or whether it gets ignored.
  39240. By default the tab key is ignored, so that it can be used to switch keyboard focus
  39241. between components.
  39242. */
  39243. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  39244. /** Returns true if the tab key is being used for input.
  39245. @see setTabKeyUsedAsCharacter
  39246. */
  39247. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  39248. /** Changes the editor to read-only mode.
  39249. By default, the text editor is not read-only. If you're making it read-only, you
  39250. might also want to call setCaretVisible (false) to get rid of the caret.
  39251. The text can still be highlighted and copied when in read-only mode.
  39252. @see isReadOnly, setCaretVisible
  39253. */
  39254. void setReadOnly (bool shouldBeReadOnly);
  39255. /** Returns true if the editor is in read-only mode.
  39256. */
  39257. bool isReadOnly() const;
  39258. /** Makes the caret visible or invisible.
  39259. By default the caret is visible.
  39260. @see setCaretColour, setCaretPosition
  39261. */
  39262. void setCaretVisible (bool shouldBeVisible);
  39263. /** Returns true if the caret is enabled.
  39264. @see setCaretVisible
  39265. */
  39266. bool isCaretVisible() const { return caret != nullptr; }
  39267. /** Enables/disables a vertical scrollbar.
  39268. (This only applies when in multi-line mode). When the text gets too long to fit
  39269. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  39270. this is enabled, the scrollbar will be hidden unless it's needed.
  39271. By default the scrollbar is enabled.
  39272. */
  39273. void setScrollbarsShown (bool shouldBeEnabled);
  39274. /** Returns true if scrollbars are enabled.
  39275. @see setScrollbarsShown
  39276. */
  39277. bool areScrollbarsShown() const { return scrollbarVisible; }
  39278. /** Changes the password character used to disguise the text.
  39279. @param passwordCharacter if this is not zero, this character will be used as a replacement
  39280. for all characters that are drawn on screen - e.g. to create
  39281. a password-style textbox containing circular blobs instead of text,
  39282. you could set this value to 0x25cf, which is the unicode character
  39283. for a black splodge (not all fonts include this, though), or 0x2022,
  39284. which is a bullet (probably the best choice for linux).
  39285. */
  39286. void setPasswordCharacter (juce_wchar passwordCharacter);
  39287. /** Returns the current password character.
  39288. @see setPasswordCharacter
  39289. */
  39290. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  39291. /** Allows a right-click menu to appear for the editor.
  39292. (This defaults to being enabled).
  39293. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  39294. of options such as cut/copy/paste, undo/redo, etc.
  39295. */
  39296. void setPopupMenuEnabled (bool menuEnabled);
  39297. /** Returns true if the right-click menu is enabled.
  39298. @see setPopupMenuEnabled
  39299. */
  39300. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  39301. /** Returns true if a popup-menu is currently being displayed.
  39302. */
  39303. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  39304. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39305. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39306. methods.
  39307. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39308. */
  39309. enum ColourIds
  39310. {
  39311. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  39312. transparent if necessary. */
  39313. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  39314. that because the editor can contain multiple colours, calling this
  39315. method won't change the colour of existing text - to do that, call
  39316. applyFontToAllText() after calling this method.*/
  39317. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  39318. the text - this can be transparent if you don't want to show any
  39319. highlighting.*/
  39320. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  39321. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  39322. the edge of the component. */
  39323. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  39324. the edge of the component when it has focus. */
  39325. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  39326. around the edge of the editor. */
  39327. };
  39328. /** Sets the font to use for newly added text.
  39329. This will change the font that will be used next time any text is added or entered
  39330. into the editor. It won't change the font of any existing text - to do that, use
  39331. applyFontToAllText() instead.
  39332. @see applyFontToAllText
  39333. */
  39334. void setFont (const Font& newFont);
  39335. /** Applies a font to all the text in the editor.
  39336. This will also set the current font to use for any new text that's added.
  39337. @see setFont
  39338. */
  39339. void applyFontToAllText (const Font& newFont);
  39340. /** Returns the font that's currently being used for new text.
  39341. @see setFont
  39342. */
  39343. const Font& getFont() const;
  39344. /** If set to true, focusing on the editor will highlight all its text.
  39345. (Set to false by default).
  39346. This is useful for boxes where you expect the user to re-enter all the
  39347. text when they focus on the component, rather than editing what's already there.
  39348. */
  39349. void setSelectAllWhenFocused (bool b);
  39350. /** Sets limits on the characters that can be entered.
  39351. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  39352. limit is set
  39353. @param allowedCharacters if this is non-empty, then only characters that occur in
  39354. this string are allowed to be entered into the editor.
  39355. */
  39356. void setInputRestrictions (int maxTextLength,
  39357. const String& allowedCharacters = String::empty);
  39358. /** When the text editor is empty, it can be set to display a message.
  39359. This is handy for things like telling the user what to type in the box - the
  39360. string is only displayed, it's not taken to actually be the contents of
  39361. the editor.
  39362. */
  39363. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  39364. /** Changes the size of the scrollbars that are used.
  39365. Handy if you need smaller scrollbars for a small text box.
  39366. */
  39367. void setScrollBarThickness (int newThicknessPixels);
  39368. /** Shows or hides the buttons on any scrollbars that are used.
  39369. @see ScrollBar::setButtonVisibility
  39370. */
  39371. void setScrollBarButtonVisibility (bool buttonsVisible);
  39372. /**
  39373. Receives callbacks from a TextEditor component when it changes.
  39374. @see TextEditor::addListener
  39375. */
  39376. class JUCE_API Listener
  39377. {
  39378. public:
  39379. /** Destructor. */
  39380. virtual ~Listener() {}
  39381. /** Called when the user changes the text in some way. */
  39382. virtual void textEditorTextChanged (TextEditor& editor);
  39383. /** Called when the user presses the return key. */
  39384. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  39385. /** Called when the user presses the escape key. */
  39386. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  39387. /** Called when the text editor loses focus. */
  39388. virtual void textEditorFocusLost (TextEditor& editor);
  39389. };
  39390. /** Registers a listener to be told when things happen to the text.
  39391. @see removeListener
  39392. */
  39393. void addListener (Listener* newListener);
  39394. /** Deregisters a listener.
  39395. @see addListener
  39396. */
  39397. void removeListener (Listener* listenerToRemove);
  39398. /** Returns the entire contents of the editor. */
  39399. String getText() const;
  39400. /** Returns a section of the contents of the editor. */
  39401. const String getTextInRange (const Range<int>& textRange) const;
  39402. /** Returns true if there are no characters in the editor.
  39403. This is more efficient than calling getText().isEmpty().
  39404. */
  39405. bool isEmpty() const;
  39406. /** Sets the entire content of the editor.
  39407. This will clear the editor and insert the given text (using the current text colour
  39408. and font). You can set the current text colour using
  39409. @code setColour (TextEditor::textColourId, ...);
  39410. @endcode
  39411. @param newText the text to add
  39412. @param sendTextChangeMessage if true, this will cause a change message to
  39413. be sent to all the listeners.
  39414. @see insertText
  39415. */
  39416. void setText (const String& newText,
  39417. bool sendTextChangeMessage = true);
  39418. /** Returns a Value object that can be used to get or set the text.
  39419. Bear in mind that this operate quite slowly if your text box contains large
  39420. amounts of text, as it needs to dynamically build the string that's involved. It's
  39421. best used for small text boxes.
  39422. */
  39423. Value& getTextValue();
  39424. /** Inserts some text at the current caret position.
  39425. If a section of the text is highlighted, it will be replaced by
  39426. this string, otherwise it will be inserted.
  39427. To delete a section of text, you can use setHighlightedRegion() to
  39428. highlight it, and call insertTextAtCursor (String::empty).
  39429. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  39430. */
  39431. void insertTextAtCaret (const String& textToInsert);
  39432. /** Deletes all the text from the editor. */
  39433. void clear();
  39434. /** Deletes the currently selected region.
  39435. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  39436. @see copy, paste, SystemClipboard
  39437. */
  39438. void cut();
  39439. /** Copies the currently selected region to the clipboard.
  39440. @see cut, paste, SystemClipboard
  39441. */
  39442. void copy();
  39443. /** Pastes the contents of the clipboard into the editor at the caret position.
  39444. @see cut, copy, SystemClipboard
  39445. */
  39446. void paste();
  39447. /** Moves the caret to be in front of a given character.
  39448. @see getCaretPosition
  39449. */
  39450. void setCaretPosition (int newIndex);
  39451. /** Returns the current index of the caret.
  39452. @see setCaretPosition
  39453. */
  39454. int getCaretPosition() const;
  39455. /** Attempts to scroll the text editor so that the caret ends up at
  39456. a specified position.
  39457. This won't affect the caret's position within the text, it tries to scroll
  39458. the entire editor vertically and horizontally so that the caret is sitting
  39459. at the given position (relative to the top-left of this component).
  39460. Depending on the amount of text available, it might not be possible to
  39461. scroll far enough for the caret to reach this exact position, but it
  39462. will go as far as it can in that direction.
  39463. */
  39464. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  39465. /** Get the graphical position of the caret.
  39466. The rectangle returned is relative to the component's top-left corner.
  39467. @see scrollEditorToPositionCaret
  39468. */
  39469. const Rectangle<int> getCaretRectangle();
  39470. /** Selects a section of the text. */
  39471. void setHighlightedRegion (const Range<int>& newSelection);
  39472. /** Returns the range of characters that are selected.
  39473. If nothing is selected, this will return an empty range.
  39474. @see setHighlightedRegion
  39475. */
  39476. const Range<int> getHighlightedRegion() const { return selection; }
  39477. /** Returns the section of text that is currently selected. */
  39478. String getHighlightedText() const;
  39479. /** Finds the index of the character at a given position.
  39480. The co-ordinates are relative to the component's top-left.
  39481. */
  39482. int getTextIndexAt (int x, int y);
  39483. /** Counts the number of characters in the text.
  39484. This is quicker than getting the text as a string if you just need to know
  39485. the length.
  39486. */
  39487. int getTotalNumChars() const;
  39488. /** Returns the total width of the text, as it is currently laid-out.
  39489. This may be larger than the size of the TextEditor, and can change when
  39490. the TextEditor is resized or the text changes.
  39491. */
  39492. int getTextWidth() const;
  39493. /** Returns the maximum height of the text, as it is currently laid-out.
  39494. This may be larger than the size of the TextEditor, and can change when
  39495. the TextEditor is resized or the text changes.
  39496. */
  39497. int getTextHeight() const;
  39498. /** Changes the size of the gap at the top and left-edge of the editor.
  39499. By default there's a gap of 4 pixels.
  39500. */
  39501. void setIndents (int newLeftIndent, int newTopIndent);
  39502. /** Changes the size of border left around the edge of the component.
  39503. @see getBorder
  39504. */
  39505. void setBorder (const BorderSize<int>& border);
  39506. /** Returns the size of border around the edge of the component.
  39507. @see setBorder
  39508. */
  39509. const BorderSize<int> getBorder() const;
  39510. /** Used to disable the auto-scrolling which keeps the caret visible.
  39511. If true (the default), the editor will scroll when the caret moves offscreen. If
  39512. set to false, it won't.
  39513. */
  39514. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  39515. /** @internal */
  39516. void paint (Graphics& g);
  39517. /** @internal */
  39518. void paintOverChildren (Graphics& g);
  39519. /** @internal */
  39520. void mouseDown (const MouseEvent& e);
  39521. /** @internal */
  39522. void mouseUp (const MouseEvent& e);
  39523. /** @internal */
  39524. void mouseDrag (const MouseEvent& e);
  39525. /** @internal */
  39526. void mouseDoubleClick (const MouseEvent& e);
  39527. /** @internal */
  39528. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39529. /** @internal */
  39530. bool keyPressed (const KeyPress& key);
  39531. /** @internal */
  39532. bool keyStateChanged (bool isKeyDown);
  39533. /** @internal */
  39534. void focusGained (FocusChangeType cause);
  39535. /** @internal */
  39536. void focusLost (FocusChangeType cause);
  39537. /** @internal */
  39538. void resized();
  39539. /** @internal */
  39540. void enablementChanged();
  39541. /** @internal */
  39542. void colourChanged();
  39543. /** @internal */
  39544. void lookAndFeelChanged();
  39545. /** @internal */
  39546. bool isTextInputActive() const;
  39547. /** @internal */
  39548. void setTemporaryUnderlining (const Array <Range<int> >&);
  39549. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  39550. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  39551. bool moveCaretUp (bool selecting);
  39552. bool moveCaretDown (bool selecting);
  39553. bool pageUp (bool selecting);
  39554. bool pageDown (bool selecting);
  39555. bool scrollDown();
  39556. bool scrollUp();
  39557. bool moveCaretToTop (bool selecting);
  39558. bool moveCaretToStartOfLine (bool selecting);
  39559. bool moveCaretToEnd (bool selecting);
  39560. bool moveCaretToEndOfLine (bool selecting);
  39561. bool deleteBackwards (bool moveInWholeWordSteps);
  39562. bool deleteForwards (bool moveInWholeWordSteps);
  39563. bool copyToClipboard();
  39564. bool cutToClipboard();
  39565. bool pasteFromClipboard();
  39566. bool selectAll();
  39567. bool undo();
  39568. bool redo();
  39569. /** This adds the items to the popup menu.
  39570. By default it adds the cut/copy/paste items, but you can override this if
  39571. you need to replace these with your own items.
  39572. If you want to add your own items to the existing ones, you can override this,
  39573. call the base class's addPopupMenuItems() method, then append your own items.
  39574. When the menu has been shown, performPopupMenuAction() will be called to
  39575. perform the item that the user has chosen.
  39576. The default menu items will be added using item IDs in the range
  39577. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  39578. menu IDs.
  39579. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  39580. a pointer to the info about it, or may be null if the menu is being triggered
  39581. by some other means.
  39582. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  39583. */
  39584. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  39585. const MouseEvent* mouseClickEvent);
  39586. /** This is called to perform one of the items that was shown on the popup menu.
  39587. If you've overridden addPopupMenuItems(), you should also override this
  39588. to perform the actions that you've added.
  39589. If you've overridden addPopupMenuItems() but have still left the default items
  39590. on the menu, remember to call the superclass's performPopupMenuAction()
  39591. so that it can perform the default actions if that's what the user clicked on.
  39592. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  39593. */
  39594. virtual void performPopupMenuAction (int menuItemID);
  39595. protected:
  39596. /** Scrolls the minimum distance needed to get the caret into view. */
  39597. void scrollToMakeSureCursorIsVisible();
  39598. /** @internal */
  39599. void moveCaret (int newCaretPos);
  39600. /** @internal */
  39601. void moveCaretTo (int newPosition, bool isSelecting);
  39602. /** Used internally to dispatch a text-change message. */
  39603. void textChanged();
  39604. /** Begins a new transaction in the UndoManager. */
  39605. void newTransaction();
  39606. /** Used internally to trigger an undo or redo. */
  39607. void doUndoRedo (bool isRedo);
  39608. /** Can be overridden to intercept return key presses directly */
  39609. virtual void returnPressed();
  39610. /** Can be overridden to intercept escape key presses directly */
  39611. virtual void escapePressed();
  39612. /** @internal */
  39613. void handleCommandMessage (int commandId);
  39614. private:
  39615. class Iterator;
  39616. class UniformTextSection;
  39617. class TextHolderComponent;
  39618. class InsertAction;
  39619. class RemoveAction;
  39620. friend class InsertAction;
  39621. friend class RemoveAction;
  39622. ScopedPointer <Viewport> viewport;
  39623. TextHolderComponent* textHolder;
  39624. BorderSize<int> borderSize;
  39625. bool readOnly : 1;
  39626. bool multiline : 1;
  39627. bool wordWrap : 1;
  39628. bool returnKeyStartsNewLine : 1;
  39629. bool popupMenuEnabled : 1;
  39630. bool selectAllTextWhenFocused : 1;
  39631. bool scrollbarVisible : 1;
  39632. bool wasFocused : 1;
  39633. bool keepCaretOnScreen : 1;
  39634. bool tabKeyUsed : 1;
  39635. bool menuActive : 1;
  39636. bool valueTextNeedsUpdating : 1;
  39637. UndoManager undoManager;
  39638. ScopedPointer<CaretComponent> caret;
  39639. int maxTextLength;
  39640. Range<int> selection;
  39641. int leftIndent, topIndent;
  39642. unsigned int lastTransactionTime;
  39643. Font currentFont;
  39644. mutable int totalNumChars;
  39645. int caretPosition;
  39646. Array <UniformTextSection*> sections;
  39647. String textToShowWhenEmpty;
  39648. Colour colourForTextWhenEmpty;
  39649. juce_wchar passwordCharacter;
  39650. Value textValue;
  39651. enum
  39652. {
  39653. notDragging,
  39654. draggingSelectionStart,
  39655. draggingSelectionEnd
  39656. } dragType;
  39657. String allowedCharacters;
  39658. ListenerList <Listener> listeners;
  39659. Array <Range<int> > underlinedSections;
  39660. void coalesceSimilarSections();
  39661. void splitSection (int sectionIndex, int charToSplitAt);
  39662. void clearInternal (UndoManager* um);
  39663. void insert (const String& text, int insertIndex, const Font& font,
  39664. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  39665. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  39666. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  39667. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  39668. void updateCaretPosition();
  39669. void textWasChangedByValue();
  39670. int indexAtPosition (float x, float y);
  39671. int findWordBreakAfter (int position) const;
  39672. int findWordBreakBefore (int position) const;
  39673. bool moveCaretWithTransation (int newPos, bool selecting);
  39674. friend class TextHolderComponent;
  39675. friend class TextEditorViewport;
  39676. void drawContent (Graphics& g);
  39677. void updateTextHolderSize();
  39678. float getWordWrapWidth() const;
  39679. void timerCallbackInt();
  39680. void repaintText (const Range<int>& range);
  39681. void scrollByLines (int deltaLines);
  39682. bool undoOrRedo (bool shouldUndo);
  39683. UndoManager* getUndoManager() noexcept;
  39684. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  39685. };
  39686. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  39687. typedef TextEditor::Listener TextEditorListener;
  39688. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  39689. /*** End of inlined file: juce_TextEditor.h ***/
  39690. #if JUCE_VC6
  39691. #define Listener ButtonListener
  39692. #endif
  39693. /**
  39694. A component that displays a text string, and can optionally become a text
  39695. editor when clicked.
  39696. */
  39697. class JUCE_API Label : public Component,
  39698. public SettableTooltipClient,
  39699. protected TextEditorListener,
  39700. private ComponentListener,
  39701. private ValueListener
  39702. {
  39703. public:
  39704. /** Creates a Label.
  39705. @param componentName the name to give the component
  39706. @param labelText the text to show in the label
  39707. */
  39708. Label (const String& componentName = String::empty,
  39709. const String& labelText = String::empty);
  39710. /** Destructor. */
  39711. ~Label();
  39712. /** Changes the label text.
  39713. If broadcastChangeMessage is true and the new text is different to the current
  39714. text, then the class will broadcast a change message to any Label::Listener objects
  39715. that are registered.
  39716. */
  39717. void setText (const String& newText, bool broadcastChangeMessage);
  39718. /** Returns the label's current text.
  39719. @param returnActiveEditorContents if this is true and the label is currently
  39720. being edited, then this method will return the
  39721. text as it's being shown in the editor. If false,
  39722. then the value returned here won't be updated until
  39723. the user has finished typing and pressed the return
  39724. key.
  39725. */
  39726. const String getText (bool returnActiveEditorContents = false) const;
  39727. /** Returns the text content as a Value object.
  39728. You can call Value::referTo() on this object to make the label read and control
  39729. a Value object that you supply.
  39730. */
  39731. Value& getTextValue() { return textValue; }
  39732. /** Changes the font to use to draw the text.
  39733. @see getFont
  39734. */
  39735. void setFont (const Font& newFont);
  39736. /** Returns the font currently being used.
  39737. @see setFont
  39738. */
  39739. const Font& getFont() const noexcept;
  39740. /** A set of colour IDs to use to change the colour of various aspects of the label.
  39741. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39742. methods.
  39743. Note that you can also use the constants from TextEditor::ColourIds to change the
  39744. colour of the text editor that is opened when a label is editable.
  39745. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39746. */
  39747. enum ColourIds
  39748. {
  39749. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  39750. textColourId = 0x1000281, /**< The colour for the text. */
  39751. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  39752. Leave this transparent to not have an outline. */
  39753. };
  39754. /** Sets the style of justification to be used for positioning the text.
  39755. (The default is Justification::centredLeft)
  39756. */
  39757. void setJustificationType (const Justification& justification);
  39758. /** Returns the type of justification, as set in setJustificationType(). */
  39759. const Justification getJustificationType() const noexcept { return justification; }
  39760. /** Changes the gap that is left between the edge of the component and the text.
  39761. By default there's a small gap left at the sides of the component to allow for
  39762. the drawing of the border, but you can change this if necessary.
  39763. */
  39764. void setBorderSize (int horizontalBorder, int verticalBorder);
  39765. /** Returns the size of the horizontal gap being left around the text.
  39766. */
  39767. int getHorizontalBorderSize() const noexcept { return horizontalBorderSize; }
  39768. /** Returns the size of the vertical gap being left around the text.
  39769. */
  39770. int getVerticalBorderSize() const noexcept { return verticalBorderSize; }
  39771. /** Makes this label "stick to" another component.
  39772. This will cause the label to follow another component around, staying
  39773. either to its left or above it.
  39774. @param owner the component to follow
  39775. @param onLeft if true, the label will stay on the left of its component; if
  39776. false, it will stay above it.
  39777. */
  39778. void attachToComponent (Component* owner, bool onLeft);
  39779. /** If this label has been attached to another component using attachToComponent, this
  39780. returns the other component.
  39781. Returns 0 if the label is not attached.
  39782. */
  39783. Component* getAttachedComponent() const;
  39784. /** If the label is attached to the left of another component, this returns true.
  39785. Returns false if the label is above the other component. This is only relevent if
  39786. attachToComponent() has been called.
  39787. */
  39788. bool isAttachedOnLeft() const noexcept { return leftOfOwnerComp; }
  39789. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  39790. using ellipsis.
  39791. @see Graphics::drawFittedText
  39792. */
  39793. void setMinimumHorizontalScale (float newScale);
  39794. float getMinimumHorizontalScale() const noexcept { return minimumHorizontalScale; }
  39795. /**
  39796. A class for receiving events from a Label.
  39797. You can register a Label::Listener with a Label using the Label::addListener()
  39798. method, and it will be called when the text of the label changes, either because
  39799. of a call to Label::setText() or by the user editing the text (if the label is
  39800. editable).
  39801. @see Label::addListener, Label::removeListener
  39802. */
  39803. class JUCE_API Listener
  39804. {
  39805. public:
  39806. /** Destructor. */
  39807. virtual ~Listener() {}
  39808. /** Called when a Label's text has changed.
  39809. */
  39810. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  39811. };
  39812. /** Registers a listener that will be called when the label's text changes. */
  39813. void addListener (Listener* listener);
  39814. /** Deregisters a previously-registered listener. */
  39815. void removeListener (Listener* listener);
  39816. /** Makes the label turn into a TextEditor when clicked.
  39817. By default this is turned off.
  39818. If turned on, then single- or double-clicking will turn the label into
  39819. an editor. If the user then changes the text, then the ChangeBroadcaster
  39820. base class will be used to send change messages to any listeners that
  39821. have registered.
  39822. If the user changes the text, the textWasEdited() method will be called
  39823. afterwards, and subclasses can override this if they need to do anything
  39824. special.
  39825. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  39826. @param editOnDoubleClick if true, a double-click is needed to start editing
  39827. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  39828. edited will discard any changes; if false, then this will
  39829. commit the changes.
  39830. @see showEditor, setEditorColours, TextEditor
  39831. */
  39832. void setEditable (bool editOnSingleClick,
  39833. bool editOnDoubleClick = false,
  39834. bool lossOfFocusDiscardsChanges = false);
  39835. /** Returns true if this option was set using setEditable(). */
  39836. bool isEditableOnSingleClick() const noexcept { return editSingleClick; }
  39837. /** Returns true if this option was set using setEditable(). */
  39838. bool isEditableOnDoubleClick() const noexcept { return editDoubleClick; }
  39839. /** Returns true if this option has been set in a call to setEditable(). */
  39840. bool doesLossOfFocusDiscardChanges() const noexcept { return lossOfFocusDiscardsChanges; }
  39841. /** Returns true if the user can edit this label's text. */
  39842. bool isEditable() const noexcept { return editSingleClick || editDoubleClick; }
  39843. /** Makes the editor appear as if the label had been clicked by the user.
  39844. @see textWasEdited, setEditable
  39845. */
  39846. void showEditor();
  39847. /** Hides the editor if it was being shown.
  39848. @param discardCurrentEditorContents if true, the label's text will be
  39849. reset to whatever it was before the editor
  39850. was shown; if false, the current contents of the
  39851. editor will be used to set the label's text
  39852. before it is hidden.
  39853. */
  39854. void hideEditor (bool discardCurrentEditorContents);
  39855. /** Returns true if the editor is currently focused and active. */
  39856. bool isBeingEdited() const noexcept;
  39857. protected:
  39858. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  39859. Subclasses can override this if they need to customise this component in some way.
  39860. */
  39861. virtual TextEditor* createEditorComponent();
  39862. /** Called after the user changes the text. */
  39863. virtual void textWasEdited();
  39864. /** Called when the text has been altered. */
  39865. virtual void textWasChanged();
  39866. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  39867. virtual void editorShown (TextEditor* editorComponent);
  39868. /** Called when the text editor is going to be deleted, after editing has finished. */
  39869. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  39870. /** @internal */
  39871. void paint (Graphics& g);
  39872. /** @internal */
  39873. void resized();
  39874. /** @internal */
  39875. void mouseUp (const MouseEvent& e);
  39876. /** @internal */
  39877. void mouseDoubleClick (const MouseEvent& e);
  39878. /** @internal */
  39879. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  39880. /** @internal */
  39881. void componentParentHierarchyChanged (Component& component);
  39882. /** @internal */
  39883. void componentVisibilityChanged (Component& component);
  39884. /** @internal */
  39885. void inputAttemptWhenModal();
  39886. /** @internal */
  39887. void focusGained (FocusChangeType);
  39888. /** @internal */
  39889. void enablementChanged();
  39890. /** @internal */
  39891. KeyboardFocusTraverser* createFocusTraverser();
  39892. /** @internal */
  39893. void textEditorTextChanged (TextEditor& editor);
  39894. /** @internal */
  39895. void textEditorReturnKeyPressed (TextEditor& editor);
  39896. /** @internal */
  39897. void textEditorEscapeKeyPressed (TextEditor& editor);
  39898. /** @internal */
  39899. void textEditorFocusLost (TextEditor& editor);
  39900. /** @internal */
  39901. void colourChanged();
  39902. /** @internal */
  39903. void valueChanged (Value&);
  39904. private:
  39905. Value textValue;
  39906. String lastTextValue;
  39907. Font font;
  39908. Justification justification;
  39909. ScopedPointer<TextEditor> editor;
  39910. ListenerList<Listener> listeners;
  39911. WeakReference<Component> ownerComponent;
  39912. int horizontalBorderSize, verticalBorderSize;
  39913. float minimumHorizontalScale;
  39914. bool editSingleClick : 1;
  39915. bool editDoubleClick : 1;
  39916. bool lossOfFocusDiscardsChanges : 1;
  39917. bool leftOfOwnerComp : 1;
  39918. bool updateFromTextEditorContents (TextEditor&);
  39919. void callChangeListeners();
  39920. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  39921. };
  39922. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  39923. typedef Label::Listener LabelListener;
  39924. #if JUCE_VC6
  39925. #undef Listener
  39926. #endif
  39927. #endif // __JUCE_LABEL_JUCEHEADER__
  39928. /*** End of inlined file: juce_Label.h ***/
  39929. #if JUCE_VC6
  39930. #define Listener SliderListener
  39931. #endif
  39932. /**
  39933. A component that lets the user choose from a drop-down list of choices.
  39934. The combo-box has a list of text strings, each with an associated id number,
  39935. that will be shown in the drop-down list when the user clicks on the component.
  39936. The currently selected choice is displayed in the combo-box, and this can
  39937. either be read-only text, or editable.
  39938. To find out when the user selects a different item or edits the text, you
  39939. can register a ComboBox::Listener to receive callbacks.
  39940. @see ComboBox::Listener
  39941. */
  39942. class JUCE_API ComboBox : public Component,
  39943. public SettableTooltipClient,
  39944. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  39945. public ValueListener,
  39946. private AsyncUpdater
  39947. {
  39948. public:
  39949. /** Creates a combo-box.
  39950. On construction, the text field will be empty, so you should call the
  39951. setSelectedId() or setText() method to choose the initial value before
  39952. displaying it.
  39953. @param componentName the name to set for the component (see Component::setName())
  39954. */
  39955. explicit ComboBox (const String& componentName = String::empty);
  39956. /** Destructor. */
  39957. ~ComboBox();
  39958. /** Sets whether the test in the combo-box is editable.
  39959. The default state for a new ComboBox is non-editable, and can only be changed
  39960. by choosing from the drop-down list.
  39961. */
  39962. void setEditableText (bool isEditable);
  39963. /** Returns true if the text is directly editable.
  39964. @see setEditableText
  39965. */
  39966. bool isTextEditable() const noexcept;
  39967. /** Sets the style of justification to be used for positioning the text.
  39968. The default is Justification::centredLeft. The text is displayed using a
  39969. Label component inside the ComboBox.
  39970. */
  39971. void setJustificationType (const Justification& justification);
  39972. /** Returns the current justification for the text box.
  39973. @see setJustificationType
  39974. */
  39975. const Justification getJustificationType() const noexcept;
  39976. /** Adds an item to be shown in the drop-down list.
  39977. @param newItemText the text of the item to show in the list
  39978. @param newItemId an associated ID number that can be set or retrieved - see
  39979. getSelectedId() and setSelectedId(). Note that this value can not
  39980. be 0!
  39981. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  39982. */
  39983. void addItem (const String& newItemText, int newItemId);
  39984. /** Adds a separator line to the drop-down list.
  39985. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  39986. */
  39987. void addSeparator();
  39988. /** Adds a heading to the drop-down list, so that you can group the items into
  39989. different sections.
  39990. The headings are indented slightly differently to set them apart from the
  39991. items on the list, and obviously can't be selected. You might want to add
  39992. separators between your sections too.
  39993. @see addItem, addSeparator
  39994. */
  39995. void addSectionHeading (const String& headingName);
  39996. /** This allows items in the drop-down list to be selectively disabled.
  39997. When you add an item, it's enabled by default, but you can call this
  39998. method to change its status.
  39999. If you disable an item which is already selected, this won't change the
  40000. current selection - it just stops the user choosing that item from the list.
  40001. */
  40002. void setItemEnabled (int itemId, bool shouldBeEnabled);
  40003. /** Returns true if the given item is enabled. */
  40004. bool isItemEnabled (int itemId) const noexcept;
  40005. /** Changes the text for an existing item.
  40006. */
  40007. void changeItemText (int itemId, const String& newText);
  40008. /** Removes all the items from the drop-down list.
  40009. If this call causes the content to be cleared, then a change-message
  40010. will be broadcast unless dontSendChangeMessage is true.
  40011. @see addItem, removeItem, getNumItems
  40012. */
  40013. void clear (bool dontSendChangeMessage = false);
  40014. /** Returns the number of items that have been added to the list.
  40015. Note that this doesn't include headers or separators.
  40016. */
  40017. int getNumItems() const noexcept;
  40018. /** Returns the text for one of the items in the list.
  40019. Note that this doesn't include headers or separators.
  40020. @param index the item's index from 0 to (getNumItems() - 1)
  40021. */
  40022. String getItemText (int index) const;
  40023. /** Returns the ID for one of the items in the list.
  40024. Note that this doesn't include headers or separators.
  40025. @param index the item's index from 0 to (getNumItems() - 1)
  40026. */
  40027. int getItemId (int index) const noexcept;
  40028. /** Returns the index in the list of a particular item ID.
  40029. If no such ID is found, this will return -1.
  40030. */
  40031. int indexOfItemId (int itemId) const noexcept;
  40032. /** Returns the ID of the item that's currently shown in the box.
  40033. If no item is selected, or if the text is editable and the user
  40034. has entered something which isn't one of the items in the list, then
  40035. this will return 0.
  40036. @see setSelectedId, getSelectedItemIndex, getText
  40037. */
  40038. int getSelectedId() const noexcept;
  40039. /** Returns a Value object that can be used to get or set the selected item's ID.
  40040. You can call Value::referTo() on this object to make the combo box control
  40041. another Value object.
  40042. */
  40043. Value& getSelectedIdAsValue() { return currentId; }
  40044. /** Sets one of the items to be the current selection.
  40045. This will set the ComboBox's text to that of the item that matches
  40046. this ID.
  40047. @param newItemId the new item to select
  40048. @param dontSendChangeMessage if set to true, this method won't trigger a
  40049. change notification
  40050. @see getSelectedId, setSelectedItemIndex, setText
  40051. */
  40052. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  40053. /** Returns the index of the item that's currently shown in the box.
  40054. If no item is selected, or if the text is editable and the user
  40055. has entered something which isn't one of the items in the list, then
  40056. this will return -1.
  40057. @see setSelectedItemIndex, getSelectedId, getText
  40058. */
  40059. int getSelectedItemIndex() const;
  40060. /** Sets one of the items to be the current selection.
  40061. This will set the ComboBox's text to that of the item at the given
  40062. index in the list.
  40063. @param newItemIndex the new item to select
  40064. @param dontSendChangeMessage if set to true, this method won't trigger a
  40065. change notification
  40066. @see getSelectedItemIndex, setSelectedId, setText
  40067. */
  40068. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  40069. /** Returns the text that is currently shown in the combo-box's text field.
  40070. If the ComboBox has editable text, then this text may have been edited
  40071. by the user; otherwise it will be one of the items from the list, or
  40072. possibly an empty string if nothing was selected.
  40073. @see setText, getSelectedId, getSelectedItemIndex
  40074. */
  40075. String getText() const;
  40076. /** Sets the contents of the combo-box's text field.
  40077. The text passed-in will be set as the current text regardless of whether
  40078. it is one of the items in the list. If the current text isn't one of the
  40079. items, then getSelectedId() will return -1, otherwise it wil return
  40080. the approriate ID.
  40081. @param newText the text to select
  40082. @param dontSendChangeMessage if set to true, this method won't trigger a
  40083. change notification
  40084. @see getText
  40085. */
  40086. void setText (const String& newText, bool dontSendChangeMessage = false);
  40087. /** Programmatically opens the text editor to allow the user to edit the current item.
  40088. This is the same effect as when the box is clicked-on.
  40089. @see Label::showEditor();
  40090. */
  40091. void showEditor();
  40092. /** Pops up the combo box's list. */
  40093. void showPopup();
  40094. /**
  40095. A class for receiving events from a ComboBox.
  40096. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  40097. method, and it will be called when the selected item in the box changes.
  40098. @see ComboBox::addListener, ComboBox::removeListener
  40099. */
  40100. class JUCE_API Listener
  40101. {
  40102. public:
  40103. /** Destructor. */
  40104. virtual ~Listener() {}
  40105. /** Called when a ComboBox has its selected item changed. */
  40106. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  40107. };
  40108. /** Registers a listener that will be called when the box's content changes. */
  40109. void addListener (Listener* listener);
  40110. /** Deregisters a previously-registered listener. */
  40111. void removeListener (Listener* listener);
  40112. /** Sets a message to display when there is no item currently selected.
  40113. @see getTextWhenNothingSelected
  40114. */
  40115. void setTextWhenNothingSelected (const String& newMessage);
  40116. /** Returns the text that is shown when no item is selected.
  40117. @see setTextWhenNothingSelected
  40118. */
  40119. String getTextWhenNothingSelected() const;
  40120. /** Sets the message to show when there are no items in the list, and the user clicks
  40121. on the drop-down box.
  40122. By default it just says "no choices", but this lets you change it to something more
  40123. meaningful.
  40124. */
  40125. void setTextWhenNoChoicesAvailable (const String& newMessage);
  40126. /** Returns the text shown when no items have been added to the list.
  40127. @see setTextWhenNoChoicesAvailable
  40128. */
  40129. String getTextWhenNoChoicesAvailable() const;
  40130. /** Gives the ComboBox a tooltip. */
  40131. void setTooltip (const String& newTooltip);
  40132. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  40133. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40134. methods.
  40135. To change the colours of the menu that pops up
  40136. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40137. */
  40138. enum ColourIds
  40139. {
  40140. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  40141. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  40142. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  40143. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  40144. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  40145. };
  40146. /** @internal */
  40147. void labelTextChanged (Label*);
  40148. /** @internal */
  40149. void enablementChanged();
  40150. /** @internal */
  40151. void colourChanged();
  40152. /** @internal */
  40153. void focusGained (Component::FocusChangeType cause);
  40154. /** @internal */
  40155. void focusLost (Component::FocusChangeType cause);
  40156. /** @internal */
  40157. void handleAsyncUpdate();
  40158. /** @internal */
  40159. const String getTooltip() { return label->getTooltip(); }
  40160. /** @internal */
  40161. void mouseDown (const MouseEvent&);
  40162. /** @internal */
  40163. void mouseDrag (const MouseEvent&);
  40164. /** @internal */
  40165. void mouseUp (const MouseEvent&);
  40166. /** @internal */
  40167. void lookAndFeelChanged();
  40168. /** @internal */
  40169. void paint (Graphics&);
  40170. /** @internal */
  40171. void resized();
  40172. /** @internal */
  40173. bool keyStateChanged (bool isKeyDown);
  40174. /** @internal */
  40175. bool keyPressed (const KeyPress&);
  40176. /** @internal */
  40177. void valueChanged (Value&);
  40178. private:
  40179. struct ItemInfo
  40180. {
  40181. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  40182. bool isSeparator() const noexcept;
  40183. bool isRealItem() const noexcept;
  40184. String name;
  40185. int itemId;
  40186. bool isEnabled : 1, isHeading : 1;
  40187. };
  40188. OwnedArray <ItemInfo> items;
  40189. Value currentId;
  40190. int lastCurrentId;
  40191. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  40192. ListenerList <Listener> listeners;
  40193. ScopedPointer<Label> label;
  40194. String textWhenNothingSelected, noChoicesMessage;
  40195. ItemInfo* getItemForId (int itemId) const noexcept;
  40196. ItemInfo* getItemForIndex (int index) const noexcept;
  40197. bool selectIfEnabled (int index);
  40198. static void popupMenuFinishedCallback (int, ComboBox*);
  40199. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  40200. };
  40201. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  40202. typedef ComboBox::Listener ComboBoxListener;
  40203. #if JUCE_VC6
  40204. #undef Listener
  40205. #endif
  40206. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  40207. /*** End of inlined file: juce_ComboBox.h ***/
  40208. #endif
  40209. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40210. /*** Start of inlined file: juce_ImageComponent.h ***/
  40211. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40212. #define __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40213. /**
  40214. A component that simply displays an image.
  40215. Use setImage to give it an image, and it'll display it - simple as that!
  40216. */
  40217. class JUCE_API ImageComponent : public Component,
  40218. public SettableTooltipClient
  40219. {
  40220. public:
  40221. /** Creates an ImageComponent. */
  40222. ImageComponent (const String& componentName = String::empty);
  40223. /** Destructor. */
  40224. ~ImageComponent();
  40225. /** Sets the image that should be displayed. */
  40226. void setImage (const Image& newImage);
  40227. /** Sets the image that should be displayed, and its placement within the component. */
  40228. void setImage (const Image& newImage,
  40229. const RectanglePlacement& placementToUse);
  40230. /** Returns the current image. */
  40231. const Image& getImage() const;
  40232. /** Sets the method of positioning that will be used to fit the image within the component's bounds.
  40233. By default the positioning is centred, and will fit the image inside the component's bounds
  40234. whilst keeping its aspect ratio correct, but you can change it to whatever layout you need.
  40235. */
  40236. void setImagePlacement (const RectanglePlacement& newPlacement);
  40237. /** Returns the current image placement. */
  40238. const RectanglePlacement getImagePlacement() const;
  40239. /** @internal */
  40240. void paint (Graphics& g);
  40241. private:
  40242. Image image;
  40243. RectanglePlacement placement;
  40244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageComponent);
  40245. };
  40246. #endif // __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40247. /*** End of inlined file: juce_ImageComponent.h ***/
  40248. #endif
  40249. #ifndef __JUCE_LABEL_JUCEHEADER__
  40250. #endif
  40251. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  40252. #endif
  40253. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  40254. /*** Start of inlined file: juce_ProgressBar.h ***/
  40255. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  40256. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  40257. /**
  40258. A progress bar component.
  40259. To use this, just create one and make it visible. It'll run its own timer
  40260. to keep an eye on a variable that you give it, and will automatically
  40261. redraw itself when the variable changes.
  40262. For an easy way of running a background task with a dialog box showing its
  40263. progress, see the ThreadWithProgressWindow class.
  40264. @see ThreadWithProgressWindow
  40265. */
  40266. class JUCE_API ProgressBar : public Component,
  40267. public SettableTooltipClient,
  40268. private Timer
  40269. {
  40270. public:
  40271. /** Creates a ProgressBar.
  40272. @param progress pass in a reference to a double that you're going to
  40273. update with your task's progress. The ProgressBar will
  40274. monitor the value of this variable and will redraw itself
  40275. when the value changes. The range is from 0 to 1.0. Obviously
  40276. you'd better be careful not to delete this variable while the
  40277. ProgressBar still exists!
  40278. */
  40279. explicit ProgressBar (double& progress);
  40280. /** Destructor. */
  40281. ~ProgressBar();
  40282. /** Turns the percentage display on or off.
  40283. By default this is on, and the progress bar will display a text string showing
  40284. its current percentage.
  40285. */
  40286. void setPercentageDisplay (bool shouldDisplayPercentage);
  40287. /** Gives the progress bar a string to display inside it.
  40288. If you call this, it will turn off the percentage display.
  40289. @see setPercentageDisplay
  40290. */
  40291. void setTextToDisplay (const String& text);
  40292. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  40293. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40294. methods.
  40295. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40296. */
  40297. enum ColourIds
  40298. {
  40299. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  40300. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  40301. classes will probably use variations on this colour. */
  40302. };
  40303. protected:
  40304. /** @internal */
  40305. void paint (Graphics& g);
  40306. /** @internal */
  40307. void lookAndFeelChanged();
  40308. /** @internal */
  40309. void visibilityChanged();
  40310. /** @internal */
  40311. void colourChanged();
  40312. private:
  40313. double& progress;
  40314. double currentValue;
  40315. bool displayPercentage;
  40316. String displayedMessage, currentMessage;
  40317. uint32 lastCallbackTime;
  40318. void timerCallback();
  40319. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  40320. };
  40321. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  40322. /*** End of inlined file: juce_ProgressBar.h ***/
  40323. #endif
  40324. #ifndef __JUCE_SLIDER_JUCEHEADER__
  40325. /*** Start of inlined file: juce_Slider.h ***/
  40326. #ifndef __JUCE_SLIDER_JUCEHEADER__
  40327. #define __JUCE_SLIDER_JUCEHEADER__
  40328. #if JUCE_VC6
  40329. #define Listener LabelListener
  40330. #endif
  40331. /**
  40332. A slider control for changing a value.
  40333. The slider can be horizontal, vertical, or rotary, and can optionally have
  40334. a text-box inside it to show an editable display of the current value.
  40335. To use it, create a Slider object and use the setSliderStyle() method
  40336. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  40337. To define the values that it can be set to, see the setRange() and setValue() methods.
  40338. There are also lots of custom tweaks you can do by subclassing and overriding
  40339. some of the virtual methods, such as changing the scaling, changing the format of
  40340. the text display, custom ways of limiting the values, etc.
  40341. You can register Slider::Listener objects with a slider, and they'll be called when
  40342. the value changes.
  40343. @see Slider::Listener
  40344. */
  40345. class JUCE_API Slider : public Component,
  40346. public SettableTooltipClient,
  40347. public AsyncUpdater,
  40348. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  40349. public LabelListener,
  40350. public ValueListener
  40351. {
  40352. public:
  40353. /** Creates a slider.
  40354. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  40355. setRange(), etc.
  40356. */
  40357. explicit Slider (const String& componentName = String::empty);
  40358. /** Destructor. */
  40359. ~Slider();
  40360. /** The types of slider available.
  40361. @see setSliderStyle, setRotaryParameters
  40362. */
  40363. enum SliderStyle
  40364. {
  40365. LinearHorizontal, /**< A traditional horizontal slider. */
  40366. LinearVertical, /**< A traditional vertical slider. */
  40367. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  40368. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  40369. @see setRotaryParameters */
  40370. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  40371. @see setRotaryParameters */
  40372. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  40373. @see setRotaryParameters */
  40374. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  40375. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  40376. @see setMinValue, setMaxValue */
  40377. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  40378. @see setMinValue, setMaxValue */
  40379. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  40380. value, with the current value being somewhere between them.
  40381. @see setMinValue, setMaxValue */
  40382. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  40383. value, with the current value being somewhere between them.
  40384. @see setMinValue, setMaxValue */
  40385. };
  40386. /** Changes the type of slider interface being used.
  40387. @param newStyle the type of interface
  40388. @see setRotaryParameters, setVelocityBasedMode,
  40389. */
  40390. void setSliderStyle (SliderStyle newStyle);
  40391. /** Returns the slider's current style.
  40392. @see setSliderStyle
  40393. */
  40394. SliderStyle getSliderStyle() const noexcept { return style; }
  40395. /** Changes the properties of a rotary slider.
  40396. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  40397. the slider's minimum value is represented
  40398. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  40399. the slider's maximum value is represented. This must be
  40400. greater than startAngleRadians
  40401. @param stopAtEnd if true, then when the slider is dragged around past the
  40402. minimum or maximum, it'll stop there; if false, it'll wrap
  40403. back to the opposite value
  40404. */
  40405. void setRotaryParameters (float startAngleRadians,
  40406. float endAngleRadians,
  40407. bool stopAtEnd);
  40408. /** Sets the distance the mouse has to move to drag the slider across
  40409. the full extent of its range.
  40410. This only applies when in modes like RotaryHorizontalDrag, where it's using
  40411. relative mouse movements to adjust the slider.
  40412. */
  40413. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  40414. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  40415. int getMouseDragSensitivity() const noexcept { return pixelsForFullDragExtent; }
  40416. /** Changes the way the the mouse is used when dragging the slider.
  40417. If true, this will turn on velocity-sensitive dragging, so that
  40418. the faster the mouse moves, the bigger the movement to the slider. This
  40419. helps when making accurate adjustments if the slider's range is quite large.
  40420. If false, the slider will just try to snap to wherever the mouse is.
  40421. */
  40422. void setVelocityBasedMode (bool isVelocityBased);
  40423. /** Returns true if velocity-based mode is active.
  40424. @see setVelocityBasedMode
  40425. */
  40426. bool getVelocityBasedMode() const noexcept { return isVelocityBased; }
  40427. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  40428. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  40429. or if you're holding down ctrl.
  40430. @param sensitivity higher values than 1.0 increase the range of acceleration used
  40431. @param threshold the minimum number of pixels that the mouse needs to move for it
  40432. to be treated as a movement
  40433. @param offset values greater than 0.0 increase the minimum speed that will be used when
  40434. the threshold is reached
  40435. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  40436. key to toggle velocity-sensitive mode
  40437. */
  40438. void setVelocityModeParameters (double sensitivity = 1.0,
  40439. int threshold = 1,
  40440. double offset = 0.0,
  40441. bool userCanPressKeyToSwapMode = true);
  40442. /** Returns the velocity sensitivity setting.
  40443. @see setVelocityModeParameters
  40444. */
  40445. double getVelocitySensitivity() const noexcept { return velocityModeSensitivity; }
  40446. /** Returns the velocity threshold setting.
  40447. @see setVelocityModeParameters
  40448. */
  40449. int getVelocityThreshold() const noexcept { return velocityModeThreshold; }
  40450. /** Returns the velocity offset setting.
  40451. @see setVelocityModeParameters
  40452. */
  40453. double getVelocityOffset() const noexcept { return velocityModeOffset; }
  40454. /** Returns the velocity user key setting.
  40455. @see setVelocityModeParameters
  40456. */
  40457. bool getVelocityModeIsSwappable() const noexcept { return userKeyOverridesVelocity; }
  40458. /** Sets up a skew factor to alter the way values are distributed.
  40459. You may want to use a range of values on the slider where more accuracy
  40460. is required towards one end of the range, so this will logarithmically
  40461. spread the values across the length of the slider.
  40462. If the factor is < 1.0, the lower end of the range will fill more of the
  40463. slider's length; if the factor is > 1.0, the upper end of the range
  40464. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  40465. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  40466. method instead.
  40467. @see getSkewFactor, setSkewFactorFromMidPoint
  40468. */
  40469. void setSkewFactor (double factor);
  40470. /** Sets up a skew factor to alter the way values are distributed.
  40471. This allows you to specify the slider value that should appear in the
  40472. centre of the slider's visible range.
  40473. @see setSkewFactor, getSkewFactor
  40474. */
  40475. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  40476. /** Returns the current skew factor.
  40477. See setSkewFactor for more info.
  40478. @see setSkewFactor, setSkewFactorFromMidPoint
  40479. */
  40480. double getSkewFactor() const noexcept { return skewFactor; }
  40481. /** Used by setIncDecButtonsMode().
  40482. */
  40483. enum IncDecButtonMode
  40484. {
  40485. incDecButtonsNotDraggable,
  40486. incDecButtonsDraggable_AutoDirection,
  40487. incDecButtonsDraggable_Horizontal,
  40488. incDecButtonsDraggable_Vertical
  40489. };
  40490. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  40491. can be dragged on the buttons to drag the values.
  40492. By default this is turned off. When enabled, clicking on the buttons still works
  40493. them as normal, but by holding down the mouse on a button and dragging it a little
  40494. distance, it flips into a mode where the value can be dragged. The drag direction can
  40495. either be set explicitly to be vertical or horizontal, or can be set to
  40496. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  40497. are side-by-side or above each other.
  40498. */
  40499. void setIncDecButtonsMode (IncDecButtonMode mode);
  40500. /** The position of the slider's text-entry box.
  40501. @see setTextBoxStyle
  40502. */
  40503. enum TextEntryBoxPosition
  40504. {
  40505. NoTextBox, /**< Doesn't display a text box. */
  40506. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  40507. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  40508. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  40509. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  40510. };
  40511. /** Changes the location and properties of the text-entry box.
  40512. @param newPosition where it should go (or NoTextBox to not have one at all)
  40513. @param isReadOnly if true, it's a read-only display
  40514. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  40515. room for the slider as well!
  40516. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  40517. room for the slider as well!
  40518. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  40519. */
  40520. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  40521. bool isReadOnly,
  40522. int textEntryBoxWidth,
  40523. int textEntryBoxHeight);
  40524. /** Returns the status of the text-box.
  40525. @see setTextBoxStyle
  40526. */
  40527. const TextEntryBoxPosition getTextBoxPosition() const noexcept { return textBoxPos; }
  40528. /** Returns the width used for the text-box.
  40529. @see setTextBoxStyle
  40530. */
  40531. int getTextBoxWidth() const noexcept { return textBoxWidth; }
  40532. /** Returns the height used for the text-box.
  40533. @see setTextBoxStyle
  40534. */
  40535. int getTextBoxHeight() const noexcept { return textBoxHeight; }
  40536. /** Makes the text-box editable.
  40537. By default this is true, and the user can enter values into the textbox,
  40538. but it can be turned off if that's not suitable.
  40539. @see setTextBoxStyle, getValueFromText, getTextFromValue
  40540. */
  40541. void setTextBoxIsEditable (bool shouldBeEditable);
  40542. /** Returns true if the text-box is read-only.
  40543. @see setTextBoxStyle
  40544. */
  40545. bool isTextBoxEditable() const { return editableText; }
  40546. /** If the text-box is editable, this will give it the focus so that the user can
  40547. type directly into it.
  40548. This is basically the effect as the user clicking on it.
  40549. */
  40550. void showTextBox();
  40551. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  40552. focus away from it.
  40553. @param discardCurrentEditorContents if true, the slider's value will be left
  40554. unchanged; if false, the current contents of the
  40555. text editor will be used to set the slider position
  40556. before it is hidden.
  40557. */
  40558. void hideTextBox (bool discardCurrentEditorContents);
  40559. /** Changes the slider's current value.
  40560. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40561. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40562. want to handle it.
  40563. @param newValue the new value to set - this will be restricted by the
  40564. minimum and maximum range, and will be snapped to the
  40565. nearest interval if one has been set
  40566. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40567. any Slider::Listeners or the valueChanged() method
  40568. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40569. synchronously; if false, it will be asynchronous
  40570. */
  40571. void setValue (double newValue,
  40572. bool sendUpdateMessage = true,
  40573. bool sendMessageSynchronously = false);
  40574. /** Returns the slider's current value. */
  40575. double getValue() const;
  40576. /** Returns the Value object that represents the slider's current position.
  40577. You can use this Value object to connect the slider's position to external values or setters,
  40578. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40579. your own Value object.
  40580. @see Value, getMaxValue, getMinValueObject
  40581. */
  40582. Value& getValueObject() { return currentValue; }
  40583. /** Sets the limits that the slider's value can take.
  40584. @param newMinimum the lowest value allowed
  40585. @param newMaximum the highest value allowed
  40586. @param newInterval the steps in which the value is allowed to increase - if this
  40587. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  40588. */
  40589. void setRange (double newMinimum,
  40590. double newMaximum,
  40591. double newInterval = 0);
  40592. /** Returns the current maximum value.
  40593. @see setRange
  40594. */
  40595. double getMaximum() const { return maximum; }
  40596. /** Returns the current minimum value.
  40597. @see setRange
  40598. */
  40599. double getMinimum() const { return minimum; }
  40600. /** Returns the current step-size for values.
  40601. @see setRange
  40602. */
  40603. double getInterval() const { return interval; }
  40604. /** For a slider with two or three thumbs, this returns the lower of its values.
  40605. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40606. A slider with three values also uses the normal getValue() and setValue() methods to
  40607. control the middle value.
  40608. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40609. */
  40610. double getMinValue() const;
  40611. /** For a slider with two or three thumbs, this returns the lower of its values.
  40612. You can use this Value object to connect the slider's position to external values or setters,
  40613. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40614. your own Value object.
  40615. @see Value, getMinValue, getMaxValueObject
  40616. */
  40617. Value& getMinValueObject() noexcept { return valueMin; }
  40618. /** For a slider with two or three thumbs, this sets the lower of its values.
  40619. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40620. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40621. want to handle it.
  40622. @param newValue the new value to set - this will be restricted by the
  40623. minimum and maximum range, and will be snapped to the nearest
  40624. interval if one has been set.
  40625. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40626. any Slider::Listeners or the valueChanged() method
  40627. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40628. synchronously; if false, it will be asynchronous
  40629. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  40630. max value (in a two-value slider) or the mid value (in a three-value
  40631. slider). If false, then if this value goes beyond those values,
  40632. it will push them along with it.
  40633. @see getMinValue, setMaxValue, setValue
  40634. */
  40635. void setMinValue (double newValue,
  40636. bool sendUpdateMessage = true,
  40637. bool sendMessageSynchronously = false,
  40638. bool allowNudgingOfOtherValues = false);
  40639. /** For a slider with two or three thumbs, this returns the higher of its values.
  40640. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40641. A slider with three values also uses the normal getValue() and setValue() methods to
  40642. control the middle value.
  40643. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40644. */
  40645. double getMaxValue() const;
  40646. /** For a slider with two or three thumbs, this returns the higher of its values.
  40647. You can use this Value object to connect the slider's position to external values or setters,
  40648. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40649. your own Value object.
  40650. @see Value, getMaxValue, getMinValueObject
  40651. */
  40652. Value& getMaxValueObject() noexcept { return valueMax; }
  40653. /** For a slider with two or three thumbs, this sets the lower of its values.
  40654. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40655. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40656. want to handle it.
  40657. @param newValue the new value to set - this will be restricted by the
  40658. minimum and maximum range, and will be snapped to the nearest
  40659. interval if one has been set.
  40660. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40661. any Slider::Listeners or the valueChanged() method
  40662. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40663. synchronously; if false, it will be asynchronous
  40664. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  40665. min value (in a two-value slider) or the mid value (in a three-value
  40666. slider). If false, then if this value goes beyond those values,
  40667. it will push them along with it.
  40668. @see getMaxValue, setMinValue, setValue
  40669. */
  40670. void setMaxValue (double newValue,
  40671. bool sendUpdateMessage = true,
  40672. bool sendMessageSynchronously = false,
  40673. bool allowNudgingOfOtherValues = false);
  40674. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  40675. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40676. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40677. want to handle it.
  40678. @param newMinValue the new minimum value to set - this will be snapped to the
  40679. nearest interval if one has been set.
  40680. @param newMaxValue the new minimum value to set - this will be snapped to the
  40681. nearest interval if one has been set.
  40682. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40683. any Slider::Listeners or the valueChanged() method
  40684. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40685. synchronously; if false, it will be asynchronous
  40686. @see setMaxValue, setMinValue, setValue
  40687. */
  40688. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  40689. bool sendUpdateMessage = true,
  40690. bool sendMessageSynchronously = false);
  40691. /** A class for receiving callbacks from a Slider.
  40692. To be told when a slider's value changes, you can register a Slider::Listener
  40693. object using Slider::addListener().
  40694. @see Slider::addListener, Slider::removeListener
  40695. */
  40696. class JUCE_API Listener
  40697. {
  40698. public:
  40699. /** Destructor. */
  40700. virtual ~Listener() {}
  40701. /** Called when the slider's value is changed.
  40702. This may be caused by dragging it, or by typing in its text entry box,
  40703. or by a call to Slider::setValue().
  40704. You can find out the new value using Slider::getValue().
  40705. @see Slider::valueChanged
  40706. */
  40707. virtual void sliderValueChanged (Slider* slider) = 0;
  40708. /** Called when the slider is about to be dragged.
  40709. This is called when a drag begins, then it's followed by multiple calls
  40710. to sliderValueChanged(), and then sliderDragEnded() is called after the
  40711. user lets go.
  40712. @see sliderDragEnded, Slider::startedDragging
  40713. */
  40714. virtual void sliderDragStarted (Slider* slider);
  40715. /** Called after a drag operation has finished.
  40716. @see sliderDragStarted, Slider::stoppedDragging
  40717. */
  40718. virtual void sliderDragEnded (Slider* slider);
  40719. };
  40720. /** Adds a listener to be called when this slider's value changes. */
  40721. void addListener (Listener* listener);
  40722. /** Removes a previously-registered listener. */
  40723. void removeListener (Listener* listener);
  40724. /** This lets you choose whether double-clicking moves the slider to a given position.
  40725. By default this is turned off, but it's handy if you want a double-click to act
  40726. as a quick way of resetting a slider. Just pass in the value you want it to
  40727. go to when double-clicked.
  40728. @see getDoubleClickReturnValue
  40729. */
  40730. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  40731. double valueToSetOnDoubleClick);
  40732. /** Returns the values last set by setDoubleClickReturnValue() method.
  40733. Sets isEnabled to true if double-click is enabled, and returns the value
  40734. that was set.
  40735. @see setDoubleClickReturnValue
  40736. */
  40737. double getDoubleClickReturnValue (bool& isEnabled) const;
  40738. /** Tells the slider whether to keep sending change messages while the user
  40739. is dragging the slider.
  40740. If set to true, a change message will only be sent when the user has
  40741. dragged the slider and let go. If set to false (the default), then messages
  40742. will be continuously sent as they drag it while the mouse button is still
  40743. held down.
  40744. */
  40745. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  40746. /** This lets you change whether the slider thumb jumps to the mouse position
  40747. when you click.
  40748. By default, this is true. If it's false, then the slider moves with relative
  40749. motion when you drag it.
  40750. This only applies to linear bars, and won't affect two- or three- value
  40751. sliders.
  40752. */
  40753. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  40754. /** If enabled, this gives the slider a pop-up bubble which appears while the
  40755. slider is being dragged.
  40756. This can be handy if your slider doesn't have a text-box, so that users can
  40757. see the value just when they're changing it.
  40758. If you pass a component as the parentComponentToUse parameter, the pop-up
  40759. bubble will be added as a child of that component when it's needed. If you
  40760. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  40761. transparent window, so if you're using an OS that can't do transparent windows
  40762. you'll have to add it to a parent component instead).
  40763. */
  40764. void setPopupDisplayEnabled (bool isEnabled,
  40765. Component* parentComponentToUse);
  40766. /** If this is set to true, then right-clicking on the slider will pop-up
  40767. a menu to let the user change the way it works.
  40768. By default this is turned off, but when turned on, the menu will include
  40769. things like velocity sensitivity, and for rotary sliders, whether they
  40770. use a linear or rotary mouse-drag to move them.
  40771. */
  40772. void setPopupMenuEnabled (bool menuEnabled);
  40773. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  40774. By default it's enabled.
  40775. */
  40776. void setScrollWheelEnabled (bool enabled);
  40777. /** Returns a number to indicate which thumb is currently being dragged by the
  40778. mouse.
  40779. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  40780. the maximum-value thumb, or -1 if none is currently down.
  40781. */
  40782. int getThumbBeingDragged() const noexcept { return sliderBeingDragged; }
  40783. /** Callback to indicate that the user is about to start dragging the slider.
  40784. @see Slider::Listener::sliderDragStarted
  40785. */
  40786. virtual void startedDragging();
  40787. /** Callback to indicate that the user has just stopped dragging the slider.
  40788. @see Slider::Listener::sliderDragEnded
  40789. */
  40790. virtual void stoppedDragging();
  40791. /** Callback to indicate that the user has just moved the slider.
  40792. @see Slider::Listener::sliderValueChanged
  40793. */
  40794. virtual void valueChanged();
  40795. /** Subclasses can override this to convert a text string to a value.
  40796. When the user enters something into the text-entry box, this method is
  40797. called to convert it to a value.
  40798. The default routine just tries to convert it to a double.
  40799. @see getTextFromValue
  40800. */
  40801. virtual double getValueFromText (const String& text);
  40802. /** Turns the slider's current value into a text string.
  40803. Subclasses can override this to customise the formatting of the text-entry box.
  40804. The default implementation just turns the value into a string, using
  40805. a number of decimal places based on the range interval. If a suffix string
  40806. has been set using setTextValueSuffix(), this will be appended to the text.
  40807. @see getValueFromText
  40808. */
  40809. virtual const String getTextFromValue (double value);
  40810. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  40811. a string.
  40812. This is used by the default implementation of getTextFromValue(), and is just
  40813. appended to the numeric value. For more advanced formatting, you can override
  40814. getTextFromValue() and do something else.
  40815. */
  40816. void setTextValueSuffix (const String& suffix);
  40817. /** Returns the suffix that was set by setTextValueSuffix(). */
  40818. const String getTextValueSuffix() const;
  40819. /** Allows a user-defined mapping of distance along the slider to its value.
  40820. The default implementation for this performs the skewing operation that
  40821. can be set up in the setSkewFactor() method. Override it if you need
  40822. some kind of custom mapping instead, but make sure you also implement the
  40823. inverse function in valueToProportionOfLength().
  40824. @param proportion a value 0 to 1.0, indicating a distance along the slider
  40825. @returns the slider value that is represented by this position
  40826. @see valueToProportionOfLength
  40827. */
  40828. virtual double proportionOfLengthToValue (double proportion);
  40829. /** Allows a user-defined mapping of value to the position of the slider along its length.
  40830. The default implementation for this performs the skewing operation that
  40831. can be set up in the setSkewFactor() method. Override it if you need
  40832. some kind of custom mapping instead, but make sure you also implement the
  40833. inverse function in proportionOfLengthToValue().
  40834. @param value a valid slider value, between the range of values specified in
  40835. setRange()
  40836. @returns a value 0 to 1.0 indicating the distance along the slider that
  40837. represents this value
  40838. @see proportionOfLengthToValue
  40839. */
  40840. virtual double valueToProportionOfLength (double value);
  40841. /** Returns the X or Y coordinate of a value along the slider's length.
  40842. If the slider is horizontal, this will be the X coordinate of the given
  40843. value, relative to the left of the slider. If it's vertical, then this will
  40844. be the Y coordinate, relative to the top of the slider.
  40845. If the slider is rotary, this will throw an assertion and return 0. If the
  40846. value is out-of-range, it will be constrained to the length of the slider.
  40847. */
  40848. float getPositionOfValue (double value);
  40849. /** This can be overridden to allow the slider to snap to user-definable values.
  40850. If overridden, it will be called when the user tries to move the slider to
  40851. a given position, and allows a subclass to sanity-check this value, possibly
  40852. returning a different value to use instead.
  40853. @param attemptedValue the value the user is trying to enter
  40854. @param userIsDragging true if the user is dragging with the mouse; false if
  40855. they are entering the value using the text box
  40856. @returns the value to use instead
  40857. */
  40858. virtual double snapValue (double attemptedValue, bool userIsDragging);
  40859. /** This can be called to force the text box to update its contents.
  40860. (Not normally needed, as this is done automatically).
  40861. */
  40862. void updateText();
  40863. /** True if the slider moves horizontally. */
  40864. bool isHorizontal() const;
  40865. /** True if the slider moves vertically. */
  40866. bool isVertical() const;
  40867. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  40868. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40869. methods.
  40870. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40871. */
  40872. enum ColourIds
  40873. {
  40874. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  40875. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  40876. and feel class how this is used. */
  40877. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  40878. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  40879. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  40880. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  40881. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  40882. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  40883. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  40884. };
  40885. protected:
  40886. /** @internal */
  40887. void labelTextChanged (Label*);
  40888. /** @internal */
  40889. void paint (Graphics& g);
  40890. /** @internal */
  40891. void resized();
  40892. /** @internal */
  40893. void mouseDown (const MouseEvent& e);
  40894. /** @internal */
  40895. void mouseUp (const MouseEvent& e);
  40896. /** @internal */
  40897. void mouseDrag (const MouseEvent& e);
  40898. /** @internal */
  40899. void mouseDoubleClick (const MouseEvent& e);
  40900. /** @internal */
  40901. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40902. /** @internal */
  40903. void modifierKeysChanged (const ModifierKeys& modifiers);
  40904. /** @internal */
  40905. void buttonClicked (Button* button);
  40906. /** @internal */
  40907. void lookAndFeelChanged();
  40908. /** @internal */
  40909. void enablementChanged();
  40910. /** @internal */
  40911. void focusOfChildComponentChanged (FocusChangeType cause);
  40912. /** @internal */
  40913. void handleAsyncUpdate();
  40914. /** @internal */
  40915. void colourChanged();
  40916. /** @internal */
  40917. void valueChanged (Value& value);
  40918. /** Returns the best number of decimal places to use when displaying numbers.
  40919. This is calculated from the slider's interval setting.
  40920. */
  40921. int getNumDecimalPlacesToDisplay() const noexcept { return numDecimalPlaces; }
  40922. private:
  40923. ListenerList <Listener> listeners;
  40924. Value currentValue, valueMin, valueMax;
  40925. double lastCurrentValue, lastValueMin, lastValueMax;
  40926. double minimum, maximum, interval, doubleClickReturnValue;
  40927. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  40928. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  40929. int velocityModeThreshold;
  40930. float rotaryStart, rotaryEnd;
  40931. int numDecimalPlaces;
  40932. Point<int> mousePosWhenLastDragged;
  40933. int mouseDragStartX, mouseDragStartY;
  40934. int sliderRegionStart, sliderRegionSize;
  40935. int sliderBeingDragged;
  40936. int pixelsForFullDragExtent;
  40937. Rectangle<int> sliderRect;
  40938. String textSuffix;
  40939. SliderStyle style;
  40940. TextEntryBoxPosition textBoxPos;
  40941. int textBoxWidth, textBoxHeight;
  40942. IncDecButtonMode incDecButtonMode;
  40943. bool editableText : 1, doubleClickToValue : 1;
  40944. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  40945. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  40946. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  40947. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  40948. ScopedPointer<Label> valueBox;
  40949. ScopedPointer<Button> incButton, decButton;
  40950. class PopupDisplayComponent;
  40951. friend class PopupDisplayComponent;
  40952. friend class ScopedPointer <PopupDisplayComponent>;
  40953. ScopedPointer <PopupDisplayComponent> popupDisplay;
  40954. Component* parentForPopupDisplay;
  40955. float getLinearSliderPos (double value);
  40956. void restoreMouseIfHidden();
  40957. void sendDragStart();
  40958. void sendDragEnd();
  40959. double constrainedValue (double value) const;
  40960. void triggerChangeMessage (bool synchronous);
  40961. bool incDecDragDirectionIsHorizontal() const;
  40962. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  40963. };
  40964. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  40965. typedef Slider::Listener SliderListener;
  40966. #if JUCE_VC6
  40967. #undef Listener
  40968. #endif
  40969. #endif // __JUCE_SLIDER_JUCEHEADER__
  40970. /*** End of inlined file: juce_Slider.h ***/
  40971. #endif
  40972. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40973. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  40974. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40975. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40976. /**
  40977. A component that displays a strip of column headings for a table, and allows these
  40978. to be resized, dragged around, etc.
  40979. This is just the component that goes at the top of a table. You can use it
  40980. directly for custom components, or to create a simple table, use the
  40981. TableListBox class.
  40982. To use one of these, create it and use addColumn() to add all the columns that you need.
  40983. Each column must be given a unique ID number that's used to refer to it.
  40984. @see TableListBox, TableHeaderComponent::Listener
  40985. */
  40986. class JUCE_API TableHeaderComponent : public Component,
  40987. private AsyncUpdater
  40988. {
  40989. public:
  40990. /** Creates an empty table header.
  40991. */
  40992. TableHeaderComponent();
  40993. /** Destructor. */
  40994. ~TableHeaderComponent();
  40995. /** A combination of these flags are passed into the addColumn() method to specify
  40996. the properties of a column.
  40997. */
  40998. enum ColumnPropertyFlags
  40999. {
  41000. 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. */
  41001. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  41002. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  41003. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  41004. 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. */
  41005. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  41006. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  41007. /** This set of default flags is used as the default parameter value in addColumn(). */
  41008. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  41009. /** A quick way of combining flags for a column that's not resizable. */
  41010. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  41011. /** A quick way of combining flags for a column that's not resizable or sortable. */
  41012. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  41013. /** A quick way of combining flags for a column that's not sortable. */
  41014. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  41015. };
  41016. /** Adds a column to the table.
  41017. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  41018. registered listeners.
  41019. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  41020. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  41021. a unique ID. This is used to identify the column later on, after the user may have
  41022. changed the order that they appear in
  41023. @param width the initial width of the column, in pixels
  41024. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  41025. if the 'resizable' flag is specified for this column
  41026. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  41027. if the 'resizable' flag is specified for this column
  41028. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  41029. properties of this column
  41030. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  41031. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  41032. all columns, not just the index amongst those that are currently visible
  41033. */
  41034. void addColumn (const String& columnName,
  41035. int columnId,
  41036. int width,
  41037. int minimumWidth = 30,
  41038. int maximumWidth = -1,
  41039. int propertyFlags = defaultFlags,
  41040. int insertIndex = -1);
  41041. /** Removes a column with the given ID.
  41042. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  41043. registered listeners.
  41044. */
  41045. void removeColumn (int columnIdToRemove);
  41046. /** Deletes all columns from the table.
  41047. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  41048. registered listeners.
  41049. */
  41050. void removeAllColumns();
  41051. /** Returns the number of columns in the table.
  41052. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  41053. return the total number of columns, including hidden ones.
  41054. @see isColumnVisible
  41055. */
  41056. int getNumColumns (bool onlyCountVisibleColumns) const;
  41057. /** Returns the name for a column.
  41058. @see setColumnName
  41059. */
  41060. const String getColumnName (int columnId) const;
  41061. /** Changes the name of a column. */
  41062. void setColumnName (int columnId, const String& newName);
  41063. /** Moves a column to a different index in the table.
  41064. @param columnId the column to move
  41065. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  41066. */
  41067. void moveColumn (int columnId, int newVisibleIndex);
  41068. /** Returns the width of one of the columns.
  41069. */
  41070. int getColumnWidth (int columnId) const;
  41071. /** Changes the width of a column.
  41072. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  41073. */
  41074. void setColumnWidth (int columnId, int newWidth);
  41075. /** Shows or hides a column.
  41076. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  41077. @see isColumnVisible
  41078. */
  41079. void setColumnVisible (int columnId, bool shouldBeVisible);
  41080. /** Returns true if this column is currently visible.
  41081. @see setColumnVisible
  41082. */
  41083. bool isColumnVisible (int columnId) const;
  41084. /** Changes the column which is the sort column.
  41085. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  41086. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  41087. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  41088. @see getSortColumnId, isSortedForwards, reSortTable
  41089. */
  41090. void setSortColumnId (int columnId, bool sortForwards);
  41091. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  41092. @see setSortColumnId, isSortedForwards
  41093. */
  41094. int getSortColumnId() const;
  41095. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  41096. @see setSortColumnId
  41097. */
  41098. bool isSortedForwards() const;
  41099. /** Triggers a re-sort of the table according to the current sort-column.
  41100. If you modifiy the table's contents, you can call this to signal that the table needs
  41101. to be re-sorted.
  41102. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  41103. tableSortOrderChanged() method of any listeners).
  41104. */
  41105. void reSortTable();
  41106. /** Returns the total width of all the visible columns in the table.
  41107. */
  41108. int getTotalWidth() const;
  41109. /** Returns the index of a given column.
  41110. If there's no such column ID, this will return -1.
  41111. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  41112. otherwise it'll return the index amongst all the columns, including any hidden ones.
  41113. */
  41114. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  41115. /** Returns the ID of the column at a given index.
  41116. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  41117. otherwise it'll count it amongst all the columns, including any hidden ones.
  41118. If the index is out-of-range, it'll return 0.
  41119. */
  41120. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  41121. /** Returns the rectangle containing of one of the columns.
  41122. The index is an index from 0 to the number of columns that are currently visible (hidden
  41123. ones are not counted). It returns a rectangle showing the position of the column relative
  41124. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  41125. */
  41126. const Rectangle<int> getColumnPosition (int index) const;
  41127. /** Finds the column ID at a given x-position in the component.
  41128. If there is a column at this point this returns its ID, or if not, it will return 0.
  41129. */
  41130. int getColumnIdAtX (int xToFind) const;
  41131. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  41132. entire width of the component.
  41133. By default this is disabled. Turning it on also means that when resizing a column, those
  41134. on the right will be squashed to fit.
  41135. */
  41136. void setStretchToFitActive (bool shouldStretchToFit);
  41137. /** Returns true if stretch-to-fit has been enabled.
  41138. @see setStretchToFitActive
  41139. */
  41140. bool isStretchToFitActive() const;
  41141. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  41142. specified width, keeping their relative proportions the same.
  41143. If the minimum widths of the columns are too wide to fit into this space, it may
  41144. actually end up wider.
  41145. */
  41146. void resizeAllColumnsToFit (int targetTotalWidth);
  41147. /** Enables or disables the pop-up menu.
  41148. The default menu allows the user to show or hide columns. You can add custom
  41149. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  41150. By default the menu is enabled.
  41151. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  41152. */
  41153. void setPopupMenuActive (bool hasMenu);
  41154. /** Returns true if the pop-up menu is enabled.
  41155. @see setPopupMenuActive
  41156. */
  41157. bool isPopupMenuActive() const;
  41158. /** Returns a string that encapsulates the table's current layout.
  41159. This can be restored later using restoreFromString(). It saves the order of
  41160. the columns, the currently-sorted column, and the widths.
  41161. @see restoreFromString
  41162. */
  41163. const String toString() const;
  41164. /** Restores the state of the table, based on a string previously created with
  41165. toString().
  41166. @see toString
  41167. */
  41168. void restoreFromString (const String& storedVersion);
  41169. /**
  41170. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  41171. You can register one of these objects for table events using TableHeaderComponent::addListener()
  41172. and TableHeaderComponent::removeListener().
  41173. @see TableHeaderComponent
  41174. */
  41175. class JUCE_API Listener
  41176. {
  41177. public:
  41178. Listener() {}
  41179. /** Destructor. */
  41180. virtual ~Listener() {}
  41181. /** This is called when some of the table's columns are added, removed, hidden,
  41182. or rearranged.
  41183. */
  41184. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  41185. /** This is called when one or more of the table's columns are resized.
  41186. */
  41187. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  41188. /** This is called when the column by which the table should be sorted is changed.
  41189. */
  41190. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  41191. /** This is called when the user begins or ends dragging one of the columns around.
  41192. When the user starts dragging a column, this is called with the ID of that
  41193. column. When they finish dragging, it is called again with 0 as the ID.
  41194. */
  41195. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  41196. int columnIdNowBeingDragged);
  41197. };
  41198. /** Adds a listener to be informed about things that happen to the header. */
  41199. void addListener (Listener* newListener);
  41200. /** Removes a previously-registered listener. */
  41201. void removeListener (Listener* listenerToRemove);
  41202. /** This can be overridden to handle a mouse-click on one of the column headers.
  41203. The default implementation will use this click to call getSortColumnId() and
  41204. change the sort order.
  41205. */
  41206. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  41207. /** This can be overridden to add custom items to the pop-up menu.
  41208. If you override this, you should call the superclass's method to add its
  41209. column show/hide items, if you want them on the menu as well.
  41210. Then to handle the result, override reactToMenuItem().
  41211. @see reactToMenuItem
  41212. */
  41213. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  41214. /** Override this to handle any custom items that you have added to the
  41215. pop-up menu with an addMenuItems() override.
  41216. If the menuReturnId isn't one of your own custom menu items, you'll need to
  41217. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  41218. handle the items that it had added.
  41219. @see addMenuItems
  41220. */
  41221. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  41222. /** @internal */
  41223. void paint (Graphics& g);
  41224. /** @internal */
  41225. void resized();
  41226. /** @internal */
  41227. void mouseMove (const MouseEvent&);
  41228. /** @internal */
  41229. void mouseEnter (const MouseEvent&);
  41230. /** @internal */
  41231. void mouseExit (const MouseEvent&);
  41232. /** @internal */
  41233. void mouseDown (const MouseEvent&);
  41234. /** @internal */
  41235. void mouseDrag (const MouseEvent&);
  41236. /** @internal */
  41237. void mouseUp (const MouseEvent&);
  41238. /** @internal */
  41239. const MouseCursor getMouseCursor();
  41240. /** Can be overridden for more control over the pop-up menu behaviour. */
  41241. virtual void showColumnChooserMenu (int columnIdClicked);
  41242. private:
  41243. struct ColumnInfo
  41244. {
  41245. String name;
  41246. int id, propertyFlags, width, minimumWidth, maximumWidth;
  41247. double lastDeliberateWidth;
  41248. bool isVisible() const;
  41249. };
  41250. OwnedArray <ColumnInfo> columns;
  41251. Array <Listener*> listeners;
  41252. ScopedPointer <Component> dragOverlayComp;
  41253. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  41254. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  41255. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  41256. ColumnInfo* getInfoForId (int columnId) const;
  41257. int visibleIndexToTotalIndex (int visibleIndex) const;
  41258. void sendColumnsChanged();
  41259. void handleAsyncUpdate();
  41260. void beginDrag (const MouseEvent&);
  41261. void endDrag (int finalIndex);
  41262. int getResizeDraggerAt (int mouseX) const;
  41263. void updateColumnUnderMouse (int x, int y);
  41264. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  41265. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  41266. };
  41267. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  41268. typedef TableHeaderComponent::Listener TableHeaderListener;
  41269. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41270. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  41271. #endif
  41272. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  41273. /*** Start of inlined file: juce_TableListBox.h ***/
  41274. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  41275. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  41276. /**
  41277. One of these is used by a TableListBox as the data model for the table's contents.
  41278. The virtual methods that you override in this class take care of drawing the
  41279. table cells, and reacting to events.
  41280. @see TableListBox
  41281. */
  41282. class JUCE_API TableListBoxModel
  41283. {
  41284. public:
  41285. TableListBoxModel() {}
  41286. /** Destructor. */
  41287. virtual ~TableListBoxModel() {}
  41288. /** This must return the number of rows currently in the table.
  41289. If the number of rows changes, you must call TableListBox::updateContent() to
  41290. cause it to refresh the list.
  41291. */
  41292. virtual int getNumRows() = 0;
  41293. /** This must draw the background behind one of the rows in the table.
  41294. The graphics context has its origin at the row's top-left, and your method
  41295. should fill the area specified by the width and height parameters.
  41296. */
  41297. virtual void paintRowBackground (Graphics& g,
  41298. int rowNumber,
  41299. int width, int height,
  41300. bool rowIsSelected) = 0;
  41301. /** This must draw one of the cells.
  41302. The graphics context's origin will already be set to the top-left of the cell,
  41303. whose size is specified by (width, height).
  41304. */
  41305. virtual void paintCell (Graphics& g,
  41306. int rowNumber,
  41307. int columnId,
  41308. int width, int height,
  41309. bool rowIsSelected) = 0;
  41310. /** This is used to create or update a custom component to go in a cell.
  41311. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  41312. and handle mouse clicks with cellClicked().
  41313. This method will be called whenever a custom component might need to be updated - e.g.
  41314. when the table is changed, or TableListBox::updateContent() is called.
  41315. If you don't need a custom component for the specified cell, then return 0.
  41316. If you do want a custom component, and the existingComponentToUpdate is null, then
  41317. this method must create a new component suitable for the cell, and return it.
  41318. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  41319. by this method. In this case, the method must either update it to make sure it's correctly representing
  41320. the given cell (which may be different from the one that the component was created for), or it can
  41321. delete this component and return a new one.
  41322. */
  41323. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  41324. Component* existingComponentToUpdate);
  41325. /** This callback is made when the user clicks on one of the cells in the table.
  41326. The mouse event's coordinates will be relative to the entire table row.
  41327. @see cellDoubleClicked, backgroundClicked
  41328. */
  41329. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  41330. /** This callback is made when the user clicks on one of the cells in the table.
  41331. The mouse event's coordinates will be relative to the entire table row.
  41332. @see cellClicked, backgroundClicked
  41333. */
  41334. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  41335. /** This can be overridden to react to the user double-clicking on a part of the list where
  41336. there are no rows.
  41337. @see cellClicked
  41338. */
  41339. virtual void backgroundClicked();
  41340. /** This callback is made when the table's sort order is changed.
  41341. This could be because the user has clicked a column header, or because the
  41342. TableHeaderComponent::setSortColumnId() method was called.
  41343. If you implement this, your method should re-sort the table using the given
  41344. column as the key.
  41345. */
  41346. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  41347. /** Returns the best width for one of the columns.
  41348. If you implement this method, you should measure the width of all the items
  41349. in this column, and return the best size.
  41350. Returning 0 means that the column shouldn't be changed.
  41351. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  41352. */
  41353. virtual int getColumnAutoSizeWidth (int columnId);
  41354. /** Returns a tooltip for a particular cell in the table.
  41355. */
  41356. virtual const String getCellTooltip (int rowNumber, int columnId);
  41357. /** Override this to be informed when rows are selected or deselected.
  41358. @see ListBox::selectedRowsChanged()
  41359. */
  41360. virtual void selectedRowsChanged (int lastRowSelected);
  41361. /** Override this to be informed when the delete key is pressed.
  41362. @see ListBox::deleteKeyPressed()
  41363. */
  41364. virtual void deleteKeyPressed (int lastRowSelected);
  41365. /** Override this to be informed when the return key is pressed.
  41366. @see ListBox::returnKeyPressed()
  41367. */
  41368. virtual void returnKeyPressed (int lastRowSelected);
  41369. /** Override this to be informed when the list is scrolled.
  41370. This might be caused by the user moving the scrollbar, or by programmatic changes
  41371. to the list position.
  41372. */
  41373. virtual void listWasScrolled();
  41374. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  41375. If this returns a non-null variant then when the user drags a row, the table will try to
  41376. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  41377. drag-and-drop operation, using this string as the source description, and the listbox
  41378. itself as the source component.
  41379. @see getDragSourceCustomData, DragAndDropContainer::startDragging
  41380. */
  41381. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  41382. };
  41383. /**
  41384. A table of cells, using a TableHeaderComponent as its header.
  41385. This component makes it easy to create a table by providing a TableListBoxModel as
  41386. the data source.
  41387. @see TableListBoxModel, TableHeaderComponent
  41388. */
  41389. class JUCE_API TableListBox : public ListBox,
  41390. private ListBoxModel,
  41391. private TableHeaderComponent::Listener
  41392. {
  41393. public:
  41394. /** Creates a TableListBox.
  41395. The model pointer passed-in can be null, in which case you can set it later
  41396. with setModel().
  41397. */
  41398. TableListBox (const String& componentName = String::empty,
  41399. TableListBoxModel* model = 0);
  41400. /** Destructor. */
  41401. ~TableListBox();
  41402. /** Changes the TableListBoxModel that is being used for this table.
  41403. */
  41404. void setModel (TableListBoxModel* newModel);
  41405. /** Returns the model currently in use. */
  41406. TableListBoxModel* getModel() const { return model; }
  41407. /** Returns the header component being used in this table. */
  41408. TableHeaderComponent& getHeader() const { return *header; }
  41409. /** Sets the header component to use for the table.
  41410. The table will take ownership of the component that you pass in, and will delete it
  41411. when it's no longer needed.
  41412. */
  41413. void setHeader (TableHeaderComponent* newHeader);
  41414. /** Changes the height of the table header component.
  41415. @see getHeaderHeight
  41416. */
  41417. void setHeaderHeight (int newHeight);
  41418. /** Returns the height of the table header.
  41419. @see setHeaderHeight
  41420. */
  41421. int getHeaderHeight() const;
  41422. /** Resizes a column to fit its contents.
  41423. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  41424. and applies that to the column.
  41425. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  41426. */
  41427. void autoSizeColumn (int columnId);
  41428. /** Calls autoSizeColumn() for all columns in the table. */
  41429. void autoSizeAllColumns();
  41430. /** Enables or disables the auto size options on the popup menu.
  41431. By default, these are enabled.
  41432. */
  41433. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  41434. /** True if the auto-size options should be shown on the menu.
  41435. @see setAutoSizeMenuOptionsShown
  41436. */
  41437. bool isAutoSizeMenuOptionShown() const;
  41438. /** Returns the position of one of the cells in the table.
  41439. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  41440. the table component's top-left. The row number isn't checked to see if it's
  41441. in-range, but the column ID must exist or this will return an empty rectangle.
  41442. If relativeToComponentTopLeft is false, the co-ords are relative to the
  41443. top-left of the table's top-left cell.
  41444. */
  41445. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  41446. bool relativeToComponentTopLeft) const;
  41447. /** Returns the component that currently represents a given cell.
  41448. If the component for this cell is off-screen or if the position is out-of-range,
  41449. this may return 0.
  41450. @see getCellPosition
  41451. */
  41452. Component* getCellComponent (int columnId, int rowNumber) const;
  41453. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  41454. @see ListBox::scrollToEnsureRowIsOnscreen
  41455. */
  41456. void scrollToEnsureColumnIsOnscreen (int columnId);
  41457. /** @internal */
  41458. int getNumRows();
  41459. /** @internal */
  41460. void paintListBoxItem (int, Graphics&, int, int, bool);
  41461. /** @internal */
  41462. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  41463. /** @internal */
  41464. void selectedRowsChanged (int lastRowSelected);
  41465. /** @internal */
  41466. void deleteKeyPressed (int currentSelectedRow);
  41467. /** @internal */
  41468. void returnKeyPressed (int currentSelectedRow);
  41469. /** @internal */
  41470. void backgroundClicked();
  41471. /** @internal */
  41472. void listWasScrolled();
  41473. /** @internal */
  41474. void tableColumnsChanged (TableHeaderComponent*);
  41475. /** @internal */
  41476. void tableColumnsResized (TableHeaderComponent*);
  41477. /** @internal */
  41478. void tableSortOrderChanged (TableHeaderComponent*);
  41479. /** @internal */
  41480. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  41481. /** @internal */
  41482. void resized();
  41483. private:
  41484. TableHeaderComponent* header;
  41485. TableListBoxModel* model;
  41486. int columnIdNowBeingDragged;
  41487. bool autoSizeOptionsShown;
  41488. void updateColumnComponents() const;
  41489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  41490. };
  41491. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  41492. /*** End of inlined file: juce_TableListBox.h ***/
  41493. #endif
  41494. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  41495. #endif
  41496. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  41497. #endif
  41498. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  41499. #endif
  41500. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41501. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  41502. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41503. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41504. /**
  41505. A factory object which can create ToolbarItemComponent objects.
  41506. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  41507. that it can create.
  41508. Each type of item is identified by a unique ID, and multiple instances of an
  41509. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  41510. bars).
  41511. @see Toolbar, ToolbarItemComponent, ToolbarButton
  41512. */
  41513. class JUCE_API ToolbarItemFactory
  41514. {
  41515. public:
  41516. ToolbarItemFactory();
  41517. /** Destructor. */
  41518. virtual ~ToolbarItemFactory();
  41519. /** A set of reserved item ID values, used for the built-in item types.
  41520. */
  41521. enum SpecialItemIds
  41522. {
  41523. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  41524. can be placed between sets of items to break them into groups. */
  41525. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  41526. items.*/
  41527. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  41528. either side of it, filling any available space. */
  41529. };
  41530. /** Must return a list of the IDs for all the item types that this factory can create.
  41531. The ids should be added to the array that is passed-in.
  41532. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  41533. and the predefined IDs in the SpecialItemIds enum.
  41534. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  41535. to this list if you want your toolbar to be able to contain those items.
  41536. The list returned here is used by the ToolbarItemPalette class to obtain its list
  41537. of available items, and their order on the palette will reflect the order in which
  41538. they appear on this list.
  41539. @see ToolbarItemPalette
  41540. */
  41541. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  41542. /** Must return the set of items that should be added to a toolbar as its default set.
  41543. This method is used by Toolbar::addDefaultItems() to determine which items to
  41544. create.
  41545. The items that your method adds to the array that is passed-in will be added to the
  41546. toolbar in the same order. Items can appear in the list more than once.
  41547. */
  41548. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  41549. /** Must create an instance of one of the items that the factory lists in its
  41550. getAllToolbarItemIds() method.
  41551. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  41552. method, except for the built-in item types from the SpecialItemIds enum, which
  41553. are created internally by the toolbar code.
  41554. Try not to keep a pointer to the object that is returned, as it will be deleted
  41555. automatically by the toolbar, and remember that multiple instances of the same
  41556. item type are likely to exist at the same time.
  41557. */
  41558. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  41559. };
  41560. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41561. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  41562. #endif
  41563. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41564. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  41565. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41566. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41567. /**
  41568. A component containing a list of toolbar items, which the user can drag onto
  41569. a toolbar to add them.
  41570. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  41571. which automatically shows one of these in a dialog box with lots of extra controls.
  41572. @see Toolbar
  41573. */
  41574. class JUCE_API ToolbarItemPalette : public Component,
  41575. public DragAndDropContainer
  41576. {
  41577. public:
  41578. /** Creates a palette of items for a given factory, with the aim of adding them
  41579. to the specified toolbar.
  41580. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  41581. set of items that are shown in this palette.
  41582. The toolbar and factory must not be deleted while this object exists.
  41583. */
  41584. ToolbarItemPalette (ToolbarItemFactory& factory,
  41585. Toolbar* toolbar);
  41586. /** Destructor. */
  41587. ~ToolbarItemPalette();
  41588. /** @internal */
  41589. void resized();
  41590. private:
  41591. ToolbarItemFactory& factory;
  41592. Toolbar* toolbar;
  41593. Viewport viewport;
  41594. OwnedArray <ToolbarItemComponent> items;
  41595. friend class Toolbar;
  41596. void replaceComponent (ToolbarItemComponent* comp);
  41597. void addComponent (int itemId, int index);
  41598. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  41599. };
  41600. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41601. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  41602. #endif
  41603. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41604. /*** Start of inlined file: juce_TreeView.h ***/
  41605. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41606. #define __JUCE_TREEVIEW_JUCEHEADER__
  41607. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  41608. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41609. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41610. /**
  41611. Components derived from this class can have files dropped onto them by an external application.
  41612. @see DragAndDropContainer
  41613. */
  41614. class JUCE_API FileDragAndDropTarget
  41615. {
  41616. public:
  41617. /** Destructor. */
  41618. virtual ~FileDragAndDropTarget() {}
  41619. /** Callback to check whether this target is interested in the set of files being offered.
  41620. Note that this will be called repeatedly when the user is dragging the mouse around over your
  41621. component, so don't do anything time-consuming in here, like opening the files to have a look
  41622. inside them!
  41623. @param files the set of (absolute) pathnames of the files that the user is dragging
  41624. @returns true if this component wants to receive the other callbacks regarging this
  41625. type of object; if it returns false, no other callbacks will be made.
  41626. */
  41627. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  41628. /** Callback to indicate that some files are being dragged over this component.
  41629. This gets called when the user moves the mouse into this component while dragging.
  41630. Use this callback as a trigger to make your component repaint itself to give the
  41631. user feedback about whether the files can be dropped here or not.
  41632. @param files the set of (absolute) pathnames of the files that the user is dragging
  41633. @param x the mouse x position, relative to this component
  41634. @param y the mouse y position, relative to this component
  41635. */
  41636. virtual void fileDragEnter (const StringArray& files, int x, int y);
  41637. /** Callback to indicate that the user is dragging some files over this component.
  41638. This gets called when the user moves the mouse over this component while dragging.
  41639. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  41640. this lets you know what happens in-between.
  41641. @param files the set of (absolute) pathnames of the files that the user is dragging
  41642. @param x the mouse x position, relative to this component
  41643. @param y the mouse y position, relative to this component
  41644. */
  41645. virtual void fileDragMove (const StringArray& files, int x, int y);
  41646. /** Callback to indicate that the mouse has moved away from this component.
  41647. This gets called when the user moves the mouse out of this component while dragging
  41648. the files.
  41649. If you've used fileDragEnter() to repaint your component and give feedback, use this
  41650. as a signal to repaint it in its normal state.
  41651. @param files the set of (absolute) pathnames of the files that the user is dragging
  41652. */
  41653. virtual void fileDragExit (const StringArray& files);
  41654. /** Callback to indicate that the user has dropped the files onto this component.
  41655. When the user drops the files, this get called, and you can use the files in whatever
  41656. way is appropriate.
  41657. Note that after this is called, the fileDragExit method may not be called, so you should
  41658. clean up in here if there's anything you need to do when the drag finishes.
  41659. @param files the set of (absolute) pathnames of the files that the user is dragging
  41660. @param x the mouse x position, relative to this component
  41661. @param y the mouse y position, relative to this component
  41662. */
  41663. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  41664. };
  41665. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41666. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  41667. class TreeView;
  41668. /**
  41669. An item in a treeview.
  41670. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  41671. own sub-items.
  41672. To implement an item that contains sub-items, override the itemOpennessChanged()
  41673. method so that when it is opened, it adds the new sub-items to itself using the
  41674. addSubItem method. Depending on the nature of the item it might choose to only
  41675. do this the first time it's opened, or it might want to refresh itself each time.
  41676. It also has the option of deleting its sub-items when it is closed, or leaving them
  41677. in place.
  41678. */
  41679. class JUCE_API TreeViewItem
  41680. {
  41681. public:
  41682. /** Constructor. */
  41683. TreeViewItem();
  41684. /** Destructor. */
  41685. virtual ~TreeViewItem();
  41686. /** Returns the number of sub-items that have been added to this item.
  41687. Note that this doesn't mean much if the node isn't open.
  41688. @see getSubItem, mightContainSubItems, addSubItem
  41689. */
  41690. int getNumSubItems() const noexcept;
  41691. /** Returns one of the item's sub-items.
  41692. Remember that the object returned might get deleted at any time when its parent
  41693. item is closed or refreshed, depending on the nature of the items you're using.
  41694. @see getNumSubItems
  41695. */
  41696. TreeViewItem* getSubItem (int index) const noexcept;
  41697. /** Removes any sub-items. */
  41698. void clearSubItems();
  41699. /** Adds a sub-item.
  41700. @param newItem the object to add to the item's sub-item list. Once added, these can be
  41701. found using getSubItem(). When the items are later removed with
  41702. removeSubItem() (or when this item is deleted), they will be deleted.
  41703. @param insertPosition the index which the new item should have when it's added. If this
  41704. value is less than 0, the item will be added to the end of the list.
  41705. */
  41706. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  41707. /** Removes one of the sub-items.
  41708. @param index the item to remove
  41709. @param deleteItem if true, the item that is removed will also be deleted.
  41710. */
  41711. void removeSubItem (int index, bool deleteItem = true);
  41712. /** Returns the TreeView to which this item belongs. */
  41713. TreeView* getOwnerView() const noexcept { return ownerView; }
  41714. /** Returns the item within which this item is contained. */
  41715. TreeViewItem* getParentItem() const noexcept { return parentItem; }
  41716. /** True if this item is currently open in the treeview. */
  41717. bool isOpen() const noexcept;
  41718. /** Opens or closes the item.
  41719. When opened or closed, the item's itemOpennessChanged() method will be called,
  41720. and a subclass should use this callback to create and add any sub-items that
  41721. it needs to.
  41722. @see itemOpennessChanged, mightContainSubItems
  41723. */
  41724. void setOpen (bool shouldBeOpen);
  41725. /** True if this item is currently selected.
  41726. Use this when painting the node, to decide whether to draw it as selected or not.
  41727. */
  41728. bool isSelected() const noexcept;
  41729. /** Selects or deselects the item.
  41730. This will cause a callback to itemSelectionChanged()
  41731. */
  41732. void setSelected (bool shouldBeSelected,
  41733. bool deselectOtherItemsFirst);
  41734. /** Returns the rectangle that this item occupies.
  41735. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  41736. top-left of the TreeView comp, so this will depend on the scroll-position of
  41737. the tree. If false, it is relative to the top-left of the topmost item in the
  41738. tree (so this would be unaffected by scrolling the view).
  41739. */
  41740. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const noexcept;
  41741. /** Sends a signal to the treeview to make it refresh itself.
  41742. Call this if your items have changed and you want the tree to update to reflect
  41743. this.
  41744. */
  41745. void treeHasChanged() const noexcept;
  41746. /** Sends a repaint message to redraw just this item.
  41747. Note that you should only call this if you want to repaint a superficial change. If
  41748. you're altering the tree's nodes, you should instead call treeHasChanged().
  41749. */
  41750. void repaintItem() const;
  41751. /** Returns the row number of this item in the tree.
  41752. The row number of an item will change according to which items are open.
  41753. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  41754. */
  41755. int getRowNumberInTree() const noexcept;
  41756. /** Returns true if all the item's parent nodes are open.
  41757. This is useful to check whether the item might actually be visible or not.
  41758. */
  41759. bool areAllParentsOpen() const noexcept;
  41760. /** Changes whether lines are drawn to connect any sub-items to this item.
  41761. By default, line-drawing is turned on.
  41762. */
  41763. void setLinesDrawnForSubItems (bool shouldDrawLines) noexcept;
  41764. /** Tells the tree whether this item can potentially be opened.
  41765. If your item could contain sub-items, this should return true; if it returns
  41766. false then the tree will not try to open the item. This determines whether or
  41767. not the item will be drawn with a 'plus' button next to it.
  41768. */
  41769. virtual bool mightContainSubItems() = 0;
  41770. /** Returns a string to uniquely identify this item.
  41771. If you're planning on using the TreeView::getOpennessState() method, then
  41772. these strings will be used to identify which nodes are open. The string
  41773. should be unique amongst the item's sibling items, but it's ok for there
  41774. to be duplicates at other levels of the tree.
  41775. If you're not going to store the state, then it's ok not to bother implementing
  41776. this method.
  41777. */
  41778. virtual const String getUniqueName() const;
  41779. /** Called when an item is opened or closed.
  41780. When setOpen() is called and the item has specified that it might
  41781. have sub-items with the mightContainSubItems() method, this method
  41782. is called to let the item create or manage its sub-items.
  41783. So when this is called with isNowOpen set to true (i.e. when the item is being
  41784. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  41785. refresh its sub-item list.
  41786. When this is called with isNowOpen set to false, the subclass might want
  41787. to use clearSubItems() to save on space, or it might choose to leave them,
  41788. depending on the nature of the tree.
  41789. You could also use this callback as a trigger to start a background process
  41790. which asynchronously creates sub-items and adds them, if that's more
  41791. appropriate for the task in hand.
  41792. @see mightContainSubItems
  41793. */
  41794. virtual void itemOpennessChanged (bool isNowOpen);
  41795. /** Must return the width required by this item.
  41796. If your item needs to have a particular width in pixels, return that value; if
  41797. you'd rather have it just fill whatever space is available in the treeview,
  41798. return -1.
  41799. If all your items return -1, no horizontal scrollbar will be shown, but if any
  41800. items have fixed widths and extend beyond the width of the treeview, a
  41801. scrollbar will appear.
  41802. Each item can be a different width, but if they change width, you should call
  41803. treeHasChanged() to update the tree.
  41804. */
  41805. virtual int getItemWidth() const { return -1; }
  41806. /** Must return the height required by this item.
  41807. This is the height in pixels that the item will take up. Items in the tree
  41808. can be different heights, but if they change height, you should call
  41809. treeHasChanged() to update the tree.
  41810. */
  41811. virtual int getItemHeight() const { return 20; }
  41812. /** You can override this method to return false if you don't want to allow the
  41813. user to select this item.
  41814. */
  41815. virtual bool canBeSelected() const { return true; }
  41816. /** Creates a component that will be used to represent this item.
  41817. You don't have to implement this method - if it returns 0 then no component
  41818. will be used for the item, and you can just draw it using the paintItem()
  41819. callback. But if you do return a component, it will be positioned in the
  41820. treeview so that it can be used to represent this item.
  41821. The component returned will be managed by the treeview, so always return
  41822. a new component, and don't keep a reference to it, as the treeview will
  41823. delete it later when it goes off the screen or is no longer needed. Also
  41824. bear in mind that if the component keeps a reference to the item that
  41825. created it, that item could be deleted before the component. Its position
  41826. and size will be completely managed by the tree, so don't attempt to move it
  41827. around.
  41828. Something you may want to do with your component is to give it a pointer to
  41829. the TreeView that created it. This is perfectly safe, and there's no danger
  41830. of it becoming a dangling pointer because the TreeView will always delete
  41831. the component before it is itself deleted.
  41832. As long as you stick to these rules you can return whatever kind of
  41833. component you like. It's most useful if you're doing things like drag-and-drop
  41834. of items, or want to use a Label component to edit item names, etc.
  41835. */
  41836. virtual Component* createItemComponent() { return nullptr; }
  41837. /** Draws the item's contents.
  41838. You can choose to either implement this method and draw each item, or you
  41839. can use createItemComponent() to create a component that will represent the
  41840. item.
  41841. If all you need in your tree is to be able to draw the items and detect when
  41842. the user selects or double-clicks one of them, it's probably enough to
  41843. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  41844. complicated interactions, you may need to use createItemComponent() instead.
  41845. @param g the graphics context to draw into
  41846. @param width the width of the area available for drawing
  41847. @param height the height of the area available for drawing
  41848. */
  41849. virtual void paintItem (Graphics& g, int width, int height);
  41850. /** Draws the item's open/close button.
  41851. If you don't implement this method, the default behaviour is to
  41852. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  41853. it for custom effects.
  41854. */
  41855. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  41856. /** Called when the user clicks on this item.
  41857. If you're using createItemComponent() to create a custom component for the
  41858. item, the mouse-clicks might not make it through to the treeview, but this
  41859. is how you find out about clicks when just drawing each item individually.
  41860. The associated mouse-event details are passed in, so you can find out about
  41861. which button, where it was, etc.
  41862. @see itemDoubleClicked
  41863. */
  41864. virtual void itemClicked (const MouseEvent& e);
  41865. /** Called when the user double-clicks on this item.
  41866. If you're using createItemComponent() to create a custom component for the
  41867. item, the mouse-clicks might not make it through to the treeview, but this
  41868. is how you find out about clicks when just drawing each item individually.
  41869. The associated mouse-event details are passed in, so you can find out about
  41870. which button, where it was, etc.
  41871. If not overridden, the base class method here will open or close the item as
  41872. if the 'plus' button had been clicked.
  41873. @see itemClicked
  41874. */
  41875. virtual void itemDoubleClicked (const MouseEvent& e);
  41876. /** Called when the item is selected or deselected.
  41877. Use this if you want to do something special when the item's selectedness
  41878. changes. By default it'll get repainted when this happens.
  41879. */
  41880. virtual void itemSelectionChanged (bool isNowSelected);
  41881. /** The item can return a tool tip string here if it wants to.
  41882. @see TooltipClient
  41883. */
  41884. virtual const String getTooltip();
  41885. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  41886. If this returns a non-null variant then when the user drags an item, the treeview will
  41887. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  41888. a drag-and-drop operation, using this string as the source description, with the treeview
  41889. itself as the source component.
  41890. If you need more complex drag-and-drop behaviour, you can use custom components for
  41891. the items, and use those to trigger the drag.
  41892. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  41893. isInterestedInFileDrag(), etc.
  41894. @see DragAndDropContainer::startDragging
  41895. */
  41896. virtual const var getDragSourceDescription();
  41897. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  41898. method and return true.
  41899. If you return true and allow some files to be dropped, you'll also need to implement the
  41900. filesDropped() method to do something with them.
  41901. Note that this will be called often, so make your implementation very quick! There's
  41902. certainly no time to try opening the files and having a think about what's inside them!
  41903. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  41904. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  41905. */
  41906. virtual bool isInterestedInFileDrag (const StringArray& files);
  41907. /** When files are dropped into this item, this callback is invoked.
  41908. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  41909. The insertIndex value indicates where in the list of sub-items the files were dropped.
  41910. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  41911. */
  41912. virtual void filesDropped (const StringArray& files, int insertIndex);
  41913. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  41914. If you implement this method, you'll also need to implement itemDropped() in order to handle
  41915. the items when they are dropped.
  41916. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  41917. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  41918. */
  41919. virtual bool isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails);
  41920. /** When a things are dropped into this item, this callback is invoked.
  41921. For this to work, you need to have also implemented isInterestedInDragSource().
  41922. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  41923. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  41924. */
  41925. virtual void itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex);
  41926. /** Sets a flag to indicate that the item wants to be allowed
  41927. to draw all the way across to the left edge of the treeview.
  41928. By default this is false, which means that when the paintItem()
  41929. method is called, its graphics context is clipped to only allow
  41930. drawing within the item's rectangle. If this flag is set to true,
  41931. then the graphics context isn't clipped on its left side, so it
  41932. can draw all the way across to the left margin. Note that the
  41933. context will still have its origin in the same place though, so
  41934. the coordinates of anything to its left will be negative. It's
  41935. mostly useful if you want to draw a wider bar behind the
  41936. highlighted item.
  41937. */
  41938. void setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept;
  41939. /** Saves the current state of open/closed nodes so it can be restored later.
  41940. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  41941. and records it as XML. To identify node objects it uses the
  41942. TreeViewItem::getUniqueName() method to create named paths. This
  41943. means that the same state of open/closed nodes can be restored to a
  41944. completely different instance of the tree, as long as it contains nodes
  41945. whose unique names are the same.
  41946. You'd normally want to use TreeView::getOpennessState() rather than call it
  41947. for a specific item, but this can be handy if you need to briefly save the state
  41948. for a section of the tree.
  41949. The caller is responsible for deleting the object that is returned.
  41950. @see TreeView::getOpennessState, restoreOpennessState
  41951. */
  41952. XmlElement* getOpennessState() const noexcept;
  41953. /** Restores the openness of this item and all its sub-items from a saved state.
  41954. See TreeView::restoreOpennessState for more details.
  41955. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  41956. for a specific item, but this can be handy if you need to briefly save the state
  41957. for a section of the tree.
  41958. @see TreeView::restoreOpennessState, getOpennessState
  41959. */
  41960. void restoreOpennessState (const XmlElement& xml) noexcept;
  41961. /** Returns the index of this item in its parent's sub-items. */
  41962. int getIndexInParent() const noexcept;
  41963. /** Returns true if this item is the last of its parent's sub-itens. */
  41964. bool isLastOfSiblings() const noexcept;
  41965. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  41966. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  41967. The string takes the form of a path, constructed from the getUniqueName() of this
  41968. item and all its parents, so these must all be correctly implemented for it to work.
  41969. @see TreeView::findItemFromIdentifierString, getUniqueName
  41970. */
  41971. String getItemIdentifierString() const;
  41972. /**
  41973. This handy class takes a copy of a TreeViewItem's openness when you create it,
  41974. and restores that openness state when its destructor is called.
  41975. This can very handy when you're refreshing sub-items - e.g.
  41976. @code
  41977. void MyTreeViewItem::updateChildItems()
  41978. {
  41979. OpennessRestorer openness (*this); // saves the openness state here..
  41980. clearSubItems();
  41981. // add a bunch of sub-items here which may or may not be the same as the ones that
  41982. // were previously there
  41983. addSubItem (...
  41984. // ..and at this point, the old openness is restored, so any items that haven't
  41985. // changed will have their old openness retained.
  41986. }
  41987. @endcode
  41988. */
  41989. class OpennessRestorer
  41990. {
  41991. public:
  41992. OpennessRestorer (TreeViewItem& treeViewItem);
  41993. ~OpennessRestorer();
  41994. private:
  41995. TreeViewItem& treeViewItem;
  41996. ScopedPointer <XmlElement> oldOpenness;
  41997. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  41998. };
  41999. private:
  42000. TreeView* ownerView;
  42001. TreeViewItem* parentItem;
  42002. OwnedArray <TreeViewItem> subItems;
  42003. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  42004. int uid;
  42005. bool selected : 1;
  42006. bool redrawNeeded : 1;
  42007. bool drawLinesInside : 1;
  42008. bool drawsInLeftMargin : 1;
  42009. unsigned int openness : 2;
  42010. friend class TreeView;
  42011. friend class TreeViewContentComponent;
  42012. void updatePositions (int newY);
  42013. int getIndentX() const noexcept;
  42014. void setOwnerView (TreeView*) noexcept;
  42015. void paintRecursively (Graphics&, int width);
  42016. TreeViewItem* getTopLevelItem() noexcept;
  42017. TreeViewItem* findItemRecursively (int y) noexcept;
  42018. TreeViewItem* getDeepestOpenParentItem() noexcept;
  42019. int getNumRows() const noexcept;
  42020. TreeViewItem* getItemOnRow (int index) noexcept;
  42021. void deselectAllRecursively();
  42022. int countSelectedItemsRecursively (int depth) const noexcept;
  42023. TreeViewItem* getSelectedItemWithIndex (int index) noexcept;
  42024. TreeViewItem* getNextVisibleItem (bool recurse) const noexcept;
  42025. TreeViewItem* findItemFromIdentifierString (const String&);
  42026. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  42027. // The parameters for these methods have changed - please update your code!
  42028. virtual void isInterestedInDragSource (const String&, Component*) {}
  42029. virtual int itemDropped (const String&, Component*, int) { return 0; }
  42030. #endif
  42031. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  42032. };
  42033. /**
  42034. A tree-view component.
  42035. Use one of these to hold and display a structure of TreeViewItem objects.
  42036. */
  42037. class JUCE_API TreeView : public Component,
  42038. public SettableTooltipClient,
  42039. public FileDragAndDropTarget,
  42040. public DragAndDropTarget,
  42041. private AsyncUpdater
  42042. {
  42043. public:
  42044. /** Creates an empty treeview.
  42045. Once you've got a treeview component, you'll need to give it something to
  42046. display, using the setRootItem() method.
  42047. */
  42048. TreeView (const String& componentName = String::empty);
  42049. /** Destructor. */
  42050. ~TreeView();
  42051. /** Sets the item that is displayed in the treeview.
  42052. A tree has a single root item which contains as many sub-items as it needs. If
  42053. you want the tree to contain a number of root items, you should still use a single
  42054. root item above these, but hide it using setRootItemVisible().
  42055. You can pass in 0 to this method to clear the tree and remove its current root item.
  42056. The object passed in will not be deleted by the treeview, it's up to the caller
  42057. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  42058. this item until you've removed it from the tree, either by calling setRootItem (nullptr),
  42059. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  42060. to delete it.
  42061. */
  42062. void setRootItem (TreeViewItem* newRootItem);
  42063. /** Returns the tree's root item.
  42064. This will be the last object passed to setRootItem(), or 0 if none has been set.
  42065. */
  42066. TreeViewItem* getRootItem() const noexcept { return rootItem; }
  42067. /** This will remove and delete the current root item.
  42068. It's a convenient way of deleting the item and calling setRootItem (nullptr).
  42069. */
  42070. void deleteRootItem();
  42071. /** Changes whether the tree's root item is shown or not.
  42072. If the root item is hidden, only its sub-items will be shown in the treeview - this
  42073. lets you make the tree look as if it's got many root items. If it's hidden, this call
  42074. will also make sure the root item is open (otherwise the treeview would look empty).
  42075. */
  42076. void setRootItemVisible (bool shouldBeVisible);
  42077. /** Returns true if the root item is visible.
  42078. @see setRootItemVisible
  42079. */
  42080. bool isRootItemVisible() const noexcept { return rootItemVisible; }
  42081. /** Sets whether items are open or closed by default.
  42082. Normally, items are closed until the user opens them, but you can use this
  42083. to make them default to being open until explicitly closed.
  42084. @see areItemsOpenByDefault
  42085. */
  42086. void setDefaultOpenness (bool isOpenByDefault);
  42087. /** Returns true if the tree's items default to being open.
  42088. @see setDefaultOpenness
  42089. */
  42090. bool areItemsOpenByDefault() const noexcept { return defaultOpenness; }
  42091. /** This sets a flag to indicate that the tree can be used for multi-selection.
  42092. You can always select multiple items internally by calling the
  42093. TreeViewItem::setSelected() method, but this flag indicates whether the user
  42094. is allowed to multi-select by clicking on the tree.
  42095. By default it is disabled.
  42096. @see isMultiSelectEnabled
  42097. */
  42098. void setMultiSelectEnabled (bool canMultiSelect);
  42099. /** Returns whether multi-select has been enabled for the tree.
  42100. @see setMultiSelectEnabled
  42101. */
  42102. bool isMultiSelectEnabled() const noexcept { return multiSelectEnabled; }
  42103. /** Sets a flag to indicate whether to hide the open/close buttons.
  42104. @see areOpenCloseButtonsVisible
  42105. */
  42106. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  42107. /** Returns whether open/close buttons are shown.
  42108. @see setOpenCloseButtonsVisible
  42109. */
  42110. bool areOpenCloseButtonsVisible() const noexcept { return openCloseButtonsVisible; }
  42111. /** Deselects any items that are currently selected. */
  42112. void clearSelectedItems();
  42113. /** Returns the number of items that are currently selected.
  42114. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  42115. tree will be recursed.
  42116. @see getSelectedItem, clearSelectedItems
  42117. */
  42118. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const noexcept;
  42119. /** Returns one of the selected items in the tree.
  42120. @param index the index, 0 to (getNumSelectedItems() - 1)
  42121. */
  42122. TreeViewItem* getSelectedItem (int index) const noexcept;
  42123. /** Returns the number of rows the tree is using.
  42124. This will depend on which items are open.
  42125. @see TreeViewItem::getRowNumberInTree()
  42126. */
  42127. int getNumRowsInTree() const;
  42128. /** Returns the item on a particular row of the tree.
  42129. If the index is out of range, this will return 0.
  42130. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  42131. */
  42132. TreeViewItem* getItemOnRow (int index) const;
  42133. /** Returns the item that contains a given y position.
  42134. The y is relative to the top of the TreeView component.
  42135. */
  42136. TreeViewItem* getItemAt (int yPosition) const noexcept;
  42137. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  42138. void scrollToKeepItemVisible (TreeViewItem* item);
  42139. /** Returns the treeview's Viewport object. */
  42140. Viewport* getViewport() const noexcept;
  42141. /** Returns the number of pixels by which each nested level of the tree is indented.
  42142. @see setIndentSize
  42143. */
  42144. int getIndentSize() const noexcept { return indentSize; }
  42145. /** Changes the distance by which each nested level of the tree is indented.
  42146. @see getIndentSize
  42147. */
  42148. void setIndentSize (int newIndentSize);
  42149. /** Searches the tree for an item with the specified identifier.
  42150. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  42151. If no such item exists, this will return false. If the item is found, all of its items
  42152. will be automatically opened.
  42153. */
  42154. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  42155. /** Saves the current state of open/closed nodes so it can be restored later.
  42156. This takes a snapshot of which nodes have been explicitly opened or closed,
  42157. and records it as XML. To identify node objects it uses the
  42158. TreeViewItem::getUniqueName() method to create named paths. This
  42159. means that the same state of open/closed nodes can be restored to a
  42160. completely different instance of the tree, as long as it contains nodes
  42161. whose unique names are the same.
  42162. The caller is responsible for deleting the object that is returned.
  42163. @param alsoIncludeScrollPosition if this is true, the state will also
  42164. include information about where the
  42165. tree has been scrolled to vertically,
  42166. so this can also be restored
  42167. @see restoreOpennessState
  42168. */
  42169. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  42170. /** Restores a previously saved arrangement of open/closed nodes.
  42171. This will try to restore a snapshot of the tree's state that was created by
  42172. the getOpennessState() method. If any of the nodes named in the original
  42173. XML aren't present in this tree, they will be ignored.
  42174. If restoreStoredSelection is true, it will also try to re-select any items that
  42175. were selected in the stored state.
  42176. @see getOpennessState
  42177. */
  42178. void restoreOpennessState (const XmlElement& newState,
  42179. bool restoreStoredSelection);
  42180. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  42181. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42182. methods.
  42183. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42184. */
  42185. enum ColourIds
  42186. {
  42187. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  42188. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  42189. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  42190. };
  42191. /** @internal */
  42192. void paint (Graphics& g);
  42193. /** @internal */
  42194. void resized();
  42195. /** @internal */
  42196. bool keyPressed (const KeyPress& key);
  42197. /** @internal */
  42198. void colourChanged();
  42199. /** @internal */
  42200. void enablementChanged();
  42201. /** @internal */
  42202. bool isInterestedInFileDrag (const StringArray& files);
  42203. /** @internal */
  42204. void fileDragEnter (const StringArray& files, int x, int y);
  42205. /** @internal */
  42206. void fileDragMove (const StringArray& files, int x, int y);
  42207. /** @internal */
  42208. void fileDragExit (const StringArray& files);
  42209. /** @internal */
  42210. void filesDropped (const StringArray& files, int x, int y);
  42211. /** @internal */
  42212. bool isInterestedInDragSource (const SourceDetails&);
  42213. /** @internal */
  42214. void itemDragEnter (const SourceDetails&);
  42215. /** @internal */
  42216. void itemDragMove (const SourceDetails&);
  42217. /** @internal */
  42218. void itemDragExit (const SourceDetails&);
  42219. /** @internal */
  42220. void itemDropped (const SourceDetails&);
  42221. private:
  42222. friend class TreeViewItem;
  42223. friend class TreeViewContentComponent;
  42224. class TreeViewport;
  42225. class InsertPointHighlight;
  42226. class TargetGroupHighlight;
  42227. friend class ScopedPointer<TreeViewport>;
  42228. friend class ScopedPointer<InsertPointHighlight>;
  42229. friend class ScopedPointer<TargetGroupHighlight>;
  42230. ScopedPointer<TreeViewport> viewport;
  42231. CriticalSection nodeAlterationLock;
  42232. TreeViewItem* rootItem;
  42233. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  42234. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  42235. int indentSize;
  42236. bool defaultOpenness : 1;
  42237. bool needsRecalculating : 1;
  42238. bool rootItemVisible : 1;
  42239. bool multiSelectEnabled : 1;
  42240. bool openCloseButtonsVisible : 1;
  42241. void itemsChanged() noexcept;
  42242. void handleAsyncUpdate();
  42243. void moveSelectedRow (int delta);
  42244. void updateButtonUnderMouse (const MouseEvent& e);
  42245. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) noexcept;
  42246. void hideDragHighlight() noexcept;
  42247. void handleDrag (const StringArray& files, const SourceDetails&);
  42248. void handleDrop (const StringArray& files, const SourceDetails&);
  42249. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  42250. const StringArray& files, const SourceDetails&) const noexcept;
  42251. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  42252. };
  42253. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  42254. /*** End of inlined file: juce_TreeView.h ***/
  42255. #endif
  42256. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42257. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42258. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42259. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42260. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  42261. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42262. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42263. /*** Start of inlined file: juce_FileFilter.h ***/
  42264. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  42265. #define __JUCE_FILEFILTER_JUCEHEADER__
  42266. /**
  42267. Interface for deciding which files are suitable for something.
  42268. For example, this is used by DirectoryContentsList to select which files
  42269. go into the list.
  42270. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  42271. */
  42272. class JUCE_API FileFilter
  42273. {
  42274. public:
  42275. /** Creates a filter with the given description.
  42276. The description can be returned later with the getDescription() method.
  42277. */
  42278. FileFilter (const String& filterDescription);
  42279. /** Destructor. */
  42280. virtual ~FileFilter();
  42281. /** Returns the description that the filter was created with. */
  42282. const String& getDescription() const noexcept;
  42283. /** Should return true if this file is suitable for inclusion in whatever context
  42284. the object is being used.
  42285. */
  42286. virtual bool isFileSuitable (const File& file) const = 0;
  42287. /** Should return true if this directory is suitable for inclusion in whatever context
  42288. the object is being used.
  42289. */
  42290. virtual bool isDirectorySuitable (const File& file) const = 0;
  42291. protected:
  42292. String description;
  42293. };
  42294. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  42295. /*** End of inlined file: juce_FileFilter.h ***/
  42296. /**
  42297. A class to asynchronously scan for details about the files in a directory.
  42298. This keeps a list of files and some information about them, using a background
  42299. thread to scan for more files. As files are found, it broadcasts change messages
  42300. to tell any listeners.
  42301. @see FileListComponent, FileBrowserComponent
  42302. */
  42303. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  42304. public TimeSliceClient
  42305. {
  42306. public:
  42307. /** Creates a directory list.
  42308. To set the directory it should point to, use setDirectory(), which will
  42309. also start it scanning for files on the background thread.
  42310. When the background thread finds and adds new files to this list, the
  42311. ChangeBroadcaster class will send a change message, so you can register
  42312. listeners and update them when the list changes.
  42313. @param fileFilter an optional filter to select which files are
  42314. included in the list. If this is 0, then all files
  42315. and directories are included. Make sure that the
  42316. filter doesn't get deleted during the lifetime of this
  42317. object
  42318. @param threadToUse a thread object that this list can use
  42319. to scan for files as a background task. Make sure
  42320. that the thread you give it has been started, or you
  42321. won't get any files!
  42322. */
  42323. DirectoryContentsList (const FileFilter* fileFilter,
  42324. TimeSliceThread& threadToUse);
  42325. /** Destructor. */
  42326. ~DirectoryContentsList();
  42327. /** Sets the directory to look in for files.
  42328. If the directory that's passed in is different to the current one, this will
  42329. also start the background thread scanning it for files.
  42330. */
  42331. void setDirectory (const File& directory,
  42332. bool includeDirectories,
  42333. bool includeFiles);
  42334. /** Returns the directory that's currently being used. */
  42335. const File& getDirectory() const;
  42336. /** Clears the list, and stops the thread scanning for files. */
  42337. void clear();
  42338. /** Clears the list and restarts scanning the directory for files. */
  42339. void refresh();
  42340. /** True if the background thread hasn't yet finished scanning for files. */
  42341. bool isStillLoading() const;
  42342. /** Tells the list whether or not to ignore hidden files.
  42343. By default these are ignored.
  42344. */
  42345. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  42346. /** Returns true if hidden files are ignored.
  42347. @see setIgnoresHiddenFiles
  42348. */
  42349. bool ignoresHiddenFiles() const;
  42350. /** Contains cached information about one of the files in a DirectoryContentsList.
  42351. */
  42352. struct FileInfo
  42353. {
  42354. /** The filename.
  42355. This isn't a full pathname, it's just the last part of the path, same as you'd
  42356. get from File::getFileName().
  42357. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  42358. */
  42359. String filename;
  42360. /** File size in bytes. */
  42361. int64 fileSize;
  42362. /** File modification time.
  42363. As supplied by File::getLastModificationTime().
  42364. */
  42365. Time modificationTime;
  42366. /** File creation time.
  42367. As supplied by File::getCreationTime().
  42368. */
  42369. Time creationTime;
  42370. /** True if the file is a directory. */
  42371. bool isDirectory;
  42372. /** True if the file is read-only. */
  42373. bool isReadOnly;
  42374. };
  42375. /** Returns the number of files currently available in the list.
  42376. The info about one of these files can be retrieved with getFileInfo() or
  42377. getFile().
  42378. Obviously as the background thread runs and scans the directory for files, this
  42379. number will change.
  42380. @see getFileInfo, getFile
  42381. */
  42382. int getNumFiles() const;
  42383. /** Returns the cached information about one of the files in the list.
  42384. If the index is in-range, this will return true and will copy the file's details
  42385. to the structure that is passed-in.
  42386. If it returns false, then the index wasn't in range, and the structure won't
  42387. be affected.
  42388. @see getNumFiles, getFile
  42389. */
  42390. bool getFileInfo (int index, FileInfo& resultInfo) const;
  42391. /** Returns one of the files in the list.
  42392. @param index should be less than getNumFiles(). If this is out-of-range, the
  42393. return value will be File::nonexistent
  42394. @see getNumFiles, getFileInfo
  42395. */
  42396. File getFile (int index) const;
  42397. /** Returns the file filter being used.
  42398. The filter is specified in the constructor.
  42399. */
  42400. const FileFilter* getFilter() const { return fileFilter; }
  42401. /** @internal */
  42402. int useTimeSlice();
  42403. /** @internal */
  42404. TimeSliceThread& getTimeSliceThread() { return thread; }
  42405. /** @internal */
  42406. static int compareElements (const DirectoryContentsList::FileInfo* first,
  42407. const DirectoryContentsList::FileInfo* second);
  42408. private:
  42409. File root;
  42410. const FileFilter* fileFilter;
  42411. TimeSliceThread& thread;
  42412. int fileTypeFlags;
  42413. CriticalSection fileListLock;
  42414. OwnedArray <FileInfo> files;
  42415. ScopedPointer <DirectoryIterator> fileFindHandle;
  42416. bool volatile shouldStop;
  42417. void changed();
  42418. bool checkNextFile (bool& hasChanged);
  42419. bool addFile (const File& file, bool isDir,
  42420. const int64 fileSize, const Time& modTime,
  42421. const Time& creationTime, bool isReadOnly);
  42422. void setTypeFlags (int newFlags);
  42423. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  42424. };
  42425. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42426. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  42427. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  42428. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42429. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42430. /**
  42431. A listener for user selection events in a file browser.
  42432. This is used by a FileBrowserComponent or FileListComponent.
  42433. */
  42434. class JUCE_API FileBrowserListener
  42435. {
  42436. public:
  42437. /** Destructor. */
  42438. virtual ~FileBrowserListener();
  42439. /** Callback when the user selects a different file in the browser. */
  42440. virtual void selectionChanged() = 0;
  42441. /** Callback when the user clicks on a file in the browser. */
  42442. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  42443. /** Callback when the user double-clicks on a file in the browser. */
  42444. virtual void fileDoubleClicked (const File& file) = 0;
  42445. };
  42446. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42447. /*** End of inlined file: juce_FileBrowserListener.h ***/
  42448. /**
  42449. A base class for components that display a list of the files in a directory.
  42450. @see DirectoryContentsList
  42451. */
  42452. class JUCE_API DirectoryContentsDisplayComponent
  42453. {
  42454. public:
  42455. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  42456. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  42457. /** Destructor. */
  42458. virtual ~DirectoryContentsDisplayComponent();
  42459. /** Returns the number of files the user has got selected.
  42460. @see getSelectedFile
  42461. */
  42462. virtual int getNumSelectedFiles() const = 0;
  42463. /** Returns one of the files that the user has currently selected.
  42464. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  42465. @see getNumSelectedFiles
  42466. */
  42467. virtual const File getSelectedFile (int index) const = 0;
  42468. /** Deselects any selected files. */
  42469. virtual void deselectAllFiles() = 0;
  42470. /** Scrolls this view to the top. */
  42471. virtual void scrollToTop() = 0;
  42472. /** Adds a listener to be told when files are selected or clicked.
  42473. @see removeListener
  42474. */
  42475. void addListener (FileBrowserListener* listener);
  42476. /** Removes a listener.
  42477. @see addListener
  42478. */
  42479. void removeListener (FileBrowserListener* listener);
  42480. /** A set of colour IDs to use to change the colour of various aspects of the list.
  42481. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42482. methods.
  42483. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42484. */
  42485. enum ColourIds
  42486. {
  42487. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  42488. textColourId = 0x1000541, /**< The colour for the text. */
  42489. };
  42490. /** @internal */
  42491. void sendSelectionChangeMessage();
  42492. /** @internal */
  42493. void sendDoubleClickMessage (const File& file);
  42494. /** @internal */
  42495. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  42496. protected:
  42497. DirectoryContentsList& fileList;
  42498. ListenerList <FileBrowserListener> listeners;
  42499. private:
  42500. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  42501. };
  42502. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42503. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42504. #endif
  42505. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42506. #endif
  42507. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42508. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  42509. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42510. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42511. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  42512. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42513. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42514. /**
  42515. Base class for components that live inside a file chooser dialog box and
  42516. show previews of the files that get selected.
  42517. One of these allows special extra information to be displayed for files
  42518. in a dialog box as the user selects them. Each time the current file or
  42519. directory is changed, the selectedFileChanged() method will be called
  42520. to allow it to update itself appropriately.
  42521. @see FileChooser, ImagePreviewComponent
  42522. */
  42523. class JUCE_API FilePreviewComponent : public Component
  42524. {
  42525. public:
  42526. /** Creates a FilePreviewComponent. */
  42527. FilePreviewComponent();
  42528. /** Destructor. */
  42529. ~FilePreviewComponent();
  42530. /** Called to indicate that the user's currently selected file has changed.
  42531. @param newSelectedFile the newly selected file or directory, which may be
  42532. File::nonexistent if none is selected.
  42533. */
  42534. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  42535. private:
  42536. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  42537. };
  42538. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42539. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  42540. /**
  42541. A component for browsing and selecting a file or directory to open or save.
  42542. This contains a FileListComponent and adds various boxes and controls for
  42543. navigating and selecting a file. It can work in different modes so that it can
  42544. be used for loading or saving a file, or for choosing a directory.
  42545. @see FileChooserDialogBox, FileChooser, FileListComponent
  42546. */
  42547. class JUCE_API FileBrowserComponent : public Component,
  42548. public ChangeBroadcaster,
  42549. private FileBrowserListener,
  42550. private TextEditorListener,
  42551. private ButtonListener,
  42552. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  42553. private FileFilter
  42554. {
  42555. public:
  42556. /** Various options for the browser.
  42557. A combination of these is passed into the FileBrowserComponent constructor.
  42558. */
  42559. enum FileChooserFlags
  42560. {
  42561. openMode = 1, /**< specifies that the component should allow the user to
  42562. choose an existing file with the intention of opening it. */
  42563. saveMode = 2, /**< specifies that the component should allow the user to specify
  42564. the name of a file that will be used to save something. */
  42565. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  42566. conjunction with canSelectDirectories). */
  42567. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  42568. conjuction with canSelectFiles). */
  42569. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  42570. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  42571. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  42572. };
  42573. /** Creates a FileBrowserComponent.
  42574. @param flags A combination of flags from the FileChooserFlags enumeration,
  42575. used to specify the component's behaviour. The flags must contain
  42576. either openMode or saveMode, and canSelectFiles and/or
  42577. canSelectDirectories.
  42578. @param initialFileOrDirectory The file or directory that should be selected when
  42579. the component begins. If this is File::nonexistent,
  42580. a default directory will be chosen.
  42581. @param fileFilter an optional filter to use to determine which files
  42582. are shown. If this is 0 then all files are displayed. Note
  42583. that a pointer is kept internally to this object, so
  42584. make sure that it is not deleted before the browser object
  42585. is deleted.
  42586. @param previewComp an optional preview component that will be used to
  42587. show previews of files that the user selects
  42588. */
  42589. FileBrowserComponent (int flags,
  42590. const File& initialFileOrDirectory,
  42591. const FileFilter* fileFilter,
  42592. FilePreviewComponent* previewComp);
  42593. /** Destructor. */
  42594. ~FileBrowserComponent();
  42595. /** Returns the number of files that the user has got selected.
  42596. If multiple select isn't active, this will only be 0 or 1. To get the complete
  42597. list of files they've chosen, pass an index to getCurrentFile().
  42598. */
  42599. int getNumSelectedFiles() const noexcept;
  42600. /** Returns one of the files that the user has chosen.
  42601. If the box has multi-select enabled, the index lets you specify which of the files
  42602. to get - see getNumSelectedFiles() to find out how many files were chosen.
  42603. @see getHighlightedFile
  42604. */
  42605. File getSelectedFile (int index) const noexcept;
  42606. /** Deselects any files that are currently selected.
  42607. */
  42608. void deselectAllFiles();
  42609. /** Returns true if the currently selected file(s) are usable.
  42610. This can be used to decide whether the user can press "ok" for the
  42611. current file. What it does depends on the mode, so for example in an "open"
  42612. mode, this only returns true if a file has been selected and if it exists.
  42613. In a "save" mode, a non-existent file would also be valid.
  42614. */
  42615. bool currentFileIsValid() const;
  42616. /** This returns the last item in the view that the user has highlighted.
  42617. This may be different from getCurrentFile(), which returns the value
  42618. that is shown in the filename box, and if there are multiple selections,
  42619. this will only return one of them.
  42620. @see getSelectedFile
  42621. */
  42622. File getHighlightedFile() const noexcept;
  42623. /** Returns the directory whose contents are currently being shown in the listbox. */
  42624. const File& getRoot() const;
  42625. /** Changes the directory that's being shown in the listbox. */
  42626. void setRoot (const File& newRootDirectory);
  42627. /** Equivalent to pressing the "up" button to browse the parent directory. */
  42628. void goUp();
  42629. /** Refreshes the directory that's currently being listed. */
  42630. void refresh();
  42631. /** Changes the filter that's being used to sift the files. */
  42632. void setFileFilter (const FileFilter* newFileFilter);
  42633. /** Returns a verb to describe what should happen when the file is accepted.
  42634. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  42635. mode, it'll be "Save", etc.
  42636. */
  42637. virtual const String getActionVerb() const;
  42638. /** Returns true if the saveMode flag was set when this component was created.
  42639. */
  42640. bool isSaveMode() const noexcept;
  42641. /** Adds a listener to be told when the user selects and clicks on files.
  42642. @see removeListener
  42643. */
  42644. void addListener (FileBrowserListener* listener);
  42645. /** Removes a listener.
  42646. @see addListener
  42647. */
  42648. void removeListener (FileBrowserListener* listener);
  42649. /** @internal */
  42650. void resized();
  42651. /** @internal */
  42652. void buttonClicked (Button* b);
  42653. /** @internal */
  42654. void comboBoxChanged (ComboBox*);
  42655. /** @internal */
  42656. void textEditorTextChanged (TextEditor& editor);
  42657. /** @internal */
  42658. void textEditorReturnKeyPressed (TextEditor& editor);
  42659. /** @internal */
  42660. void textEditorEscapeKeyPressed (TextEditor& editor);
  42661. /** @internal */
  42662. void textEditorFocusLost (TextEditor& editor);
  42663. /** @internal */
  42664. bool keyPressed (const KeyPress& key);
  42665. /** @internal */
  42666. void selectionChanged();
  42667. /** @internal */
  42668. void fileClicked (const File& f, const MouseEvent& e);
  42669. /** @internal */
  42670. void fileDoubleClicked (const File& f);
  42671. /** @internal */
  42672. bool isFileSuitable (const File& file) const;
  42673. /** @internal */
  42674. bool isDirectorySuitable (const File&) const;
  42675. /** @internal */
  42676. FilePreviewComponent* getPreviewComponent() const noexcept;
  42677. protected:
  42678. /** Returns a list of names and paths for the default places the user might want to look.
  42679. Use an empty string to indicate a section break.
  42680. */
  42681. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  42682. /** Updates the items in the dropdown list of recent paths with the values from getRoots(). */
  42683. void resetRecentPaths();
  42684. private:
  42685. ScopedPointer <DirectoryContentsList> fileList;
  42686. const FileFilter* fileFilter;
  42687. int flags;
  42688. File currentRoot;
  42689. Array<File> chosenFiles;
  42690. ListenerList <FileBrowserListener> listeners;
  42691. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  42692. FilePreviewComponent* previewComp;
  42693. ComboBox currentPathBox;
  42694. TextEditor filenameBox;
  42695. Label fileLabel;
  42696. ScopedPointer<Button> goUpButton;
  42697. TimeSliceThread thread;
  42698. void sendListenerChangeMessage();
  42699. bool isFileOrDirSuitable (const File& f) const;
  42700. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  42701. };
  42702. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42703. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  42704. #endif
  42705. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42706. #endif
  42707. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42708. /*** Start of inlined file: juce_FileChooser.h ***/
  42709. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42710. #define __JUCE_FILECHOOSER_JUCEHEADER__
  42711. /**
  42712. Creates a dialog box to choose a file or directory to load or save.
  42713. To use a FileChooser:
  42714. - create one (as a local stack variable is the neatest way)
  42715. - call one of its browseFor.. methods
  42716. - if this returns true, the user has selected a file, so you can retrieve it
  42717. with the getResult() method.
  42718. e.g. @code
  42719. void loadMooseFile()
  42720. {
  42721. FileChooser myChooser ("Please select the moose you want to load...",
  42722. File::getSpecialLocation (File::userHomeDirectory),
  42723. "*.moose");
  42724. if (myChooser.browseForFileToOpen())
  42725. {
  42726. File mooseFile (myChooser.getResult());
  42727. loadMoose (mooseFile);
  42728. }
  42729. }
  42730. @endcode
  42731. */
  42732. class JUCE_API FileChooser
  42733. {
  42734. public:
  42735. /** Creates a FileChooser.
  42736. After creating one of these, use one of the browseFor... methods to display it.
  42737. @param dialogBoxTitle a text string to display in the dialog box to
  42738. tell the user what's going on
  42739. @param initialFileOrDirectory the file or directory that should be selected when
  42740. the dialog box opens. If this parameter is set to
  42741. File::nonexistent, a sensible default directory
  42742. will be used instead.
  42743. @param filePatternsAllowed a set of file patterns to specify which files can be
  42744. selected - each pattern should be separated by a
  42745. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  42746. empty string means that all files are allowed
  42747. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  42748. possible; if false, then a Juce-based browser dialog
  42749. box will always be used
  42750. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  42751. */
  42752. FileChooser (const String& dialogBoxTitle,
  42753. const File& initialFileOrDirectory = File::nonexistent,
  42754. const String& filePatternsAllowed = String::empty,
  42755. bool useOSNativeDialogBox = true);
  42756. /** Destructor. */
  42757. ~FileChooser();
  42758. /** Shows a dialog box to choose a file to open.
  42759. This will display the dialog box modally, using an "open file" mode, so that
  42760. it won't allow non-existent files or directories to be chosen.
  42761. @param previewComponent an optional component to display inside the dialog
  42762. box to show special info about the files that the user
  42763. is browsing. The component will not be deleted by this
  42764. object, so the caller must take care of it.
  42765. @returns true if the user selected a file, in which case, use the getResult()
  42766. method to find out what it was. Returns false if they cancelled instead.
  42767. @see browseForFileToSave, browseForDirectory
  42768. */
  42769. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  42770. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  42771. The files that are returned can be obtained by calling getResults(). See
  42772. browseForFileToOpen() for more info about the behaviour of this method.
  42773. */
  42774. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  42775. /** Shows a dialog box to choose a file to save.
  42776. This will display the dialog box modally, using an "save file" mode, so it
  42777. will allow non-existent files to be chosen, but not directories.
  42778. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  42779. the user if they're sure they want to overwrite a file that already
  42780. exists
  42781. @returns true if the user chose a file and pressed 'ok', in which case, use
  42782. the getResult() method to find out what the file was. Returns false
  42783. if they cancelled instead.
  42784. @see browseForFileToOpen, browseForDirectory
  42785. */
  42786. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  42787. /** Shows a dialog box to choose a directory.
  42788. This will display the dialog box modally, using an "open directory" mode, so it
  42789. will only allow directories to be returned, not files.
  42790. @returns true if the user chose a directory and pressed 'ok', in which case, use
  42791. the getResult() method to find out what they chose. Returns false
  42792. if they cancelled instead.
  42793. @see browseForFileToOpen, browseForFileToSave
  42794. */
  42795. bool browseForDirectory();
  42796. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  42797. The files that are returned can be obtained by calling getResults(). See
  42798. browseForFileToOpen() for more info about the behaviour of this method.
  42799. */
  42800. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  42801. /** Returns the last file that was chosen by one of the browseFor methods.
  42802. After calling the appropriate browseFor... method, this method lets you
  42803. find out what file or directory they chose.
  42804. Note that the file returned is only valid if the browse method returned true (i.e.
  42805. if the user pressed 'ok' rather than cancelling).
  42806. If you're using a multiple-file select, then use the getResults() method instead,
  42807. to obtain the list of all files chosen.
  42808. @see getResults
  42809. */
  42810. File getResult() const;
  42811. /** Returns a list of all the files that were chosen during the last call to a
  42812. browse method.
  42813. This array may be empty if no files were chosen, or can contain multiple entries
  42814. if multiple files were chosen.
  42815. @see getResult
  42816. */
  42817. const Array<File>& getResults() const;
  42818. private:
  42819. String title, filters;
  42820. File startingFile;
  42821. Array<File> results;
  42822. bool useNativeDialogBox;
  42823. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  42824. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42825. FilePreviewComponent* previewComponent);
  42826. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  42827. const String& filters, bool selectsDirectories, bool selectsFiles,
  42828. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42829. FilePreviewComponent* previewComponent);
  42830. JUCE_LEAK_DETECTOR (FileChooser);
  42831. };
  42832. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  42833. /*** End of inlined file: juce_FileChooser.h ***/
  42834. #endif
  42835. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42836. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  42837. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42838. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42839. /*** Start of inlined file: juce_ResizableWindow.h ***/
  42840. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42841. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42842. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  42843. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42844. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42845. /*** Start of inlined file: juce_DropShadower.h ***/
  42846. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42847. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  42848. /**
  42849. Adds a drop-shadow to a component.
  42850. This object creates and manages a set of components which sit around a
  42851. component, creating a gaussian shadow around it. The components will track
  42852. the position of the component and if it's brought to the front they'll also
  42853. follow this.
  42854. For desktop windows you don't need to use this class directly - just
  42855. set the Component::windowHasDropShadow flag when calling
  42856. Component::addToDesktop(), and the system will create one of these if it's
  42857. needed (which it obviously isn't on the Mac, for example).
  42858. */
  42859. class JUCE_API DropShadower : public ComponentListener
  42860. {
  42861. public:
  42862. /** Creates a DropShadower.
  42863. @param alpha the opacity of the shadows, from 0 to 1.0
  42864. @param xOffset the horizontal displacement of the shadow, in pixels
  42865. @param yOffset the vertical displacement of the shadow, in pixels
  42866. @param blurRadius the radius of the blur to use for creating the shadow
  42867. */
  42868. DropShadower (float alpha = 0.5f,
  42869. int xOffset = 1,
  42870. int yOffset = 5,
  42871. float blurRadius = 10.0f);
  42872. /** Destructor. */
  42873. virtual ~DropShadower();
  42874. /** Attaches the DropShadower to the component you want to shadow. */
  42875. void setOwner (Component* componentToFollow);
  42876. /** @internal */
  42877. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42878. /** @internal */
  42879. void componentBroughtToFront (Component& component);
  42880. /** @internal */
  42881. void componentParentHierarchyChanged (Component& component);
  42882. /** @internal */
  42883. void componentVisibilityChanged (Component& component);
  42884. private:
  42885. Component* owner;
  42886. OwnedArray<Component> shadowWindows;
  42887. Image shadowImageSections[12];
  42888. const int xOffset, yOffset;
  42889. const float alpha, blurRadius;
  42890. bool reentrant;
  42891. void updateShadows();
  42892. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  42893. void bringShadowWindowsToFront();
  42894. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  42895. };
  42896. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  42897. /*** End of inlined file: juce_DropShadower.h ***/
  42898. /**
  42899. A base class for top-level windows.
  42900. This class is used for components that are considered a major part of your
  42901. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  42902. etc. Things like menus that pop up briefly aren't derived from it.
  42903. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  42904. could itself be the child of another component.
  42905. The class manages a list of all instances of top-level windows that are in use,
  42906. and each one is also given the concept of being "active". The active window is
  42907. one that is actively being used by the user. This isn't quite the same as the
  42908. component with the keyboard focus, because there may be a popup menu or other
  42909. temporary window which gets keyboard focus while the active top level window is
  42910. unchanged.
  42911. A top-level window also has an optional drop-shadow.
  42912. @see ResizableWindow, DocumentWindow, DialogWindow
  42913. */
  42914. class JUCE_API TopLevelWindow : public Component
  42915. {
  42916. public:
  42917. /** Creates a TopLevelWindow.
  42918. @param name the name to give the component
  42919. @param addToDesktop if true, the window will be automatically added to the
  42920. desktop; if false, you can use it as a child component
  42921. */
  42922. TopLevelWindow (const String& name, bool addToDesktop);
  42923. /** Destructor. */
  42924. ~TopLevelWindow();
  42925. /** True if this is currently the TopLevelWindow that is actively being used.
  42926. This isn't quite the same as having keyboard focus, because the focus may be
  42927. on a child component or a temporary pop-up menu, etc, while this window is
  42928. still considered to be active.
  42929. @see activeWindowStatusChanged
  42930. */
  42931. bool isActiveWindow() const noexcept { return windowIsActive_; }
  42932. /** This will set the bounds of the window so that it's centred in front of another
  42933. window.
  42934. If your app has a few windows open and want to pop up a dialog box for one of
  42935. them, you can use this to show it in front of the relevent parent window, which
  42936. is a bit neater than just having it appear in the middle of the screen.
  42937. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  42938. be used instead. If no window is focused, it'll just default to the middle of the
  42939. screen.
  42940. */
  42941. void centreAroundComponent (Component* componentToCentreAround,
  42942. int width, int height);
  42943. /** Turns the drop-shadow on and off. */
  42944. void setDropShadowEnabled (bool useShadow);
  42945. /** Sets whether an OS-native title bar will be used, or a Juce one.
  42946. @see isUsingNativeTitleBar
  42947. */
  42948. void setUsingNativeTitleBar (bool useNativeTitleBar);
  42949. /** Returns true if the window is currently using an OS-native title bar.
  42950. @see setUsingNativeTitleBar
  42951. */
  42952. bool isUsingNativeTitleBar() const noexcept { return useNativeTitleBar && isOnDesktop(); }
  42953. /** Returns the number of TopLevelWindow objects currently in use.
  42954. @see getTopLevelWindow
  42955. */
  42956. static int getNumTopLevelWindows() noexcept;
  42957. /** Returns one of the TopLevelWindow objects currently in use.
  42958. The index is 0 to (getNumTopLevelWindows() - 1).
  42959. */
  42960. static TopLevelWindow* getTopLevelWindow (int index) noexcept;
  42961. /** Returns the currently-active top level window.
  42962. There might not be one, of course, so this can return 0.
  42963. */
  42964. static TopLevelWindow* getActiveTopLevelWindow() noexcept;
  42965. /** @internal */
  42966. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = nullptr);
  42967. protected:
  42968. /** This callback happens when this window becomes active or inactive.
  42969. @see isActiveWindow
  42970. */
  42971. virtual void activeWindowStatusChanged();
  42972. /** @internal */
  42973. void focusOfChildComponentChanged (FocusChangeType cause);
  42974. /** @internal */
  42975. void parentHierarchyChanged();
  42976. /** @internal */
  42977. virtual int getDesktopWindowStyleFlags() const;
  42978. /** @internal */
  42979. void recreateDesktopWindow();
  42980. /** @internal */
  42981. void visibilityChanged();
  42982. private:
  42983. friend class TopLevelWindowManager;
  42984. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  42985. ScopedPointer <DropShadower> shadower;
  42986. void setWindowActive (bool isNowActive);
  42987. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  42988. };
  42989. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42990. /*** End of inlined file: juce_TopLevelWindow.h ***/
  42991. /*** Start of inlined file: juce_ComponentDragger.h ***/
  42992. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42993. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42994. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42995. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42996. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42997. /**
  42998. A class that imposes restrictions on a Component's size or position.
  42999. This is used by classes such as ResizableCornerComponent,
  43000. ResizableBorderComponent and ResizableWindow.
  43001. The base class can impose some basic size and position limits, but you can
  43002. also subclass this for custom uses.
  43003. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  43004. */
  43005. class JUCE_API ComponentBoundsConstrainer
  43006. {
  43007. public:
  43008. /** When first created, the object will not impose any restrictions on the components. */
  43009. ComponentBoundsConstrainer() noexcept;
  43010. /** Destructor. */
  43011. virtual ~ComponentBoundsConstrainer();
  43012. /** Imposes a minimum width limit. */
  43013. void setMinimumWidth (int minimumWidth) noexcept;
  43014. /** Returns the current minimum width. */
  43015. int getMinimumWidth() const noexcept { return minW; }
  43016. /** Imposes a maximum width limit. */
  43017. void setMaximumWidth (int maximumWidth) noexcept;
  43018. /** Returns the current maximum width. */
  43019. int getMaximumWidth() const noexcept { return maxW; }
  43020. /** Imposes a minimum height limit. */
  43021. void setMinimumHeight (int minimumHeight) noexcept;
  43022. /** Returns the current minimum height. */
  43023. int getMinimumHeight() const noexcept { return minH; }
  43024. /** Imposes a maximum height limit. */
  43025. void setMaximumHeight (int maximumHeight) noexcept;
  43026. /** Returns the current maximum height. */
  43027. int getMaximumHeight() const noexcept { return maxH; }
  43028. /** Imposes a minimum width and height limit. */
  43029. void setMinimumSize (int minimumWidth,
  43030. int minimumHeight) noexcept;
  43031. /** Imposes a maximum width and height limit. */
  43032. void setMaximumSize (int maximumWidth,
  43033. int maximumHeight) noexcept;
  43034. /** Set all the maximum and minimum dimensions. */
  43035. void setSizeLimits (int minimumWidth,
  43036. int minimumHeight,
  43037. int maximumWidth,
  43038. int maximumHeight) noexcept;
  43039. /** Sets the amount by which the component is allowed to go off-screen.
  43040. The values indicate how many pixels must remain on-screen when dragged off
  43041. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  43042. when the component goes off the top of the screen, its y-position will be
  43043. clipped so that there are always at least 10 pixels on-screen. In other words,
  43044. the lowest y-position it can take would be (10 - the component's height).
  43045. If you pass 0 or less for one of these amounts, the component is allowed
  43046. to move beyond that edge completely, with no restrictions at all.
  43047. If you pass a very large number (i.e. larger that the dimensions of the
  43048. component itself), then the component won't be allowed to overlap that
  43049. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  43050. the component will bump into the left side of the screen and go no further.
  43051. */
  43052. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  43053. int minimumWhenOffTheLeft,
  43054. int minimumWhenOffTheBottom,
  43055. int minimumWhenOffTheRight) noexcept;
  43056. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43057. int getMinimumWhenOffTheTop() const noexcept { return minOffTop; }
  43058. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43059. int getMinimumWhenOffTheLeft() const noexcept { return minOffLeft; }
  43060. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43061. int getMinimumWhenOffTheBottom() const noexcept { return minOffBottom; }
  43062. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43063. int getMinimumWhenOffTheRight() const noexcept { return minOffRight; }
  43064. /** Specifies a width-to-height ratio that the resizer should always maintain.
  43065. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  43066. will always be maintained as this multiple of the height.
  43067. @see setResizeLimits
  43068. */
  43069. void setFixedAspectRatio (double widthOverHeight) noexcept;
  43070. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  43071. If no aspect ratio is being enforced, this will return 0.
  43072. */
  43073. double getFixedAspectRatio() const noexcept;
  43074. /** This callback changes the given co-ordinates to impose whatever the current
  43075. constraints are set to be.
  43076. @param bounds the target position that should be examined and adjusted
  43077. @param previousBounds the component's current size
  43078. @param limits the region in which the component can be positioned
  43079. @param isStretchingTop whether the top edge of the component is being resized
  43080. @param isStretchingLeft whether the left edge of the component is being resized
  43081. @param isStretchingBottom whether the bottom edge of the component is being resized
  43082. @param isStretchingRight whether the right edge of the component is being resized
  43083. */
  43084. virtual void checkBounds (Rectangle<int>& bounds,
  43085. const Rectangle<int>& previousBounds,
  43086. const Rectangle<int>& limits,
  43087. bool isStretchingTop,
  43088. bool isStretchingLeft,
  43089. bool isStretchingBottom,
  43090. bool isStretchingRight);
  43091. /** This callback happens when the resizer is about to start dragging. */
  43092. virtual void resizeStart();
  43093. /** This callback happens when the resizer has finished dragging. */
  43094. virtual void resizeEnd();
  43095. /** Checks the given bounds, and then sets the component to the corrected size. */
  43096. void setBoundsForComponent (Component* component,
  43097. const Rectangle<int>& bounds,
  43098. bool isStretchingTop,
  43099. bool isStretchingLeft,
  43100. bool isStretchingBottom,
  43101. bool isStretchingRight);
  43102. /** Performs a check on the current size of a component, and moves or resizes
  43103. it if it fails the constraints.
  43104. */
  43105. void checkComponentBounds (Component* component);
  43106. /** Called by setBoundsForComponent() to apply a new constrained size to a
  43107. component.
  43108. By default this just calls setBounds(), but it virtual in case it's needed for
  43109. extremely cunning purposes.
  43110. */
  43111. virtual void applyBoundsToComponent (Component* component,
  43112. const Rectangle<int>& bounds);
  43113. private:
  43114. int minW, maxW, minH, maxH;
  43115. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  43116. double aspectRatio;
  43117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  43118. };
  43119. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43120. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  43121. /**
  43122. An object to take care of the logic for dragging components around with the mouse.
  43123. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  43124. then in your mouseDrag() callback, call dragComponent().
  43125. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  43126. to limit the component's position and keep it on-screen.
  43127. e.g. @code
  43128. class MyDraggableComp
  43129. {
  43130. ComponentDragger myDragger;
  43131. void mouseDown (const MouseEvent& e)
  43132. {
  43133. myDragger.startDraggingComponent (this, e);
  43134. }
  43135. void mouseDrag (const MouseEvent& e)
  43136. {
  43137. myDragger.dragComponent (this, e, nullptr);
  43138. }
  43139. };
  43140. @endcode
  43141. */
  43142. class JUCE_API ComponentDragger
  43143. {
  43144. public:
  43145. /** Creates a ComponentDragger. */
  43146. ComponentDragger();
  43147. /** Destructor. */
  43148. virtual ~ComponentDragger();
  43149. /** Call this from your component's mouseDown() method, to prepare for dragging.
  43150. @param componentToDrag the component that you want to drag
  43151. @param e the mouse event that is triggering the drag
  43152. @see dragComponent
  43153. */
  43154. void startDraggingComponent (Component* componentToDrag,
  43155. const MouseEvent& e);
  43156. /** Call this from your mouseDrag() callback to move the component.
  43157. This will move the component, but will first check the validity of the
  43158. component's new position using the checkPosition() method, which you
  43159. can override if you need to enforce special positioning limits on the
  43160. component.
  43161. @param componentToDrag the component that you want to drag
  43162. @param e the current mouse-drag event
  43163. @param constrainer an optional constrainer object that should be used
  43164. to apply limits to the component's position. Pass
  43165. null if you don't want to contrain the movement.
  43166. @see startDraggingComponent
  43167. */
  43168. void dragComponent (Component* componentToDrag,
  43169. const MouseEvent& e,
  43170. ComponentBoundsConstrainer* constrainer);
  43171. private:
  43172. Point<int> mouseDownWithinTarget;
  43173. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  43174. };
  43175. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43176. /*** End of inlined file: juce_ComponentDragger.h ***/
  43177. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  43178. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43179. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43180. /**
  43181. A component that resizes its parent component when dragged.
  43182. This component forms a frame around the edge of a component, allowing it to
  43183. be dragged by the edges or corners to resize it - like the way windows are
  43184. resized in MSWindows or Linux.
  43185. To use it, just add it to your component, making it fill the entire parent component
  43186. (there's a mouse hit-test that only traps mouse-events which land around the
  43187. edge of the component, so it's even ok to put it on top of any other components
  43188. you're using). Make sure you rescale the resizer component to fill the parent
  43189. each time the parent's size changes.
  43190. @see ResizableCornerComponent
  43191. */
  43192. class JUCE_API ResizableBorderComponent : public Component
  43193. {
  43194. public:
  43195. /** Creates a resizer.
  43196. Pass in the target component which you want to be resized when this one is
  43197. dragged.
  43198. The target component will usually be a parent of the resizer component, but this
  43199. isn't mandatory.
  43200. Remember that when the target component is resized, it'll need to move and
  43201. resize this component to keep it in place, as this won't happen automatically.
  43202. If the constrainer parameter is non-zero, then this object will be used to enforce
  43203. limits on the size and position that the component can be stretched to. Make sure
  43204. that the constrainer isn't deleted while still in use by this object.
  43205. @see ComponentBoundsConstrainer
  43206. */
  43207. ResizableBorderComponent (Component* componentToResize,
  43208. ComponentBoundsConstrainer* constrainer);
  43209. /** Destructor. */
  43210. ~ResizableBorderComponent();
  43211. /** Specifies how many pixels wide the draggable edges of this component are.
  43212. @see getBorderThickness
  43213. */
  43214. void setBorderThickness (const BorderSize<int>& newBorderSize);
  43215. /** Returns the number of pixels wide that the draggable edges of this component are.
  43216. @see setBorderThickness
  43217. */
  43218. const BorderSize<int> getBorderThickness() const;
  43219. /** Represents the different sections of a resizable border, which allow it to
  43220. resized in different ways.
  43221. */
  43222. class Zone
  43223. {
  43224. public:
  43225. enum Zones
  43226. {
  43227. centre = 0,
  43228. left = 1,
  43229. top = 2,
  43230. right = 4,
  43231. bottom = 8
  43232. };
  43233. /** Creates a Zone from a combination of the flags in \enum Zones. */
  43234. explicit Zone (int zoneFlags = 0) noexcept;
  43235. Zone (const Zone& other) noexcept;
  43236. Zone& operator= (const Zone& other) noexcept;
  43237. bool operator== (const Zone& other) const noexcept;
  43238. bool operator!= (const Zone& other) const noexcept;
  43239. /** Given a point within a rectangle with a resizable border, this returns the
  43240. zone that the point lies within.
  43241. */
  43242. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  43243. const BorderSize<int>& border,
  43244. const Point<int>& position);
  43245. /** Returns an appropriate mouse-cursor for this resize zone. */
  43246. const MouseCursor getMouseCursor() const noexcept;
  43247. /** Returns true if dragging this zone will move the enire object without resizing it. */
  43248. bool isDraggingWholeObject() const noexcept { return zone == centre; }
  43249. /** Returns true if dragging this zone will move the object's left edge. */
  43250. bool isDraggingLeftEdge() const noexcept { return (zone & left) != 0; }
  43251. /** Returns true if dragging this zone will move the object's right edge. */
  43252. bool isDraggingRightEdge() const noexcept { return (zone & right) != 0; }
  43253. /** Returns true if dragging this zone will move the object's top edge. */
  43254. bool isDraggingTopEdge() const noexcept { return (zone & top) != 0; }
  43255. /** Returns true if dragging this zone will move the object's bottom edge. */
  43256. bool isDraggingBottomEdge() const noexcept { return (zone & bottom) != 0; }
  43257. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  43258. applies to.
  43259. */
  43260. template <typename ValueType>
  43261. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  43262. const Point<ValueType>& distance) const noexcept
  43263. {
  43264. if (isDraggingWholeObject())
  43265. return original + distance;
  43266. if (isDraggingLeftEdge())
  43267. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  43268. if (isDraggingRightEdge())
  43269. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  43270. if (isDraggingTopEdge())
  43271. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  43272. if (isDraggingBottomEdge())
  43273. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  43274. return original;
  43275. }
  43276. /** Returns the raw flags for this zone. */
  43277. int getZoneFlags() const noexcept { return zone; }
  43278. private:
  43279. int zone;
  43280. };
  43281. protected:
  43282. /** @internal */
  43283. void paint (Graphics& g);
  43284. /** @internal */
  43285. void mouseEnter (const MouseEvent& e);
  43286. /** @internal */
  43287. void mouseMove (const MouseEvent& e);
  43288. /** @internal */
  43289. void mouseDown (const MouseEvent& e);
  43290. /** @internal */
  43291. void mouseDrag (const MouseEvent& e);
  43292. /** @internal */
  43293. void mouseUp (const MouseEvent& e);
  43294. /** @internal */
  43295. bool hitTest (int x, int y);
  43296. private:
  43297. WeakReference<Component> component;
  43298. ComponentBoundsConstrainer* constrainer;
  43299. BorderSize<int> borderSize;
  43300. Rectangle<int> originalBounds;
  43301. Zone mouseZone;
  43302. void updateMouseZone (const MouseEvent& e);
  43303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  43304. };
  43305. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43306. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  43307. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  43308. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43309. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43310. /** A component that resizes a parent component when dragged.
  43311. This is the small triangular stripey resizer component you get in the bottom-right
  43312. of windows (more commonly on the Mac than Windows). Put one in the corner of
  43313. a larger component and it will automatically resize its parent when it gets dragged
  43314. around.
  43315. @see ResizableFrameComponent
  43316. */
  43317. class JUCE_API ResizableCornerComponent : public Component
  43318. {
  43319. public:
  43320. /** Creates a resizer.
  43321. Pass in the target component which you want to be resized when this one is
  43322. dragged.
  43323. The target component will usually be a parent of the resizer component, but this
  43324. isn't mandatory.
  43325. Remember that when the target component is resized, it'll need to move and
  43326. resize this component to keep it in place, as this won't happen automatically.
  43327. If the constrainer parameter is non-zero, then this object will be used to enforce
  43328. limits on the size and position that the component can be stretched to. Make sure
  43329. that the constrainer isn't deleted while still in use by this object. If you
  43330. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  43331. @see ComponentBoundsConstrainer
  43332. */
  43333. ResizableCornerComponent (Component* componentToResize,
  43334. ComponentBoundsConstrainer* constrainer);
  43335. /** Destructor. */
  43336. ~ResizableCornerComponent();
  43337. protected:
  43338. /** @internal */
  43339. void paint (Graphics& g);
  43340. /** @internal */
  43341. void mouseDown (const MouseEvent& e);
  43342. /** @internal */
  43343. void mouseDrag (const MouseEvent& e);
  43344. /** @internal */
  43345. void mouseUp (const MouseEvent& e);
  43346. /** @internal */
  43347. bool hitTest (int x, int y);
  43348. private:
  43349. WeakReference<Component> component;
  43350. ComponentBoundsConstrainer* constrainer;
  43351. Rectangle<int> originalBounds;
  43352. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  43353. };
  43354. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43355. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  43356. /**
  43357. A base class for top-level windows that can be dragged around and resized.
  43358. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  43359. to give it a component that will remain positioned inside it (leaving a gap around
  43360. the edges for a border).
  43361. It's not advisable to add child components directly to a ResizableWindow: put them
  43362. inside your content component instead. And overriding methods like resized(), moved(), etc
  43363. is also not recommended - instead override these methods for your content component.
  43364. (If for some obscure reason you do need to override these methods, always remember to
  43365. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  43366. decorations correctly).
  43367. By default resizing isn't enabled - use the setResizable() method to enable it and
  43368. to choose the style of resizing to use.
  43369. @see TopLevelWindow
  43370. */
  43371. class JUCE_API ResizableWindow : public TopLevelWindow
  43372. {
  43373. public:
  43374. /** Creates a ResizableWindow.
  43375. This constructor doesn't specify a background colour, so the LookAndFeel's default
  43376. background colour will be used.
  43377. @param name the name to give the component
  43378. @param addToDesktop if true, the window will be automatically added to the
  43379. desktop; if false, you can use it as a child component
  43380. */
  43381. ResizableWindow (const String& name,
  43382. bool addToDesktop);
  43383. /** Creates a ResizableWindow.
  43384. @param name the name to give the component
  43385. @param backgroundColour the colour to use for filling the window's background.
  43386. @param addToDesktop if true, the window will be automatically added to the
  43387. desktop; if false, you can use it as a child component
  43388. */
  43389. ResizableWindow (const String& name,
  43390. const Colour& backgroundColour,
  43391. bool addToDesktop);
  43392. /** Destructor.
  43393. If a content component has been set with setContentOwned(), it will be deleted.
  43394. */
  43395. ~ResizableWindow();
  43396. /** Returns the colour currently being used for the window's background.
  43397. As a convenience the window will fill itself with this colour, but you
  43398. can override the paint() method if you need more customised behaviour.
  43399. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  43400. @see setBackgroundColour
  43401. */
  43402. const Colour getBackgroundColour() const noexcept;
  43403. /** Changes the colour currently being used for the window's background.
  43404. As a convenience the window will fill itself with this colour, but you
  43405. can override the paint() method if you need more customised behaviour.
  43406. Note that the opaque state of this window is altered by this call to reflect
  43407. the opacity of the colour passed-in. On window systems which can't support
  43408. semi-transparent windows this might cause problems, (though it's unlikely you'll
  43409. be using this class as a base for a semi-transparent component anyway).
  43410. You can also use the ResizableWindow::backgroundColourId colour id to set
  43411. this colour.
  43412. @see getBackgroundColour
  43413. */
  43414. void setBackgroundColour (const Colour& newColour);
  43415. /** Make the window resizable or fixed.
  43416. @param shouldBeResizable whether it's resizable at all
  43417. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  43418. bottom-right; if false, it'll use a ResizableBorderComponent
  43419. around the edge
  43420. @see setResizeLimits, isResizable
  43421. */
  43422. void setResizable (bool shouldBeResizable,
  43423. bool useBottomRightCornerResizer);
  43424. /** True if resizing is enabled.
  43425. @see setResizable
  43426. */
  43427. bool isResizable() const noexcept;
  43428. /** This sets the maximum and minimum sizes for the window.
  43429. If the window's current size is outside these limits, it will be resized to
  43430. make sure it's within them.
  43431. Calling setBounds() on the component will bypass any size checking - it's only when
  43432. the window is being resized by the user that these values are enforced.
  43433. @see setResizable, setFixedAspectRatio
  43434. */
  43435. void setResizeLimits (int newMinimumWidth,
  43436. int newMinimumHeight,
  43437. int newMaximumWidth,
  43438. int newMaximumHeight) noexcept;
  43439. /** Returns the bounds constrainer object that this window is using.
  43440. You can access this to change its properties.
  43441. */
  43442. ComponentBoundsConstrainer* getConstrainer() noexcept { return constrainer; }
  43443. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  43444. A pointer to the object you pass in will be kept, but it won't be deleted
  43445. by this object, so it's the caller's responsiblity to manage it.
  43446. If you pass 0, then no contraints will be placed on the positioning of the window.
  43447. */
  43448. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  43449. /** Calls the window's setBounds method, after first checking these bounds
  43450. with the current constrainer.
  43451. @see setConstrainer
  43452. */
  43453. void setBoundsConstrained (const Rectangle<int>& bounds);
  43454. /** Returns true if the window is currently in full-screen mode.
  43455. @see setFullScreen
  43456. */
  43457. bool isFullScreen() const;
  43458. /** Puts the window into full-screen mode, or restores it to its normal size.
  43459. If true, the window will become full-screen; if false, it will return to the
  43460. last size it was before being made full-screen.
  43461. @see isFullScreen
  43462. */
  43463. void setFullScreen (bool shouldBeFullScreen);
  43464. /** Returns true if the window is currently minimised.
  43465. @see setMinimised
  43466. */
  43467. bool isMinimised() const;
  43468. /** Minimises the window, or restores it to its previous position and size.
  43469. When being un-minimised, it'll return to the last position and size it
  43470. was in before being minimised.
  43471. @see isMinimised
  43472. */
  43473. void setMinimised (bool shouldMinimise);
  43474. /** Returns a string which encodes the window's current size and position.
  43475. This string will encapsulate the window's size, position, and whether it's
  43476. in full-screen mode. It's intended for letting your application save and
  43477. restore a window's position.
  43478. Use the restoreWindowStateFromString() to restore from a saved state.
  43479. @see restoreWindowStateFromString
  43480. */
  43481. String getWindowStateAsString();
  43482. /** Restores the window to a previously-saved size and position.
  43483. This restores the window's size, positon and full-screen status from an
  43484. string that was previously created with the getWindowStateAsString()
  43485. method.
  43486. @returns false if the string wasn't a valid window state
  43487. @see getWindowStateAsString
  43488. */
  43489. bool restoreWindowStateFromString (const String& previousState);
  43490. /** Returns the current content component.
  43491. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  43492. has yet been specified.
  43493. @see setContentOwned, setContentNonOwned
  43494. */
  43495. Component* getContentComponent() const noexcept { return contentComponent; }
  43496. /** Changes the current content component.
  43497. This sets a component that will be placed in the centre of the ResizableWindow,
  43498. (leaving a space around the edge for the border).
  43499. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43500. with addChildComponent(). Instead, add them to the content component.
  43501. @param newContentComponent the new component to use - this component will be deleted when it's
  43502. no longer needed (i.e. when the window is deleted or a new content
  43503. component is set for it). To set a component that this window will not
  43504. delete, call setContentNonOwned() instead.
  43505. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43506. such that it always fits around the size of the content component. If false,
  43507. the new content will be resized to fit the current space available.
  43508. */
  43509. void setContentOwned (Component* newContentComponent,
  43510. bool resizeToFitWhenContentChangesSize);
  43511. /** Changes the current content component.
  43512. This sets a component that will be placed in the centre of the ResizableWindow,
  43513. (leaving a space around the edge for the border).
  43514. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43515. with addChildComponent(). Instead, add them to the content component.
  43516. @param newContentComponent the new component to use - this component will NOT be deleted by this
  43517. component, so it's the caller's responsibility to manage its lifetime (it's
  43518. ok to delete it while this window is still using it). To set a content
  43519. component that the window will delete, call setContentOwned() instead.
  43520. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43521. such that it always fits around the size of the content component. If false,
  43522. the new content will be resized to fit the current space available.
  43523. */
  43524. void setContentNonOwned (Component* newContentComponent,
  43525. bool resizeToFitWhenContentChangesSize);
  43526. /** Removes the current content component.
  43527. If the previous content component was added with setContentOwned(), it will also be deleted. If
  43528. it was added with setContentNonOwned(), it will simply be removed from this component.
  43529. */
  43530. void clearContentComponent();
  43531. /** Changes the window so that the content component ends up with the specified size.
  43532. This is basically a setSize call on the window, but which adds on the borders,
  43533. so you can specify the content component's target size.
  43534. */
  43535. void setContentComponentSize (int width, int height);
  43536. /** Returns the width of the frame to use around the window.
  43537. @see getContentComponentBorder
  43538. */
  43539. virtual const BorderSize<int> getBorderThickness();
  43540. /** Returns the insets to use when positioning the content component.
  43541. @see getBorderThickness
  43542. */
  43543. virtual const BorderSize<int> getContentComponentBorder();
  43544. /** A set of colour IDs to use to change the colour of various aspects of the window.
  43545. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43546. methods.
  43547. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43548. */
  43549. enum ColourIds
  43550. {
  43551. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  43552. };
  43553. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  43554. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  43555. bool deleteOldOne = true,
  43556. bool resizeToFit = false));
  43557. protected:
  43558. /** @internal */
  43559. void paint (Graphics& g);
  43560. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43561. void moved();
  43562. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43563. void resized();
  43564. /** @internal */
  43565. void mouseDown (const MouseEvent& e);
  43566. /** @internal */
  43567. void mouseDrag (const MouseEvent& e);
  43568. /** @internal */
  43569. void lookAndFeelChanged();
  43570. /** @internal */
  43571. void childBoundsChanged (Component* child);
  43572. /** @internal */
  43573. void parentSizeChanged();
  43574. /** @internal */
  43575. void visibilityChanged();
  43576. /** @internal */
  43577. void activeWindowStatusChanged();
  43578. /** @internal */
  43579. int getDesktopWindowStyleFlags() const;
  43580. #if JUCE_DEBUG
  43581. /** Overridden to warn people about adding components directly to this component
  43582. instead of using setContentOwned().
  43583. If you know what you're doing and are sure you really want to add a component, specify
  43584. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43585. */
  43586. void addChildComponent (Component* child, int zOrder = -1);
  43587. /** Overridden to warn people about adding components directly to this component
  43588. instead of using setContentOwned().
  43589. If you know what you're doing and are sure you really want to add a component, specify
  43590. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43591. */
  43592. void addAndMakeVisible (Component* child, int zOrder = -1);
  43593. #endif
  43594. ScopedPointer <ResizableCornerComponent> resizableCorner;
  43595. ScopedPointer <ResizableBorderComponent> resizableBorder;
  43596. private:
  43597. Component::SafePointer <Component> contentComponent;
  43598. bool ownsContentComponent, resizeToFitContent, fullscreen;
  43599. ComponentDragger dragger;
  43600. Rectangle<int> lastNonFullScreenPos;
  43601. ComponentBoundsConstrainer defaultConstrainer;
  43602. ComponentBoundsConstrainer* constrainer;
  43603. #if JUCE_DEBUG
  43604. bool hasBeenResized;
  43605. #endif
  43606. void initialise (bool addToDesktop);
  43607. void updateLastPos();
  43608. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  43609. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  43610. // The parameters for these methods have changed - please update your code!
  43611. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  43612. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  43613. #endif
  43614. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  43615. };
  43616. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43617. /*** End of inlined file: juce_ResizableWindow.h ***/
  43618. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  43619. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43620. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43621. /**
  43622. A glyph from a particular font, with a particular size, style,
  43623. typeface and position.
  43624. You should rarely need to use this class directly - for most purposes, the
  43625. GlyphArrangement class will do what you need for text layout.
  43626. @see GlyphArrangement, Font
  43627. */
  43628. class JUCE_API PositionedGlyph
  43629. {
  43630. public:
  43631. PositionedGlyph (const Font& font, juce_wchar character, int glyphNumber,
  43632. float anchorX, float baselineY, float width, bool isWhitespace);
  43633. PositionedGlyph (const PositionedGlyph& other);
  43634. PositionedGlyph& operator= (const PositionedGlyph& other);
  43635. ~PositionedGlyph();
  43636. /** Returns the character the glyph represents. */
  43637. juce_wchar getCharacter() const noexcept { return character; }
  43638. /** Checks whether the glyph is actually empty. */
  43639. bool isWhitespace() const noexcept { return whitespace; }
  43640. /** Returns the position of the glyph's left-hand edge. */
  43641. float getLeft() const noexcept { return x; }
  43642. /** Returns the position of the glyph's right-hand edge. */
  43643. float getRight() const noexcept { return x + w; }
  43644. /** Returns the y position of the glyph's baseline. */
  43645. float getBaselineY() const noexcept { return y; }
  43646. /** Returns the y position of the top of the glyph. */
  43647. float getTop() const { return y - font.getAscent(); }
  43648. /** Returns the y position of the bottom of the glyph. */
  43649. float getBottom() const { return y + font.getDescent(); }
  43650. /** Returns the bounds of the glyph. */
  43651. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  43652. /** Shifts the glyph's position by a relative amount. */
  43653. void moveBy (float deltaX, float deltaY);
  43654. /** Draws the glyph into a graphics context. */
  43655. void draw (const Graphics& g) const;
  43656. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  43657. void draw (const Graphics& g, const AffineTransform& transform) const;
  43658. /** Returns the path for this glyph.
  43659. @param path the glyph's outline will be appended to this path
  43660. */
  43661. void createPath (Path& path) const;
  43662. /** Checks to see if a point lies within this glyph. */
  43663. bool hitTest (float x, float y) const;
  43664. private:
  43665. friend class GlyphArrangement;
  43666. Font font;
  43667. juce_wchar character;
  43668. int glyph;
  43669. float x, y, w;
  43670. bool whitespace;
  43671. JUCE_LEAK_DETECTOR (PositionedGlyph);
  43672. };
  43673. /**
  43674. A set of glyphs, each with a position.
  43675. You can create a GlyphArrangement, text to it and then draw it onto a
  43676. graphics context. It's used internally by the text methods in the
  43677. Graphics class, but can be used directly if more control is needed.
  43678. @see Font, PositionedGlyph
  43679. */
  43680. class JUCE_API GlyphArrangement
  43681. {
  43682. public:
  43683. /** Creates an empty arrangement. */
  43684. GlyphArrangement();
  43685. /** Takes a copy of another arrangement. */
  43686. GlyphArrangement (const GlyphArrangement& other);
  43687. /** Copies another arrangement onto this one.
  43688. To add another arrangement without clearing this one, use addGlyphArrangement().
  43689. */
  43690. GlyphArrangement& operator= (const GlyphArrangement& other);
  43691. /** Destructor. */
  43692. ~GlyphArrangement();
  43693. /** Returns the total number of glyphs in the arrangement. */
  43694. int getNumGlyphs() const noexcept { return glyphs.size(); }
  43695. /** Returns one of the glyphs from the arrangement.
  43696. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  43697. careful not to pass an out-of-range index here, as it
  43698. doesn't do any bounds-checking.
  43699. */
  43700. PositionedGlyph& getGlyph (int index) const;
  43701. /** Clears all text from the arrangement and resets it.
  43702. */
  43703. void clear();
  43704. /** Appends a line of text to the arrangement.
  43705. This will add the text as a single line, where x is the left-hand edge of the
  43706. first character, and y is the position for the text's baseline.
  43707. If the text contains new-lines or carriage-returns, this will ignore them - use
  43708. addJustifiedText() to add multi-line arrangements.
  43709. */
  43710. void addLineOfText (const Font& font,
  43711. const String& text,
  43712. float x, float y);
  43713. /** Adds a line of text, truncating it if it's wider than a specified size.
  43714. This is the same as addLineOfText(), but if the line's width exceeds the value
  43715. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  43716. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  43717. */
  43718. void addCurtailedLineOfText (const Font& font,
  43719. const String& text,
  43720. float x, float y,
  43721. float maxWidthPixels,
  43722. bool useEllipsis);
  43723. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  43724. This will add text to the arrangement, breaking it into new lines either where there
  43725. is a new-line or carriage-return character in the text, or where a line's width
  43726. exceeds the value set in maxLineWidth.
  43727. Each line that is added will be laid out using the flags set in horizontalLayout, so
  43728. the lines can be left- or right-justified, or centred horizontally in the space
  43729. between x and (x + maxLineWidth).
  43730. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  43731. lines will be placed below it, separated by a distance of font.getHeight().
  43732. */
  43733. void addJustifiedText (const Font& font,
  43734. const String& text,
  43735. float x, float y,
  43736. float maxLineWidth,
  43737. const Justification& horizontalLayout);
  43738. /** Tries to fit some text withing a given space.
  43739. This does its best to make the given text readable within the specified rectangle,
  43740. so it useful for labelling things.
  43741. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  43742. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  43743. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  43744. it's been truncated.
  43745. A Justification parameter lets you specify how the text is laid out within the rectangle,
  43746. both horizontally and vertically.
  43747. @see Graphics::drawFittedText
  43748. */
  43749. void addFittedText (const Font& font,
  43750. const String& text,
  43751. float x, float y, float width, float height,
  43752. const Justification& layout,
  43753. int maximumLinesToUse,
  43754. float minimumHorizontalScale = 0.7f);
  43755. /** Appends another glyph arrangement to this one. */
  43756. void addGlyphArrangement (const GlyphArrangement& other);
  43757. /** Appends a custom glyph to the arrangement. */
  43758. void addGlyph (const PositionedGlyph& glyph);
  43759. /** Draws this glyph arrangement to a graphics context.
  43760. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  43761. method, which renders the glyphs as filled vectors.
  43762. */
  43763. void draw (const Graphics& g) const;
  43764. /** Draws this glyph arrangement to a graphics context.
  43765. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  43766. method for non-transformed arrangements.
  43767. */
  43768. void draw (const Graphics& g, const AffineTransform& transform) const;
  43769. /** Converts the set of glyphs into a path.
  43770. @param path the glyphs' outlines will be appended to this path
  43771. */
  43772. void createPath (Path& path) const;
  43773. /** Looks for a glyph that contains the given co-ordinate.
  43774. @returns the index of the glyph, or -1 if none were found.
  43775. */
  43776. int findGlyphIndexAt (float x, float y) const;
  43777. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  43778. @param startIndex the first glyph to test
  43779. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  43780. startIndex will be included
  43781. @param includeWhitespace if true, the extent of any whitespace characters will also
  43782. be taken into account
  43783. */
  43784. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  43785. /** Shifts a set of glyphs by a given amount.
  43786. @param startIndex the first glyph to transform
  43787. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  43788. startIndex will be used
  43789. @param deltaX the amount to add to their x-positions
  43790. @param deltaY the amount to add to their y-positions
  43791. */
  43792. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  43793. float deltaX, float deltaY);
  43794. /** Removes a set of glyphs from the arrangement.
  43795. @param startIndex the first glyph to remove
  43796. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  43797. startIndex will be deleted
  43798. */
  43799. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  43800. /** Expands or compresses a set of glyphs horizontally.
  43801. @param startIndex the first glyph to transform
  43802. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  43803. startIndex will be used
  43804. @param horizontalScaleFactor how much to scale their horizontal width by
  43805. */
  43806. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  43807. float horizontalScaleFactor);
  43808. /** Justifies a set of glyphs within a given space.
  43809. This moves the glyphs as a block so that the whole thing is located within the
  43810. given rectangle with the specified layout.
  43811. If the Justification::horizontallyJustified flag is specified, each line will
  43812. be stretched out to fill the specified width.
  43813. */
  43814. void justifyGlyphs (int startIndex, int numGlyphs,
  43815. float x, float y, float width, float height,
  43816. const Justification& justification);
  43817. private:
  43818. OwnedArray <PositionedGlyph> glyphs;
  43819. int insertEllipsis (const Font&, float maxXPos, int startIndex, int endIndex);
  43820. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font&,
  43821. const Justification&, float minimumHorizontalScale);
  43822. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  43823. JUCE_LEAK_DETECTOR (GlyphArrangement);
  43824. };
  43825. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43826. /*** End of inlined file: juce_GlyphArrangement.h ***/
  43827. /*** Start of inlined file: juce_AlertWindow.h ***/
  43828. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43829. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  43830. /*** Start of inlined file: juce_TextLayout.h ***/
  43831. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  43832. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  43833. class Graphics;
  43834. /**
  43835. A laid-out arrangement of text.
  43836. You can add text in different fonts to a TextLayout object, then call its
  43837. layout() method to word-wrap it into lines. The layout can then be drawn
  43838. using a graphics context.
  43839. It's handy if you've got a message to display, because you can format it,
  43840. measure the extent of the layout, and then create a suitably-sized window
  43841. to show it in.
  43842. @see Font, Graphics::drawFittedText, GlyphArrangement
  43843. */
  43844. class JUCE_API TextLayout
  43845. {
  43846. public:
  43847. /** Creates an empty text layout.
  43848. Text can then be appended using the appendText() method.
  43849. */
  43850. TextLayout();
  43851. /** Creates a copy of another layout object. */
  43852. TextLayout (const TextLayout& other);
  43853. /** Creates a text layout from an initial string and font. */
  43854. TextLayout (const String& text, const Font& font);
  43855. /** Destructor. */
  43856. ~TextLayout();
  43857. /** Copies another layout onto this one. */
  43858. TextLayout& operator= (const TextLayout& layoutToCopy);
  43859. /** Clears the layout, removing all its text. */
  43860. void clear();
  43861. /** Adds a string to the end of the arrangement.
  43862. The string will be broken onto new lines wherever it contains
  43863. carriage-returns or linefeeds. After adding it, you can call layout()
  43864. to wrap long lines into a paragraph and justify it.
  43865. */
  43866. void appendText (const String& textToAppend,
  43867. const Font& fontToUse);
  43868. /** Replaces all the text with a new string.
  43869. This is equivalent to calling clear() followed by appendText().
  43870. */
  43871. void setText (const String& newText,
  43872. const Font& fontToUse);
  43873. /** Returns true if the layout has not had any text added yet. */
  43874. bool isEmpty() const;
  43875. /** Breaks the text up to form a paragraph with the given width.
  43876. @param maximumWidth any text wider than this will be split
  43877. across multiple lines
  43878. @param justification how the lines are to be laid-out horizontally
  43879. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  43880. width that keeps all the lines of text at a
  43881. similar length - this is good when you're displaying
  43882. a short message and don't want it to get split
  43883. onto two lines with only a couple of words on
  43884. the second line, which looks untidy.
  43885. */
  43886. void layout (int maximumWidth,
  43887. const Justification& justification,
  43888. bool attemptToBalanceLineLengths);
  43889. /** Returns the overall width of the entire text layout. */
  43890. int getWidth() const;
  43891. /** Returns the overall height of the entire text layout. */
  43892. int getHeight() const;
  43893. /** Returns the total number of lines of text. */
  43894. int getNumLines() const { return totalLines; }
  43895. /** Returns the width of a particular line of text.
  43896. @param lineNumber the line, from 0 to (getNumLines() - 1)
  43897. */
  43898. int getLineWidth (int lineNumber) const;
  43899. /** Renders the text at a specified position using a graphics context.
  43900. */
  43901. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  43902. /** Renders the text within a specified rectangle using a graphics context.
  43903. The justification flags dictate how the block of text should be positioned
  43904. within the rectangle.
  43905. */
  43906. void drawWithin (Graphics& g,
  43907. int x, int y, int w, int h,
  43908. const Justification& layoutFlags) const;
  43909. private:
  43910. class Token;
  43911. friend class OwnedArray <Token>;
  43912. OwnedArray <Token> tokens;
  43913. int totalLines;
  43914. JUCE_LEAK_DETECTOR (TextLayout);
  43915. };
  43916. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  43917. /*** End of inlined file: juce_TextLayout.h ***/
  43918. /** A window that displays a message and has buttons for the user to react to it.
  43919. For simple dialog boxes with just a couple of buttons on them, there are
  43920. some static methods for running these.
  43921. For more complex dialogs, an AlertWindow can be created, then it can have some
  43922. buttons and components added to it, and its runModalLoop() method is then used to
  43923. show it. The value returned by runModalLoop() shows which button the
  43924. user pressed to dismiss the box.
  43925. @see ThreadWithProgressWindow
  43926. */
  43927. class JUCE_API AlertWindow : public TopLevelWindow,
  43928. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43929. {
  43930. public:
  43931. /** The type of icon to show in the dialog box. */
  43932. enum AlertIconType
  43933. {
  43934. NoIcon, /**< No icon will be shown on the dialog box. */
  43935. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  43936. user to answer a question. */
  43937. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  43938. warning about something and shouldn't be ignored. */
  43939. InfoIcon /**< An icon that indicates that the dialog box is just
  43940. giving the user some information, which doesn't require
  43941. a response from them. */
  43942. };
  43943. /** Creates an AlertWindow.
  43944. @param title the headline to show at the top of the dialog box
  43945. @param message a longer, more descriptive message to show underneath the
  43946. headline
  43947. @param iconType the type of icon to display
  43948. @param associatedComponent if this is non-null, it specifies the component that the
  43949. alert window should be associated with. Depending on the look
  43950. and feel, this might be used for positioning of the alert window.
  43951. */
  43952. AlertWindow (const String& title,
  43953. const String& message,
  43954. AlertIconType iconType,
  43955. Component* associatedComponent = nullptr);
  43956. /** Destroys the AlertWindow */
  43957. ~AlertWindow();
  43958. /** Returns the type of alert icon that was specified when the window
  43959. was created. */
  43960. AlertIconType getAlertType() const noexcept { return alertIconType; }
  43961. /** Changes the dialog box's message.
  43962. This will also resize the window to fit the new message if required.
  43963. */
  43964. void setMessage (const String& message);
  43965. /** Adds a button to the window.
  43966. @param name the text to show on the button
  43967. @param returnValue the value that should be returned from runModalLoop()
  43968. if this is the button that the user presses.
  43969. @param shortcutKey1 an optional key that can be pressed to trigger this button
  43970. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  43971. */
  43972. void addButton (const String& name,
  43973. int returnValue,
  43974. const KeyPress& shortcutKey1 = KeyPress(),
  43975. const KeyPress& shortcutKey2 = KeyPress());
  43976. /** Returns the number of buttons that the window currently has. */
  43977. int getNumButtons() const;
  43978. /** Invokes a click of one of the buttons. */
  43979. void triggerButtonClick (const String& buttonName);
  43980. /** Adds a textbox to the window for entering strings.
  43981. @param name an internal name for the text-box. This is the name to pass to
  43982. the getTextEditorContents() method to find out what the
  43983. user typed-in.
  43984. @param initialContents a string to show in the text box when it's first shown
  43985. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43986. text-box to label it.
  43987. @param isPasswordBox if true, the text editor will display asterisks instead of
  43988. the actual text
  43989. @see getTextEditorContents
  43990. */
  43991. void addTextEditor (const String& name,
  43992. const String& initialContents,
  43993. const String& onScreenLabel = String::empty,
  43994. bool isPasswordBox = false);
  43995. /** Returns the contents of a named textbox.
  43996. After showing an AlertWindow that contains a text editor, this can be
  43997. used to find out what the user has typed into it.
  43998. @param nameOfTextEditor the name of the text box that you're interested in
  43999. @see addTextEditor
  44000. */
  44001. String getTextEditorContents (const String& nameOfTextEditor) const;
  44002. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  44003. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  44004. /** Adds a drop-down list of choices to the box.
  44005. After the box has been shown, the getComboBoxComponent() method can
  44006. be used to find out which item the user picked.
  44007. @param name the label to use for the drop-down list
  44008. @param items the list of items to show in it
  44009. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44010. combo-box to label it.
  44011. @see getComboBoxComponent
  44012. */
  44013. void addComboBox (const String& name,
  44014. const StringArray& items,
  44015. const String& onScreenLabel = String::empty);
  44016. /** Returns a drop-down list that was added to the AlertWindow.
  44017. @param nameOfList the name that was passed into the addComboBox() method
  44018. when creating the drop-down
  44019. @returns the ComboBox component, or 0 if none was found for the given name.
  44020. */
  44021. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  44022. /** Adds a block of text.
  44023. This is handy for adding a multi-line note next to a textbox or combo-box,
  44024. to provide more details about what's going on.
  44025. */
  44026. void addTextBlock (const String& text);
  44027. /** Adds a progress-bar to the window.
  44028. @param progressValue a variable that will be repeatedly checked while the
  44029. dialog box is visible, to see how far the process has
  44030. got. The value should be in the range 0 to 1.0
  44031. */
  44032. void addProgressBarComponent (double& progressValue);
  44033. /** Adds a user-defined component to the dialog box.
  44034. @param component the component to add - its size should be set up correctly
  44035. before it is passed in. The caller is responsible for deleting
  44036. the component later on - the AlertWindow won't delete it.
  44037. */
  44038. void addCustomComponent (Component* component);
  44039. /** Returns the number of custom components in the dialog box.
  44040. @see getCustomComponent, addCustomComponent
  44041. */
  44042. int getNumCustomComponents() const;
  44043. /** Returns one of the custom components in the dialog box.
  44044. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44045. will return 0
  44046. @see getNumCustomComponents, addCustomComponent
  44047. */
  44048. Component* getCustomComponent (int index) const;
  44049. /** Removes one of the custom components in the dialog box.
  44050. Note that this won't delete it, it just removes the component from the window
  44051. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44052. will return 0
  44053. @returns the component that was removed (or null)
  44054. @see getNumCustomComponents, addCustomComponent
  44055. */
  44056. Component* removeCustomComponent (int index);
  44057. /** Returns true if the window contains any components other than just buttons.*/
  44058. bool containsAnyExtraComponents() const;
  44059. // easy-to-use message box functions:
  44060. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44061. If the callback parameter is null, the box is shown modally, and the method will
  44062. block until the user has clicked the button (or pressed the escape or return keys).
  44063. If the callback parameter is non-null, the box will be displayed and placed into a
  44064. modal state, but this method will return immediately, and the callback will be invoked
  44065. later when the user dismisses the box.
  44066. @param iconType the type of icon to show
  44067. @param title the headline to show at the top of the box
  44068. @param message a longer, more descriptive message to show underneath the
  44069. headline
  44070. @param buttonText the text to show in the button - if this string is empty, the
  44071. default string "ok" (or a localised version) will be used.
  44072. @param associatedComponent if this is non-null, it specifies the component that the
  44073. alert window should be associated with. Depending on the look
  44074. and feel, this might be used for positioning of the alert window.
  44075. */
  44076. #if JUCE_MODAL_LOOPS_PERMITTED
  44077. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  44078. const String& title,
  44079. const String& message,
  44080. const String& buttonText = String::empty,
  44081. Component* associatedComponent = nullptr);
  44082. #endif
  44083. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44084. If the callback parameter is null, the box is shown modally, and the method will
  44085. block until the user has clicked the button (or pressed the escape or return keys).
  44086. If the callback parameter is non-null, the box will be displayed and placed into a
  44087. modal state, but this method will return immediately, and the callback will be invoked
  44088. later when the user dismisses the box.
  44089. @param iconType the type of icon to show
  44090. @param title the headline to show at the top of the box
  44091. @param message a longer, more descriptive message to show underneath the
  44092. headline
  44093. @param buttonText the text to show in the button - if this string is empty, the
  44094. default string "ok" (or a localised version) will be used.
  44095. @param associatedComponent if this is non-null, it specifies the component that the
  44096. alert window should be associated with. Depending on the look
  44097. and feel, this might be used for positioning of the alert window.
  44098. */
  44099. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  44100. const String& title,
  44101. const String& message,
  44102. const String& buttonText = String::empty,
  44103. Component* associatedComponent = nullptr);
  44104. /** Shows a dialog box with two buttons.
  44105. Ideal for ok/cancel or yes/no choices. The return key can also be used
  44106. to trigger the first button, and the escape key for the second button.
  44107. If the callback parameter is null, the box is shown modally, and the method will
  44108. block until the user has clicked the button (or pressed the escape or return keys).
  44109. If the callback parameter is non-null, the box will be displayed and placed into a
  44110. modal state, but this method will return immediately, and the callback will be invoked
  44111. later when the user dismisses the box.
  44112. @param iconType the type of icon to show
  44113. @param title the headline to show at the top of the box
  44114. @param message a longer, more descriptive message to show underneath the
  44115. headline
  44116. @param button1Text the text to show in the first button - if this string is
  44117. empty, the default string "ok" (or a localised version of it)
  44118. will be used.
  44119. @param button2Text the text to show in the second button - if this string is
  44120. empty, the default string "cancel" (or a localised version of it)
  44121. will be used.
  44122. @param associatedComponent if this is non-null, it specifies the component that the
  44123. alert window should be associated with. Depending on the look
  44124. and feel, this might be used for positioning of the alert window.
  44125. @param callback if this is non-null, the menu will be launched asynchronously,
  44126. returning immediately, and the callback will receive a call to its
  44127. modalStateFinished() when the box is dismissed, with its parameter
  44128. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  44129. will be owned and deleted by the system, so make sure that it works
  44130. safely and doesn't keep any references to objects that might be deleted
  44131. before it gets called.
  44132. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  44133. is not null, the method always returns false, and the user's choice is delivered
  44134. later by the callback.
  44135. */
  44136. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  44137. const String& title,
  44138. const String& message,
  44139. #if JUCE_MODAL_LOOPS_PERMITTED
  44140. const String& button1Text = String::empty,
  44141. const String& button2Text = String::empty,
  44142. Component* associatedComponent = nullptr,
  44143. ModalComponentManager::Callback* callback = nullptr);
  44144. #else
  44145. const String& button1Text,
  44146. const String& button2Text,
  44147. Component* associatedComponent,
  44148. ModalComponentManager::Callback* callback);
  44149. #endif
  44150. /** Shows a dialog box with three buttons.
  44151. Ideal for yes/no/cancel boxes.
  44152. The escape key can be used to trigger the third button.
  44153. If the callback parameter is null, the box is shown modally, and the method will
  44154. block until the user has clicked the button (or pressed the escape or return keys).
  44155. If the callback parameter is non-null, the box will be displayed and placed into a
  44156. modal state, but this method will return immediately, and the callback will be invoked
  44157. later when the user dismisses the box.
  44158. @param iconType the type of icon to show
  44159. @param title the headline to show at the top of the box
  44160. @param message a longer, more descriptive message to show underneath the
  44161. headline
  44162. @param button1Text the text to show in the first button - if an empty string, then
  44163. "yes" will be used (or a localised version of it)
  44164. @param button2Text the text to show in the first button - if an empty string, then
  44165. "no" will be used (or a localised version of it)
  44166. @param button3Text the text to show in the first button - if an empty string, then
  44167. "cancel" will be used (or a localised version of it)
  44168. @param associatedComponent if this is non-null, it specifies the component that the
  44169. alert window should be associated with. Depending on the look
  44170. and feel, this might be used for positioning of the alert window.
  44171. @param callback if this is non-null, the menu will be launched asynchronously,
  44172. returning immediately, and the callback will receive a call to its
  44173. modalStateFinished() when the box is dismissed, with its parameter
  44174. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  44175. if it was cancelled, The callback object will be owned and deleted by the
  44176. system, so make sure that it works safely and doesn't keep any references
  44177. to objects that might be deleted before it gets called.
  44178. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  44179. returns one of the following values:
  44180. - 0 if the third button was pressed (normally used for 'cancel')
  44181. - 1 if the first button was pressed (normally used for 'yes')
  44182. - 2 if the middle button was pressed (normally used for 'no')
  44183. */
  44184. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  44185. const String& title,
  44186. const String& message,
  44187. #if JUCE_MODAL_LOOPS_PERMITTED
  44188. const String& button1Text = String::empty,
  44189. const String& button2Text = String::empty,
  44190. const String& button3Text = String::empty,
  44191. Component* associatedComponent = nullptr,
  44192. ModalComponentManager::Callback* callback = nullptr);
  44193. #else
  44194. const String& button1Text,
  44195. const String& button2Text,
  44196. const String& button3Text,
  44197. Component* associatedComponent,
  44198. ModalComponentManager::Callback* callback);
  44199. #endif
  44200. /** Shows an operating-system native dialog box.
  44201. @param title the title to use at the top
  44202. @param bodyText the longer message to show
  44203. @param isOkCancel if true, this will show an ok/cancel box, if false,
  44204. it'll show a box with just an ok button
  44205. @returns true if the ok button was pressed, false if they pressed cancel.
  44206. */
  44207. #if JUCE_MODAL_LOOPS_PERMITTED
  44208. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  44209. const String& bodyText,
  44210. bool isOkCancel);
  44211. #endif
  44212. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  44213. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44214. methods.
  44215. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44216. */
  44217. enum ColourIds
  44218. {
  44219. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  44220. textColourId = 0x1001810, /**< The colour for the text. */
  44221. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  44222. };
  44223. protected:
  44224. /** @internal */
  44225. void paint (Graphics& g);
  44226. /** @internal */
  44227. void mouseDown (const MouseEvent& e);
  44228. /** @internal */
  44229. void mouseDrag (const MouseEvent& e);
  44230. /** @internal */
  44231. bool keyPressed (const KeyPress& key);
  44232. /** @internal */
  44233. void buttonClicked (Button* button);
  44234. /** @internal */
  44235. void lookAndFeelChanged();
  44236. /** @internal */
  44237. void userTriedToCloseWindow();
  44238. /** @internal */
  44239. int getDesktopWindowStyleFlags() const;
  44240. private:
  44241. String text;
  44242. TextLayout textLayout;
  44243. AlertIconType alertIconType;
  44244. ComponentBoundsConstrainer constrainer;
  44245. ComponentDragger dragger;
  44246. Rectangle<int> textArea;
  44247. OwnedArray<TextButton> buttons;
  44248. OwnedArray<TextEditor> textBoxes;
  44249. OwnedArray<ComboBox> comboBoxes;
  44250. OwnedArray<ProgressBar> progressBars;
  44251. Array<Component*> customComps;
  44252. OwnedArray<Component> textBlocks;
  44253. Array<Component*> allComps;
  44254. StringArray textboxNames, comboBoxNames;
  44255. Font font;
  44256. Component* associatedComponent;
  44257. void updateLayout (bool onlyIncreaseSize);
  44258. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  44259. };
  44260. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  44261. /*** End of inlined file: juce_AlertWindow.h ***/
  44262. /**
  44263. A file open/save dialog box.
  44264. This is a Juce-based file dialog box; to use a native file chooser, see the
  44265. FileChooser class.
  44266. To use one of these, create it and call its show() method. e.g.
  44267. @code
  44268. {
  44269. WildcardFileFilter wildcardFilter ("*.foo", String::empty, "Foo files");
  44270. FileBrowserComponent browser (FileBrowserComponent::canSelectFiles,
  44271. File::nonexistent,
  44272. &wildcardFilter,
  44273. nullptr);
  44274. FileChooserDialogBox dialogBox ("Open some kind of file",
  44275. "Please choose some kind of file that you want to open...",
  44276. browser,
  44277. false,
  44278. Colours::lightgrey);
  44279. if (dialogBox.show())
  44280. {
  44281. File selectedFile = browser.getSelectedFile (0);
  44282. ...etc..
  44283. }
  44284. }
  44285. @endcode
  44286. @see FileChooser
  44287. */
  44288. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  44289. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44290. public FileBrowserListener
  44291. {
  44292. public:
  44293. /** Creates a file chooser box.
  44294. @param title the main title to show at the top of the box
  44295. @param instructions an optional longer piece of text to show below the title in
  44296. a smaller font, describing in more detail what's required.
  44297. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  44298. box. Make sure you delete this after (but not before!) the
  44299. dialog box has been deleted.
  44300. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  44301. if they try to select a file that already exists. (This
  44302. flag is only used when saving files)
  44303. @param backgroundColour the background colour for the top level window
  44304. @see FileBrowserComponent, FilePreviewComponent
  44305. */
  44306. FileChooserDialogBox (const String& title,
  44307. const String& instructions,
  44308. FileBrowserComponent& browserComponent,
  44309. bool warnAboutOverwritingExistingFiles,
  44310. const Colour& backgroundColour);
  44311. /** Destructor. */
  44312. ~FileChooserDialogBox();
  44313. #if JUCE_MODAL_LOOPS_PERMITTED
  44314. /** Displays and runs the dialog box modally.
  44315. This will show the box with the specified size, returning true if the user
  44316. pressed 'ok', or false if they cancelled.
  44317. Leave the width or height as 0 to use the default size
  44318. */
  44319. bool show (int width = 0, int height = 0);
  44320. /** Displays and runs the dialog box modally.
  44321. This will show the box with the specified size at the specified location,
  44322. returning true if the user pressed 'ok', or false if they cancelled.
  44323. Leave the width or height as 0 to use the default size.
  44324. */
  44325. bool showAt (int x, int y, int width, int height);
  44326. #endif
  44327. /** Sets the size of this dialog box to its default and positions it either in the
  44328. centre of the screen, or centred around a component that is provided.
  44329. */
  44330. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  44331. /** A set of colour IDs to use to change the colour of various aspects of the box.
  44332. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44333. methods.
  44334. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44335. */
  44336. enum ColourIds
  44337. {
  44338. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  44339. };
  44340. /** @internal */
  44341. void buttonClicked (Button* button);
  44342. /** @internal */
  44343. void closeButtonPressed();
  44344. /** @internal */
  44345. void selectionChanged();
  44346. /** @internal */
  44347. void fileClicked (const File& file, const MouseEvent& e);
  44348. /** @internal */
  44349. void fileDoubleClicked (const File& file);
  44350. private:
  44351. class ContentComponent;
  44352. ContentComponent* content;
  44353. const bool warnAboutOverwritingExistingFiles;
  44354. void okButtonPressed();
  44355. void createNewFolder();
  44356. void createNewFolderConfirmed (const String& name);
  44357. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  44358. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  44359. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  44360. };
  44361. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  44362. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  44363. #endif
  44364. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  44365. #endif
  44366. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44367. /*** Start of inlined file: juce_FileListComponent.h ***/
  44368. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44369. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44370. /**
  44371. A component that displays the files in a directory as a listbox.
  44372. This implements the DirectoryContentsDisplayComponent base class so that
  44373. it can be used in a FileBrowserComponent.
  44374. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44375. class and the FileBrowserListener class.
  44376. @see DirectoryContentsList, FileTreeComponent
  44377. */
  44378. class JUCE_API FileListComponent : public ListBox,
  44379. public DirectoryContentsDisplayComponent,
  44380. private ListBoxModel,
  44381. private ChangeListener
  44382. {
  44383. public:
  44384. /** Creates a listbox to show the contents of a specified directory.
  44385. */
  44386. FileListComponent (DirectoryContentsList& listToShow);
  44387. /** Destructor. */
  44388. ~FileListComponent();
  44389. /** Returns the number of files the user has got selected.
  44390. @see getSelectedFile
  44391. */
  44392. int getNumSelectedFiles() const;
  44393. /** Returns one of the files that the user has currently selected.
  44394. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44395. @see getNumSelectedFiles
  44396. */
  44397. const File getSelectedFile (int index = 0) const;
  44398. /** Deselects any files that are currently selected. */
  44399. void deselectAllFiles();
  44400. /** Scrolls to the top of the list. */
  44401. void scrollToTop();
  44402. /** @internal */
  44403. void changeListenerCallback (ChangeBroadcaster*);
  44404. /** @internal */
  44405. int getNumRows();
  44406. /** @internal */
  44407. void paintListBoxItem (int, Graphics&, int, int, bool);
  44408. /** @internal */
  44409. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  44410. /** @internal */
  44411. void selectedRowsChanged (int lastRowSelected);
  44412. /** @internal */
  44413. void deleteKeyPressed (int currentSelectedRow);
  44414. /** @internal */
  44415. void returnKeyPressed (int currentSelectedRow);
  44416. private:
  44417. File lastDirectory;
  44418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  44419. };
  44420. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44421. /*** End of inlined file: juce_FileListComponent.h ***/
  44422. #endif
  44423. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44424. /*** Start of inlined file: juce_FilenameComponent.h ***/
  44425. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44426. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44427. class FilenameComponent;
  44428. /**
  44429. Listens for events happening to a FilenameComponent.
  44430. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  44431. register one of these objects for event callbacks when the filename is changed.
  44432. @see FilenameComponent
  44433. */
  44434. class JUCE_API FilenameComponentListener
  44435. {
  44436. public:
  44437. /** Destructor. */
  44438. virtual ~FilenameComponentListener() {}
  44439. /** This method is called after the FilenameComponent's file has been changed. */
  44440. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  44441. };
  44442. /**
  44443. Shows a filename as an editable text box, with a 'browse' button and a
  44444. drop-down list for recently selected files.
  44445. A handy component for dialogue boxes where you want the user to be able to
  44446. select a file or directory.
  44447. Attach an FilenameComponentListener using the addListener() method, and it will
  44448. get called each time the user changes the filename, either by browsing for a file
  44449. and clicking 'ok', or by typing a new filename into the box and pressing return.
  44450. @see FileChooser, ComboBox
  44451. */
  44452. class JUCE_API FilenameComponent : public Component,
  44453. public SettableTooltipClient,
  44454. public FileDragAndDropTarget,
  44455. private AsyncUpdater,
  44456. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44457. private ComboBoxListener
  44458. {
  44459. public:
  44460. /** Creates a FilenameComponent.
  44461. @param name the name for this component.
  44462. @param currentFile the file to initially show in the box
  44463. @param canEditFilename if true, the user can manually edit the filename; if false,
  44464. they can only change it by browsing for a new file
  44465. @param isDirectory if true, the file will be treated as a directory, and
  44466. an appropriate directory browser used
  44467. @param isForSaving if true, the file browser will allow non-existent files to
  44468. be picked, as the file is assumed to be used for saving rather
  44469. than loading
  44470. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  44471. If an empty string is passed in, then the pattern is assumed to be "*"
  44472. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  44473. to any filenames that are entered or chosen
  44474. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  44475. will only appear if the initial file isn't valid)
  44476. */
  44477. FilenameComponent (const String& name,
  44478. const File& currentFile,
  44479. bool canEditFilename,
  44480. bool isDirectory,
  44481. bool isForSaving,
  44482. const String& fileBrowserWildcard,
  44483. const String& enforcedSuffix,
  44484. const String& textWhenNothingSelected);
  44485. /** Destructor. */
  44486. ~FilenameComponent();
  44487. /** Returns the currently displayed filename. */
  44488. File getCurrentFile() const;
  44489. /** Changes the current filename.
  44490. If addToRecentlyUsedList is true, the filename will also be added to the
  44491. drop-down list of recent files.
  44492. If sendChangeNotification is false, then the listeners won't be told of the
  44493. change.
  44494. */
  44495. void setCurrentFile (File newFile,
  44496. bool addToRecentlyUsedList,
  44497. bool sendChangeNotification = true);
  44498. /** Changes whether the use can type into the filename box.
  44499. */
  44500. void setFilenameIsEditable (bool shouldBeEditable);
  44501. /** Sets a file or directory to be the default starting point for the browser to show.
  44502. This is only used if the current file hasn't been set.
  44503. */
  44504. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44505. /** Returns all the entries on the recent files list.
  44506. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  44507. state of this list.
  44508. @see setRecentlyUsedFilenames
  44509. */
  44510. StringArray getRecentlyUsedFilenames() const;
  44511. /** Sets all the entries on the recent files list.
  44512. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  44513. state of this list.
  44514. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  44515. */
  44516. void setRecentlyUsedFilenames (const StringArray& filenames);
  44517. /** Adds an entry to the recently-used files dropdown list.
  44518. If the file is already in the list, it will be moved to the top. A limit
  44519. is also placed on the number of items that are kept in the list.
  44520. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  44521. */
  44522. void addRecentlyUsedFile (const File& file);
  44523. /** Changes the limit for the number of files that will be stored in the recent-file list.
  44524. */
  44525. void setMaxNumberOfRecentFiles (int newMaximum);
  44526. /** Changes the text shown on the 'browse' button.
  44527. By default this button just says "..." but you can change it. The button itself
  44528. can be changed using the look-and-feel classes, so it might not actually have any
  44529. text on it.
  44530. */
  44531. void setBrowseButtonText (const String& browseButtonText);
  44532. /** Adds a listener that will be called when the selected file is changed. */
  44533. void addListener (FilenameComponentListener* listener);
  44534. /** Removes a previously-registered listener. */
  44535. void removeListener (FilenameComponentListener* listener);
  44536. /** Gives the component a tooltip. */
  44537. void setTooltip (const String& newTooltip);
  44538. /** @internal */
  44539. void paintOverChildren (Graphics& g);
  44540. /** @internal */
  44541. void resized();
  44542. /** @internal */
  44543. void lookAndFeelChanged();
  44544. /** @internal */
  44545. bool isInterestedInFileDrag (const StringArray& files);
  44546. /** @internal */
  44547. void filesDropped (const StringArray& files, int, int);
  44548. /** @internal */
  44549. void fileDragEnter (const StringArray& files, int, int);
  44550. /** @internal */
  44551. void fileDragExit (const StringArray& files);
  44552. private:
  44553. ComboBox filenameBox;
  44554. String lastFilename;
  44555. ScopedPointer<Button> browseButton;
  44556. int maxRecentFiles;
  44557. bool isDir, isSaving, isFileDragOver;
  44558. String wildcard, enforcedSuffix, browseButtonText;
  44559. ListenerList <FilenameComponentListener> listeners;
  44560. File defaultBrowseFile;
  44561. void comboBoxChanged (ComboBox*);
  44562. void buttonClicked (Button* button);
  44563. void handleAsyncUpdate();
  44564. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  44565. };
  44566. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44567. /*** End of inlined file: juce_FilenameComponent.h ***/
  44568. #endif
  44569. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  44570. #endif
  44571. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44572. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  44573. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44574. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44575. /**
  44576. Shows a set of file paths in a list, allowing them to be added, removed or
  44577. re-ordered.
  44578. @see FileSearchPath
  44579. */
  44580. class JUCE_API FileSearchPathListComponent : public Component,
  44581. public SettableTooltipClient,
  44582. public FileDragAndDropTarget,
  44583. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44584. private ListBoxModel
  44585. {
  44586. public:
  44587. /** Creates an empty FileSearchPathListComponent. */
  44588. FileSearchPathListComponent();
  44589. /** Destructor. */
  44590. ~FileSearchPathListComponent();
  44591. /** Returns the path as it is currently shown. */
  44592. const FileSearchPath& getPath() const noexcept { return path; }
  44593. /** Changes the current path. */
  44594. void setPath (const FileSearchPath& newPath);
  44595. /** Sets a file or directory to be the default starting point for the browser to show.
  44596. This is only used if the current file hasn't been set.
  44597. */
  44598. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44599. /** A set of colour IDs to use to change the colour of various aspects of the label.
  44600. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44601. methods.
  44602. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44603. */
  44604. enum ColourIds
  44605. {
  44606. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  44607. Make this transparent if you don't want the background to be filled. */
  44608. };
  44609. /** @internal */
  44610. int getNumRows();
  44611. /** @internal */
  44612. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  44613. /** @internal */
  44614. void deleteKeyPressed (int lastRowSelected);
  44615. /** @internal */
  44616. void returnKeyPressed (int lastRowSelected);
  44617. /** @internal */
  44618. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  44619. /** @internal */
  44620. void selectedRowsChanged (int lastRowSelected);
  44621. /** @internal */
  44622. void resized();
  44623. /** @internal */
  44624. void paint (Graphics& g);
  44625. /** @internal */
  44626. bool isInterestedInFileDrag (const StringArray& files);
  44627. /** @internal */
  44628. void filesDropped (const StringArray& files, int, int);
  44629. /** @internal */
  44630. void buttonClicked (Button* button);
  44631. private:
  44632. FileSearchPath path;
  44633. File defaultBrowseTarget;
  44634. ListBox listBox;
  44635. TextButton addButton, removeButton, changeButton;
  44636. DrawableButton upButton, downButton;
  44637. void changed();
  44638. void updateButtons();
  44639. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  44640. };
  44641. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44642. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  44643. #endif
  44644. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44645. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  44646. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44647. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44648. /**
  44649. A component that displays the files in a directory as a treeview.
  44650. This implements the DirectoryContentsDisplayComponent base class so that
  44651. it can be used in a FileBrowserComponent.
  44652. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44653. class and the FileBrowserListener class.
  44654. @see DirectoryContentsList, FileListComponent
  44655. */
  44656. class JUCE_API FileTreeComponent : public TreeView,
  44657. public DirectoryContentsDisplayComponent
  44658. {
  44659. public:
  44660. /** Creates a listbox to show the contents of a specified directory.
  44661. */
  44662. FileTreeComponent (DirectoryContentsList& listToShow);
  44663. /** Destructor. */
  44664. ~FileTreeComponent();
  44665. /** Returns the number of files the user has got selected.
  44666. @see getSelectedFile
  44667. */
  44668. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  44669. /** Returns one of the files that the user has currently selected.
  44670. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44671. @see getNumSelectedFiles
  44672. */
  44673. const File getSelectedFile (int index = 0) const;
  44674. /** Deselects any files that are currently selected. */
  44675. void deselectAllFiles();
  44676. /** Scrolls the list to the top. */
  44677. void scrollToTop();
  44678. /** Setting a name for this allows tree items to be dragged.
  44679. The string that you pass in here will be returned by the getDragSourceDescription()
  44680. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  44681. */
  44682. void setDragAndDropDescription (const String& description);
  44683. /** Returns the last value that was set by setDragAndDropDescription().
  44684. */
  44685. const String& getDragAndDropDescription() const noexcept { return dragAndDropDescription; }
  44686. private:
  44687. String dragAndDropDescription;
  44688. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  44689. };
  44690. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44691. /*** End of inlined file: juce_FileTreeComponent.h ***/
  44692. #endif
  44693. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44694. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  44695. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44696. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44697. /**
  44698. A simple preview component that shows thumbnails of image files.
  44699. @see FileChooserDialogBox, FilePreviewComponent
  44700. */
  44701. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  44702. private Timer
  44703. {
  44704. public:
  44705. /** Creates an ImagePreviewComponent. */
  44706. ImagePreviewComponent();
  44707. /** Destructor. */
  44708. ~ImagePreviewComponent();
  44709. /** @internal */
  44710. void selectedFileChanged (const File& newSelectedFile);
  44711. /** @internal */
  44712. void paint (Graphics& g);
  44713. /** @internal */
  44714. void timerCallback();
  44715. private:
  44716. File fileToLoad;
  44717. Image currentThumbnail;
  44718. String currentDetails;
  44719. void getThumbSize (int& w, int& h) const;
  44720. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  44721. };
  44722. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44723. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  44724. #endif
  44725. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44726. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  44727. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44728. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44729. /**
  44730. A type of FileFilter that works by wildcard pattern matching.
  44731. This filter only allows files that match one of the specified patterns, but
  44732. allows all directories through.
  44733. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  44734. */
  44735. class JUCE_API WildcardFileFilter : public FileFilter
  44736. {
  44737. public:
  44738. /**
  44739. Creates a wildcard filter for one or more patterns.
  44740. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  44741. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  44742. or .aiff.
  44743. Passing an empty string as a pattern will fail to match anything, so by leaving
  44744. either the file or directory pattern parameter empty means you can control
  44745. whether files or directories are found.
  44746. The description is a name to show the user in a list of possible patterns, so
  44747. for the wav/aiff example, your description might be "audio files".
  44748. */
  44749. WildcardFileFilter (const String& fileWildcardPatterns,
  44750. const String& directoryWildcardPatterns,
  44751. const String& description);
  44752. /** Destructor. */
  44753. ~WildcardFileFilter();
  44754. /** Returns true if the filename matches one of the patterns specified. */
  44755. bool isFileSuitable (const File& file) const;
  44756. /** This always returns true. */
  44757. bool isDirectorySuitable (const File& file) const;
  44758. private:
  44759. StringArray fileWildcards, directoryWildcards;
  44760. static void parse (const String& pattern, StringArray& result);
  44761. static bool match (const File& file, const StringArray& wildcards);
  44762. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  44763. };
  44764. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44765. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  44766. #endif
  44767. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  44768. #endif
  44769. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  44770. #endif
  44771. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  44772. #endif
  44773. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  44774. #endif
  44775. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  44776. #endif
  44777. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  44778. #endif
  44779. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  44780. #endif
  44781. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44782. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  44783. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44784. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44785. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  44786. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44787. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44788. /**
  44789. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  44790. command in a ApplicationCommandManager.
  44791. Normally, you won't actually create a KeyPressMappingSet directly, because
  44792. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  44793. you'd create yourself an ApplicationCommandManager, and call its
  44794. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  44795. KeyPressMappingSet.
  44796. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  44797. to the top-level component for which you want to handle keystrokes. So for example:
  44798. @code
  44799. class MyMainWindow : public Component
  44800. {
  44801. ApplicationCommandManager* myCommandManager;
  44802. public:
  44803. MyMainWindow()
  44804. {
  44805. myCommandManager = new ApplicationCommandManager();
  44806. // first, make sure the command manager has registered all the commands that its
  44807. // targets can perform..
  44808. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  44809. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  44810. // this will use the command manager to initialise the KeyPressMappingSet with
  44811. // the default keypresses that were specified when the targets added their commands
  44812. // to the manager.
  44813. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  44814. // having set up the default key-mappings, you might now want to load the last set
  44815. // of mappings that the user configured.
  44816. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  44817. // Now tell our top-level window to send any keypresses that arrive to the
  44818. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  44819. addKeyListener (myCommandManager->getKeyMappings());
  44820. }
  44821. ...
  44822. }
  44823. @endcode
  44824. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  44825. register to be told when a command or mapping is added, removed, etc.
  44826. There's also a UI component called KeyMappingEditorComponent that can be used
  44827. to easily edit the key mappings.
  44828. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  44829. */
  44830. class JUCE_API KeyPressMappingSet : public KeyListener,
  44831. public ChangeBroadcaster,
  44832. public FocusChangeListener
  44833. {
  44834. public:
  44835. /** Creates a KeyPressMappingSet for a given command manager.
  44836. Normally, you won't actually create a KeyPressMappingSet directly, because
  44837. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  44838. best thing to do is to create your ApplicationCommandManager, and use the
  44839. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  44840. When a suitable keypress happens, the manager's invoke() method will be
  44841. used to invoke the appropriate command.
  44842. @see ApplicationCommandManager
  44843. */
  44844. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  44845. /** Creates an copy of a KeyPressMappingSet. */
  44846. KeyPressMappingSet (const KeyPressMappingSet& other);
  44847. /** Destructor. */
  44848. ~KeyPressMappingSet();
  44849. ApplicationCommandManager* getCommandManager() const noexcept { return commandManager; }
  44850. /** Returns a list of keypresses that are assigned to a particular command.
  44851. @param commandID the command's ID
  44852. */
  44853. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  44854. /** Assigns a keypress to a command.
  44855. If the keypress is already assigned to a different command, it will first be
  44856. removed from that command, to avoid it triggering multiple functions.
  44857. @param commandID the ID of the command that you want to add a keypress to. If
  44858. this is 0, the keypress will be removed from anything that it
  44859. was previously assigned to, but not re-assigned
  44860. @param newKeyPress the new key-press
  44861. @param insertIndex if this is less than zero, the key will be appended to the
  44862. end of the list of keypresses; otherwise the new keypress will
  44863. be inserted into the existing list at this index
  44864. */
  44865. void addKeyPress (CommandID commandID,
  44866. const KeyPress& newKeyPress,
  44867. int insertIndex = -1);
  44868. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  44869. @see resetToDefaultMapping
  44870. */
  44871. void resetToDefaultMappings();
  44872. /** Resets all key-mappings to the defaults for a particular command.
  44873. @see resetToDefaultMappings
  44874. */
  44875. void resetToDefaultMapping (CommandID commandID);
  44876. /** Removes all keypresses that are assigned to any commands. */
  44877. void clearAllKeyPresses();
  44878. /** Removes all keypresses that are assigned to a particular command. */
  44879. void clearAllKeyPresses (CommandID commandID);
  44880. /** Removes one of the keypresses that are assigned to a command.
  44881. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  44882. which the keyPressIndex refers.
  44883. */
  44884. void removeKeyPress (CommandID commandID, int keyPressIndex);
  44885. /** Removes a keypress from any command that it may be assigned to.
  44886. */
  44887. void removeKeyPress (const KeyPress& keypress);
  44888. /** Returns true if the given command is linked to this key. */
  44889. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const noexcept;
  44890. /** Looks for a command that corresponds to a keypress.
  44891. @returns the UID of the command or 0 if none was found
  44892. */
  44893. CommandID findCommandForKeyPress (const KeyPress& keyPress) const noexcept;
  44894. /** Tries to recreate the mappings from a previously stored state.
  44895. The XML passed in must have been created by the createXml() method.
  44896. If the stored state makes any reference to commands that aren't
  44897. currently available, these will be ignored.
  44898. If the set of mappings being loaded was a set of differences (using createXml (true)),
  44899. then this will call resetToDefaultMappings() and then merge the saved mappings
  44900. on top. If the saved set was created with createXml (false), then this method
  44901. will first clear all existing mappings and load the saved ones as a complete set.
  44902. @returns true if it manages to load the XML correctly
  44903. @see createXml
  44904. */
  44905. bool restoreFromXml (const XmlElement& xmlVersion);
  44906. /** Creates an XML representation of the current mappings.
  44907. This will produce a lump of XML that can be later reloaded using
  44908. restoreFromXml() to recreate the current mapping state.
  44909. The object that is returned must be deleted by the caller.
  44910. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  44911. will be saved into the XML. If it's true, then the XML will
  44912. only store the differences between the current mappings and
  44913. the default mappings you'd get from calling resetToDefaultMappings().
  44914. The advantage of saving a set of differences from the default is that
  44915. if you change the default mappings (in a new version of your app, for
  44916. example), then these will be merged into a user's saved preferences.
  44917. @see restoreFromXml
  44918. */
  44919. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  44920. /** @internal */
  44921. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  44922. /** @internal */
  44923. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  44924. /** @internal */
  44925. void globalFocusChanged (Component* focusedComponent);
  44926. private:
  44927. ApplicationCommandManager* commandManager;
  44928. struct CommandMapping
  44929. {
  44930. CommandID commandID;
  44931. Array <KeyPress> keypresses;
  44932. bool wantsKeyUpDownCallbacks;
  44933. };
  44934. OwnedArray <CommandMapping> mappings;
  44935. struct KeyPressTime
  44936. {
  44937. KeyPress key;
  44938. uint32 timeWhenPressed;
  44939. };
  44940. OwnedArray <KeyPressTime> keysDown;
  44941. void handleMessage (const Message& message);
  44942. void invokeCommand (const CommandID commandID,
  44943. const KeyPress& keyPress,
  44944. const bool isKeyDown,
  44945. const int millisecsSinceKeyPressed,
  44946. Component* const originatingComponent) const;
  44947. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  44948. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  44949. };
  44950. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44951. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  44952. /**
  44953. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  44954. object.
  44955. @see KeyPressMappingSet
  44956. */
  44957. class JUCE_API KeyMappingEditorComponent : public Component
  44958. {
  44959. public:
  44960. /** Creates a KeyMappingEditorComponent.
  44961. @param mappingSet this is the set of mappings to display and edit. Make sure the
  44962. mappings object is not deleted before this component!
  44963. @param showResetToDefaultButton if true, then at the bottom of the list, the
  44964. component will include a 'reset to defaults' button.
  44965. */
  44966. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  44967. bool showResetToDefaultButton);
  44968. /** Destructor. */
  44969. virtual ~KeyMappingEditorComponent();
  44970. /** Sets up the colours to use for parts of the component.
  44971. @param mainBackground colour to use for most of the background
  44972. @param textColour colour to use for the text
  44973. */
  44974. void setColours (const Colour& mainBackground,
  44975. const Colour& textColour);
  44976. /** Returns the KeyPressMappingSet that this component is acting upon. */
  44977. KeyPressMappingSet& getMappings() const noexcept { return mappings; }
  44978. /** Can be overridden if some commands need to be excluded from the list.
  44979. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  44980. method to decide what to return, but you can override it to handle special cases.
  44981. */
  44982. virtual bool shouldCommandBeIncluded (CommandID commandID);
  44983. /** Can be overridden to indicate that some commands are shown as read-only.
  44984. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  44985. method to decide what to return, but you can override it to handle special cases.
  44986. */
  44987. virtual bool isCommandReadOnly (CommandID commandID);
  44988. /** This can be overridden to let you change the format of the string used
  44989. to describe a keypress.
  44990. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  44991. keys that are triggered by something else externally. If you override the
  44992. method, be sure to let the base class's method handle keys you're not
  44993. interested in.
  44994. */
  44995. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  44996. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  44997. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44998. methods.
  44999. To change the colours of the menu that pops up
  45000. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45001. */
  45002. enum ColourIds
  45003. {
  45004. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  45005. textColourId = 0x100ad01, /**< The colour for the text. */
  45006. };
  45007. /** @internal */
  45008. void parentHierarchyChanged();
  45009. /** @internal */
  45010. void resized();
  45011. private:
  45012. KeyPressMappingSet& mappings;
  45013. TreeView tree;
  45014. TextButton resetButton;
  45015. class TopLevelItem;
  45016. class ChangeKeyButton;
  45017. class MappingItem;
  45018. class CategoryItem;
  45019. class ItemComponent;
  45020. friend class TopLevelItem;
  45021. friend class OwnedArray <ChangeKeyButton>;
  45022. friend class ScopedPointer<TopLevelItem>;
  45023. ScopedPointer<TopLevelItem> treeItem;
  45024. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  45025. };
  45026. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  45027. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  45028. #endif
  45029. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  45030. #endif
  45031. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  45032. #endif
  45033. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  45034. #endif
  45035. #ifndef __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45036. /*** Start of inlined file: juce_TextEditorKeyMapper.h ***/
  45037. #ifndef __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45038. #define __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45039. /** This class is used to invoke a range of text-editor navigation methods on
  45040. an object, based upon a keypress event.
  45041. It's currently used internally by the TextEditor and CodeEditorComponent.
  45042. */
  45043. template <class CallbackClass>
  45044. struct TextEditorKeyMapper
  45045. {
  45046. /** Checks the keypress and invokes one of a range of navigation functions that
  45047. the target class must implement, based on the key event.
  45048. */
  45049. static bool invokeKeyFunction (CallbackClass& target, const KeyPress& key)
  45050. {
  45051. const bool isShiftDown = key.getModifiers().isShiftDown();
  45052. const bool ctrlOrAltDown = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  45053. if (key == KeyPress (KeyPress::downKey, ModifierKeys::ctrlModifier, 0)
  45054. && target.scrollUp())
  45055. return true;
  45056. if (key == KeyPress (KeyPress::upKey, ModifierKeys::ctrlModifier, 0)
  45057. && target.scrollDown())
  45058. return true;
  45059. #if JUCE_MAC
  45060. if (key.getModifiers().isCommandDown())
  45061. {
  45062. if (key.isKeyCode (KeyPress::upKey))
  45063. return target.moveCaretToTop (isShiftDown);
  45064. if (key.isKeyCode (KeyPress::downKey))
  45065. return target.moveCaretToEnd (isShiftDown);
  45066. if (key.isKeyCode (KeyPress::leftKey))
  45067. return target.moveCaretToStartOfLine (isShiftDown);
  45068. if (key.isKeyCode (KeyPress::rightKey))
  45069. return target.moveCaretToEndOfLine (isShiftDown);
  45070. }
  45071. #endif
  45072. if (key.isKeyCode (KeyPress::upKey))
  45073. return target.moveCaretUp (isShiftDown);
  45074. if (key.isKeyCode (KeyPress::downKey))
  45075. return target.moveCaretDown (isShiftDown);
  45076. if (key.isKeyCode (KeyPress::leftKey))
  45077. return target.moveCaretLeft (ctrlOrAltDown, isShiftDown);
  45078. if (key.isKeyCode (KeyPress::rightKey))
  45079. return target.moveCaretRight (ctrlOrAltDown, isShiftDown);
  45080. if (key.isKeyCode (KeyPress::pageUpKey))
  45081. return target.pageUp (isShiftDown);
  45082. if (key.isKeyCode (KeyPress::pageDownKey))
  45083. return target.pageDown (isShiftDown);
  45084. if (key.isKeyCode (KeyPress::homeKey))
  45085. return ctrlOrAltDown ? target.moveCaretToTop (isShiftDown)
  45086. : target.moveCaretToStartOfLine (isShiftDown);
  45087. if (key.isKeyCode (KeyPress::endKey))
  45088. return ctrlOrAltDown ? target.moveCaretToEnd (isShiftDown)
  45089. : target.moveCaretToEndOfLine (isShiftDown);
  45090. if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  45091. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  45092. return target.copyToClipboard();
  45093. if (key == KeyPress ('x', ModifierKeys::commandModifier, 0)
  45094. || key == KeyPress (KeyPress::deleteKey, ModifierKeys::shiftModifier, 0))
  45095. return target.cutToClipboard();
  45096. if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  45097. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  45098. return target.pasteFromClipboard();
  45099. if (key.isKeyCode (KeyPress::backspaceKey))
  45100. return target.deleteBackwards (ctrlOrAltDown);
  45101. if (key.isKeyCode (KeyPress::deleteKey))
  45102. return target.deleteForwards (ctrlOrAltDown);
  45103. if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  45104. return target.selectAll();
  45105. if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  45106. return target.undo();
  45107. if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  45108. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  45109. return target.redo();
  45110. return false;
  45111. }
  45112. };
  45113. #endif // __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45114. /*** End of inlined file: juce_TextEditorKeyMapper.h ***/
  45115. #endif
  45116. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  45117. #endif
  45118. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  45119. #endif
  45120. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  45121. #endif
  45122. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  45123. #endif
  45124. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45125. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  45126. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45127. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45128. /** An object that watches for any movement of a component or any of its parent components.
  45129. This makes it easy to check when a component is moved relative to its top-level
  45130. peer window. The normal Component::moved() method is only called when a component
  45131. moves relative to its immediate parent, and sometimes you want to know if any of
  45132. components higher up the tree have moved (which of course will affect the overall
  45133. position of all their sub-components).
  45134. It also includes a callback that lets you know when the top-level peer is changed.
  45135. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  45136. because they need to keep their custom windows in the right place and respond to
  45137. changes in the peer.
  45138. */
  45139. class JUCE_API ComponentMovementWatcher : public ComponentListener
  45140. {
  45141. public:
  45142. /** Creates a ComponentMovementWatcher to watch a given target component. */
  45143. ComponentMovementWatcher (Component* component);
  45144. /** Destructor. */
  45145. ~ComponentMovementWatcher();
  45146. /** This callback happens when the component that is being watched is moved
  45147. relative to its top-level peer window, or when it is resized. */
  45148. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  45149. /** This callback happens when the component's top-level peer is changed. */
  45150. virtual void componentPeerChanged() = 0;
  45151. /** This callback happens when the component's visibility state changes, possibly due to
  45152. one of its parents being made visible or invisible.
  45153. */
  45154. virtual void componentVisibilityChanged() = 0;
  45155. /** @internal */
  45156. void componentParentHierarchyChanged (Component& component);
  45157. /** @internal */
  45158. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  45159. /** @internal */
  45160. void componentBeingDeleted (Component& component);
  45161. /** @internal */
  45162. void componentVisibilityChanged (Component& component);
  45163. private:
  45164. WeakReference<Component> component;
  45165. uint32 lastPeerID;
  45166. Array <Component*> registeredParentComps;
  45167. bool reentrant, wasShowing;
  45168. Rectangle<int> lastBounds;
  45169. void unregister();
  45170. void registerWithParentComps();
  45171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  45172. };
  45173. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45174. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  45175. #endif
  45176. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45177. /*** Start of inlined file: juce_GroupComponent.h ***/
  45178. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45179. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45180. /**
  45181. A component that draws an outline around itself and has an optional title at
  45182. the top, for drawing an outline around a group of controls.
  45183. */
  45184. class JUCE_API GroupComponent : public Component
  45185. {
  45186. public:
  45187. /** Creates a GroupComponent.
  45188. @param componentName the name to give the component
  45189. @param labelText the text to show at the top of the outline
  45190. */
  45191. GroupComponent (const String& componentName = String::empty,
  45192. const String& labelText = String::empty);
  45193. /** Destructor. */
  45194. ~GroupComponent();
  45195. /** Changes the text that's shown at the top of the component. */
  45196. void setText (const String& newText);
  45197. /** Returns the currently displayed text label. */
  45198. const String getText() const;
  45199. /** Sets the positioning of the text label.
  45200. (The default is Justification::left)
  45201. @see getTextLabelPosition
  45202. */
  45203. void setTextLabelPosition (const Justification& justification);
  45204. /** Returns the current text label position.
  45205. @see setTextLabelPosition
  45206. */
  45207. const Justification getTextLabelPosition() const noexcept { return justification; }
  45208. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45209. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45210. methods.
  45211. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45212. */
  45213. enum ColourIds
  45214. {
  45215. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  45216. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  45217. };
  45218. /** @internal */
  45219. void paint (Graphics& g);
  45220. /** @internal */
  45221. void enablementChanged();
  45222. /** @internal */
  45223. void colourChanged();
  45224. private:
  45225. String text;
  45226. Justification justification;
  45227. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  45228. };
  45229. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45230. /*** End of inlined file: juce_GroupComponent.h ***/
  45231. #endif
  45232. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45233. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  45234. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45235. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45236. /*** Start of inlined file: juce_TabbedComponent.h ***/
  45237. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45238. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45239. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  45240. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45241. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45242. class TabbedButtonBar;
  45243. /** In a TabbedButtonBar, this component is used for each of the buttons.
  45244. If you want to create a TabbedButtonBar with custom tab components, derive
  45245. your component from this class, and override the TabbedButtonBar::createTabButton()
  45246. method to create it instead of the default one.
  45247. @see TabbedButtonBar
  45248. */
  45249. class JUCE_API TabBarButton : public Button
  45250. {
  45251. public:
  45252. /** Creates the tab button. */
  45253. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  45254. /** Destructor. */
  45255. ~TabBarButton();
  45256. /** Chooses the best length for the tab, given the specified depth.
  45257. If the tab is horizontal, this should return its width, and the depth
  45258. specifies its height. If it's vertical, it should return the height, and
  45259. the depth is actually its width.
  45260. */
  45261. virtual int getBestTabLength (int depth);
  45262. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  45263. void clicked (const ModifierKeys& mods);
  45264. bool hitTest (int x, int y);
  45265. protected:
  45266. friend class TabbedButtonBar;
  45267. TabbedButtonBar& owner;
  45268. int overlapPixels;
  45269. DropShadowEffect shadow;
  45270. /** Returns an area of the component that's safe to draw in.
  45271. This deals with the orientation of the tabs, which affects which side is
  45272. touching the tabbed box's content component.
  45273. */
  45274. const Rectangle<int> getActiveArea();
  45275. /** Returns this tab's index in its tab bar. */
  45276. int getIndex() const;
  45277. private:
  45278. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  45279. };
  45280. /**
  45281. A vertical or horizontal bar containing tabs that you can select.
  45282. You can use one of these to generate things like a dialog box that has
  45283. tabbed pages you can flip between. Attach a ChangeListener to the
  45284. button bar to be told when the user changes the page.
  45285. An easier method than doing this is to use a TabbedComponent, which
  45286. contains its own TabbedButtonBar and which takes care of the layout
  45287. and other housekeeping.
  45288. @see TabbedComponent
  45289. */
  45290. class JUCE_API TabbedButtonBar : public Component,
  45291. public ChangeBroadcaster
  45292. {
  45293. public:
  45294. /** The placement of the tab-bar
  45295. @see setOrientation, getOrientation
  45296. */
  45297. enum Orientation
  45298. {
  45299. TabsAtTop,
  45300. TabsAtBottom,
  45301. TabsAtLeft,
  45302. TabsAtRight
  45303. };
  45304. /** Creates a TabbedButtonBar with a given placement.
  45305. You can change the orientation later if you need to.
  45306. */
  45307. TabbedButtonBar (Orientation orientation);
  45308. /** Destructor. */
  45309. ~TabbedButtonBar();
  45310. /** Changes the bar's orientation.
  45311. This won't change the bar's actual size - you'll need to do that yourself,
  45312. but this determines which direction the tabs go in, and which side they're
  45313. stuck to.
  45314. */
  45315. void setOrientation (Orientation orientation);
  45316. /** Returns the current orientation.
  45317. @see setOrientation
  45318. */
  45319. Orientation getOrientation() const noexcept { return orientation; }
  45320. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  45321. fit a lot of tabs on-screen.
  45322. */
  45323. void setMinimumTabScaleFactor (double newMinimumScale);
  45324. /** Deletes all the tabs from the bar.
  45325. @see addTab
  45326. */
  45327. void clearTabs();
  45328. /** Adds a tab to the bar.
  45329. Tabs are added in left-to-right reading order.
  45330. If this is the first tab added, it'll also be automatically selected.
  45331. */
  45332. void addTab (const String& tabName,
  45333. const Colour& tabBackgroundColour,
  45334. int insertIndex = -1);
  45335. /** Changes the name of one of the tabs. */
  45336. void setTabName (int tabIndex,
  45337. const String& newName);
  45338. /** Gets rid of one of the tabs. */
  45339. void removeTab (int tabIndex);
  45340. /** Moves a tab to a new index in the list.
  45341. Pass -1 as the index to move it to the end of the list.
  45342. */
  45343. void moveTab (int currentIndex, int newIndex);
  45344. /** Returns the number of tabs in the bar. */
  45345. int getNumTabs() const;
  45346. /** Returns a list of all the tab names in the bar. */
  45347. StringArray getTabNames() const;
  45348. /** Changes the currently selected tab.
  45349. This will send a change message and cause a synchronous callback to
  45350. the currentTabChanged() method. (But if the given tab is already selected,
  45351. nothing will be done).
  45352. To deselect all the tabs, use an index of -1.
  45353. */
  45354. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  45355. /** Returns the name of the currently selected tab.
  45356. This could be an empty string if none are selected.
  45357. */
  45358. const String getCurrentTabName() const;
  45359. /** Returns the index of the currently selected tab.
  45360. This could return -1 if none are selected.
  45361. */
  45362. int getCurrentTabIndex() const noexcept { return currentTabIndex; }
  45363. /** Returns the button for a specific tab.
  45364. The button that is returned may be deleted later by this component, so don't hang
  45365. on to the pointer that is returned. A null pointer may be returned if the index is
  45366. out of range.
  45367. */
  45368. TabBarButton* getTabButton (int index) const;
  45369. /** Returns the index of a TabBarButton if it belongs to this bar. */
  45370. int indexOfTabButton (const TabBarButton* button) const;
  45371. /** Callback method to indicate the selected tab has been changed.
  45372. @see setCurrentTabIndex
  45373. */
  45374. virtual void currentTabChanged (int newCurrentTabIndex,
  45375. const String& newCurrentTabName);
  45376. /** Callback method to indicate that the user has right-clicked on a tab.
  45377. (Or ctrl-clicked on the Mac)
  45378. */
  45379. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  45380. /** Returns the colour of a tab.
  45381. This is the colour that was specified in addTab().
  45382. */
  45383. const Colour getTabBackgroundColour (int tabIndex);
  45384. /** Changes the background colour of a tab.
  45385. @see addTab, getTabBackgroundColour
  45386. */
  45387. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  45388. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45389. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45390. methods.
  45391. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45392. */
  45393. enum ColourIds
  45394. {
  45395. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  45396. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  45397. the look and feel will choose an appropriate colour. */
  45398. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  45399. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  45400. this isn't specified, the look and feel will choose an appropriate
  45401. colour. */
  45402. };
  45403. /** @internal */
  45404. void resized();
  45405. /** @internal */
  45406. void lookAndFeelChanged();
  45407. protected:
  45408. /** This creates one of the tabs.
  45409. If you need to use custom tab components, you can override this method and
  45410. return your own class instead of the default.
  45411. */
  45412. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  45413. private:
  45414. Orientation orientation;
  45415. struct TabInfo
  45416. {
  45417. ScopedPointer<TabBarButton> component;
  45418. String name;
  45419. Colour colour;
  45420. };
  45421. OwnedArray <TabInfo> tabs;
  45422. double minimumScale;
  45423. int currentTabIndex;
  45424. class BehindFrontTabComp;
  45425. friend class BehindFrontTabComp;
  45426. friend class ScopedPointer<BehindFrontTabComp>;
  45427. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  45428. ScopedPointer<Button> extraTabsButton;
  45429. void showExtraItemsMenu();
  45430. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  45431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  45432. };
  45433. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45434. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  45435. /**
  45436. A component with a TabbedButtonBar along one of its sides.
  45437. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  45438. with addTab(), and this will take care of showing the pages for you when the
  45439. user clicks on a different tab.
  45440. @see TabbedButtonBar
  45441. */
  45442. class JUCE_API TabbedComponent : public Component
  45443. {
  45444. public:
  45445. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  45446. Once created, add some tabs with the addTab() method.
  45447. */
  45448. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  45449. /** Destructor. */
  45450. ~TabbedComponent();
  45451. /** Changes the placement of the tabs.
  45452. This will rearrange the layout to place the tabs along the appropriate
  45453. side of this component, and will shift the content component accordingly.
  45454. @see TabbedButtonBar::setOrientation
  45455. */
  45456. void setOrientation (TabbedButtonBar::Orientation orientation);
  45457. /** Returns the current tab placement.
  45458. @see setOrientation, TabbedButtonBar::getOrientation
  45459. */
  45460. TabbedButtonBar::Orientation getOrientation() const noexcept;
  45461. /** Specifies how many pixels wide or high the tab-bar should be.
  45462. If the tabs are placed along the top or bottom, this specified the height
  45463. of the bar; if they're along the left or right edges, it'll be the width
  45464. of the bar.
  45465. */
  45466. void setTabBarDepth (int newDepth);
  45467. /** Returns the current thickness of the tab bar.
  45468. @see setTabBarDepth
  45469. */
  45470. int getTabBarDepth() const noexcept { return tabDepth; }
  45471. /** Specifies the thickness of an outline that should be drawn around the content component.
  45472. If this thickness is > 0, a line will be drawn around the three sides of the content
  45473. component which don't touch the tab-bar, and the content component will be inset by this amount.
  45474. To set the colour of the line, use setColour (outlineColourId, ...).
  45475. */
  45476. void setOutline (int newThickness);
  45477. /** Specifies a gap to leave around the edge of the content component.
  45478. Each edge of the content component will be indented by the given number of pixels.
  45479. */
  45480. void setIndent (int indentThickness);
  45481. /** Removes all the tabs from the bar.
  45482. @see TabbedButtonBar::clearTabs
  45483. */
  45484. void clearTabs();
  45485. /** Adds a tab to the tab-bar.
  45486. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  45487. is true, it will be deleted when the tab is removed or when this object is
  45488. deleted.
  45489. @see TabbedButtonBar::addTab
  45490. */
  45491. void addTab (const String& tabName,
  45492. const Colour& tabBackgroundColour,
  45493. Component* contentComponent,
  45494. bool deleteComponentWhenNotNeeded,
  45495. int insertIndex = -1);
  45496. /** Changes the name of one of the tabs. */
  45497. void setTabName (int tabIndex, const String& newName);
  45498. /** Gets rid of one of the tabs. */
  45499. void removeTab (int tabIndex);
  45500. /** Returns the number of tabs in the bar. */
  45501. int getNumTabs() const;
  45502. /** Returns a list of all the tab names in the bar. */
  45503. StringArray getTabNames() const;
  45504. /** Returns the content component that was added for the given index.
  45505. Be sure not to use or delete the components that are returned, as this may interfere
  45506. with the TabbedComponent's use of them.
  45507. */
  45508. Component* getTabContentComponent (int tabIndex) const noexcept;
  45509. /** Returns the colour of one of the tabs. */
  45510. const Colour getTabBackgroundColour (int tabIndex) const noexcept;
  45511. /** Changes the background colour of one of the tabs. */
  45512. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  45513. /** Changes the currently-selected tab.
  45514. To deselect all the tabs, pass -1 as the index.
  45515. @see TabbedButtonBar::setCurrentTabIndex
  45516. */
  45517. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  45518. /** Returns the index of the currently selected tab.
  45519. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  45520. */
  45521. int getCurrentTabIndex() const;
  45522. /** Returns the name of the currently selected tab.
  45523. @see addTab, TabbedButtonBar::getCurrentTabName()
  45524. */
  45525. const String getCurrentTabName() const;
  45526. /** Returns the current component that's filling the panel.
  45527. This will return 0 if there isn't one.
  45528. */
  45529. Component* getCurrentContentComponent() const noexcept { return panelComponent; }
  45530. /** Callback method to indicate the selected tab has been changed.
  45531. @see setCurrentTabIndex
  45532. */
  45533. virtual void currentTabChanged (int newCurrentTabIndex,
  45534. const String& newCurrentTabName);
  45535. /** Callback method to indicate that the user has right-clicked on a tab.
  45536. (Or ctrl-clicked on the Mac)
  45537. */
  45538. virtual void popupMenuClickOnTab (int tabIndex,
  45539. const String& tabName);
  45540. /** Returns the tab button bar component that is being used.
  45541. */
  45542. TabbedButtonBar& getTabbedButtonBar() const noexcept { return *tabs; }
  45543. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45544. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45545. methods.
  45546. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45547. */
  45548. enum ColourIds
  45549. {
  45550. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  45551. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  45552. (See setOutline) */
  45553. };
  45554. /** @internal */
  45555. void paint (Graphics& g);
  45556. /** @internal */
  45557. void resized();
  45558. /** @internal */
  45559. void lookAndFeelChanged();
  45560. protected:
  45561. /** This creates one of the tab buttons.
  45562. If you need to use custom tab components, you can override this method and
  45563. return your own class instead of the default.
  45564. */
  45565. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  45566. /** @internal */
  45567. ScopedPointer<TabbedButtonBar> tabs;
  45568. private:
  45569. Array <WeakReference<Component> > contentComponents;
  45570. WeakReference<Component> panelComponent;
  45571. int tabDepth;
  45572. int outlineThickness, edgeIndent;
  45573. class ButtonBar;
  45574. friend class ButtonBar;
  45575. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  45576. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  45577. };
  45578. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45579. /*** End of inlined file: juce_TabbedComponent.h ***/
  45580. /*** Start of inlined file: juce_DocumentWindow.h ***/
  45581. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45582. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45583. /*** Start of inlined file: juce_MenuBarModel.h ***/
  45584. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  45585. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  45586. /**
  45587. A class for controlling MenuBar components.
  45588. This class is used to tell a MenuBar what menus to show, and to respond
  45589. to a menu being selected.
  45590. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  45591. */
  45592. class JUCE_API MenuBarModel : private AsyncUpdater,
  45593. private ApplicationCommandManagerListener
  45594. {
  45595. public:
  45596. MenuBarModel() noexcept;
  45597. /** Destructor. */
  45598. virtual ~MenuBarModel();
  45599. /** Call this when some of your menu items have changed.
  45600. This method will cause a callback to any MenuBarListener objects that
  45601. are registered with this model.
  45602. If this model is displaying items from an ApplicationCommandManager, you
  45603. can use the setApplicationCommandManagerToWatch() method to cause
  45604. change messages to be sent automatically when the ApplicationCommandManager
  45605. is changed.
  45606. @see addListener, removeListener, MenuBarListener
  45607. */
  45608. void menuItemsChanged();
  45609. /** Tells the menu bar to listen to the specified command manager, and to update
  45610. itself when the commands change.
  45611. This will also allow it to flash a menu name when a command from that menu
  45612. is invoked using a keystroke.
  45613. */
  45614. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) noexcept;
  45615. /** A class to receive callbacks when a MenuBarModel changes.
  45616. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  45617. */
  45618. class JUCE_API Listener
  45619. {
  45620. public:
  45621. /** Destructor. */
  45622. virtual ~Listener() {}
  45623. /** This callback is made when items are changed in the menu bar model.
  45624. */
  45625. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  45626. /** This callback is made when an application command is invoked that
  45627. is represented by one of the items in the menu bar model.
  45628. */
  45629. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  45630. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  45631. };
  45632. /** Registers a listener for callbacks when the menu items in this model change.
  45633. The listener object will get callbacks when this object's menuItemsChanged()
  45634. method is called.
  45635. @see removeListener
  45636. */
  45637. void addListener (Listener* listenerToAdd) noexcept;
  45638. /** Removes a listener.
  45639. @see addListener
  45640. */
  45641. void removeListener (Listener* listenerToRemove) noexcept;
  45642. /** This method must return a list of the names of the menus. */
  45643. virtual const StringArray getMenuBarNames() = 0;
  45644. /** This should return the popup menu to display for a given top-level menu.
  45645. @param topLevelMenuIndex the index of the top-level menu to show
  45646. @param menuName the name of the top-level menu item to show
  45647. */
  45648. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  45649. const String& menuName) = 0;
  45650. /** This is called when a menu item has been clicked on.
  45651. @param menuItemID the item ID of the PopupMenu item that was selected
  45652. @param topLevelMenuIndex the index of the top-level menu from which the item was
  45653. chosen (just in case you've used duplicate ID numbers
  45654. on more than one of the popup menus)
  45655. */
  45656. virtual void menuItemSelected (int menuItemID,
  45657. int topLevelMenuIndex) = 0;
  45658. #if JUCE_MAC || DOXYGEN
  45659. /** MAC ONLY - Sets the model that is currently being shown as the main
  45660. menu bar at the top of the screen on the Mac.
  45661. You can pass 0 to stop the current model being displayed. Be careful
  45662. not to delete a model while it is being used.
  45663. An optional extra menu can be specified, containing items to add to the top of
  45664. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  45665. an apple, it's the one next to it, with your application's name at the top
  45666. and the services menu etc on it). When one of these items is selected, the
  45667. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  45668. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  45669. object then newMenuBarModel must be non-null.
  45670. */
  45671. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  45672. const PopupMenu* extraAppleMenuItems = nullptr);
  45673. /** MAC ONLY - Returns the menu model that is currently being shown as
  45674. the main menu bar.
  45675. */
  45676. static MenuBarModel* getMacMainMenu();
  45677. #endif
  45678. /** @internal */
  45679. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  45680. /** @internal */
  45681. void applicationCommandListChanged();
  45682. /** @internal */
  45683. void handleAsyncUpdate();
  45684. private:
  45685. ApplicationCommandManager* manager;
  45686. ListenerList <Listener> listeners;
  45687. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  45688. };
  45689. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  45690. typedef MenuBarModel::Listener MenuBarModelListener;
  45691. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  45692. /*** End of inlined file: juce_MenuBarModel.h ***/
  45693. /**
  45694. A resizable window with a title bar and maximise, minimise and close buttons.
  45695. This subclass of ResizableWindow creates a fairly standard type of window with
  45696. a title bar and various buttons. The name of the component is shown in the
  45697. title bar, and an icon can optionally be specified with setIcon().
  45698. All the methods available to a ResizableWindow are also available to this,
  45699. so it can easily be made resizable, minimised, maximised, etc.
  45700. It's not advisable to add child components directly to a DocumentWindow: put them
  45701. inside your content component instead. And overriding methods like resized(), moved(), etc
  45702. is also not recommended - instead override these methods for your content component.
  45703. (If for some obscure reason you do need to override these methods, always remember to
  45704. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  45705. decorations correctly).
  45706. You can also automatically add a menu bar to the window, using the setMenuBar()
  45707. method.
  45708. @see ResizableWindow, DialogWindow
  45709. */
  45710. class JUCE_API DocumentWindow : public ResizableWindow
  45711. {
  45712. public:
  45713. /** The set of available button-types that can be put on the title bar.
  45714. @see setTitleBarButtonsRequired
  45715. */
  45716. enum TitleBarButtons
  45717. {
  45718. minimiseButton = 1,
  45719. maximiseButton = 2,
  45720. closeButton = 4,
  45721. /** A combination of all the buttons above. */
  45722. allButtons = 7
  45723. };
  45724. /** Creates a DocumentWindow.
  45725. @param name the name to give the component - this is also
  45726. the title shown at the top of the window. To change
  45727. this later, use setName()
  45728. @param backgroundColour the colour to use for filling the window's background.
  45729. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45730. should be shown on the title bar. This value is a bitwise
  45731. combination of values from the TitleBarButtons enum. Note
  45732. that it can be "allButtons" to get them all. You
  45733. can change this later with the setTitleBarButtonsRequired()
  45734. method, which can also specify where they are positioned.
  45735. @param addToDesktop if true, the window will be automatically added to the
  45736. desktop; if false, you can use it as a child component
  45737. @see TitleBarButtons
  45738. */
  45739. DocumentWindow (const String& name,
  45740. const Colour& backgroundColour,
  45741. int requiredButtons,
  45742. bool addToDesktop = true);
  45743. /** Destructor.
  45744. If a content component has been set with setContentOwned(), it will be deleted.
  45745. */
  45746. ~DocumentWindow();
  45747. /** Changes the component's name.
  45748. (This is overridden from Component::setName() to cause a repaint, as
  45749. the name is what gets drawn across the window's title bar).
  45750. */
  45751. void setName (const String& newName);
  45752. /** Sets an icon to show in the title bar, next to the title.
  45753. A copy is made internally of the image, so the caller can delete the
  45754. image after calling this. If 0 is passed-in, any existing icon will be
  45755. removed.
  45756. */
  45757. void setIcon (const Image& imageToUse);
  45758. /** Changes the height of the title-bar. */
  45759. void setTitleBarHeight (int newHeight);
  45760. /** Returns the current title bar height. */
  45761. int getTitleBarHeight() const;
  45762. /** Changes the set of title-bar buttons being shown.
  45763. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45764. should be shown on the title bar. This value is a bitwise
  45765. combination of values from the TitleBarButtons enum. Note
  45766. that it can be "allButtons" to get them all.
  45767. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  45768. left side of the bar; if false, they'll be placed at the right
  45769. */
  45770. void setTitleBarButtonsRequired (int requiredButtons,
  45771. bool positionTitleBarButtonsOnLeft);
  45772. /** Sets whether the title should be centred within the window.
  45773. If true, the title text is shown in the middle of the title-bar; if false,
  45774. it'll be shown at the left of the bar.
  45775. */
  45776. void setTitleBarTextCentred (bool textShouldBeCentred);
  45777. /** Creates a menu inside this window.
  45778. @param menuBarModel this specifies a MenuBarModel that should be used to
  45779. generate the contents of a menu bar that will be placed
  45780. just below the title bar, and just above any content
  45781. component. If this value is zero, any existing menu bar
  45782. will be removed from the component; if non-zero, one will
  45783. be added if it's required.
  45784. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  45785. or less to use the look-and-feel's default size.
  45786. */
  45787. void setMenuBar (MenuBarModel* menuBarModel,
  45788. int menuBarHeight = 0);
  45789. /** Returns the current menu bar component, or null if there isn't one.
  45790. This is probably a MenuBarComponent, unless a custom one has been set using
  45791. setMenuBarComponent().
  45792. */
  45793. Component* getMenuBarComponent() const noexcept;
  45794. /** Replaces the current menu bar with a custom component.
  45795. The component will be owned and deleted by the document window.
  45796. */
  45797. void setMenuBarComponent (Component* newMenuBarComponent);
  45798. /** This method is called when the user tries to close the window.
  45799. This is triggered by the user clicking the close button, or using some other
  45800. OS-specific key shortcut or OS menu for getting rid of a window.
  45801. If the window is just a pop-up, you should override this closeButtonPressed()
  45802. method and make it delete the window in whatever way is appropriate for your
  45803. app. E.g. you might just want to call "delete this".
  45804. If your app is centred around this window such that the whole app should quit when
  45805. the window is closed, then you will probably want to use this method as an opportunity
  45806. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  45807. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  45808. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  45809. or closing it via the taskbar icon on Windows).
  45810. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  45811. redirects it to call this method, so any methods of closing the window that are
  45812. caught by userTriedToCloseWindow() will also end up here).
  45813. */
  45814. virtual void closeButtonPressed();
  45815. /** Callback that is triggered when the minimise button is pressed.
  45816. The default implementation of this calls ResizableWindow::setMinimised(), but
  45817. you can override it to do more customised behaviour.
  45818. */
  45819. virtual void minimiseButtonPressed();
  45820. /** Callback that is triggered when the maximise button is pressed, or when the
  45821. title-bar is double-clicked.
  45822. The default implementation of this calls ResizableWindow::setFullScreen(), but
  45823. you can override it to do more customised behaviour.
  45824. */
  45825. virtual void maximiseButtonPressed();
  45826. /** Returns the close button, (or 0 if there isn't one). */
  45827. Button* getCloseButton() const noexcept;
  45828. /** Returns the minimise button, (or 0 if there isn't one). */
  45829. Button* getMinimiseButton() const noexcept;
  45830. /** Returns the maximise button, (or 0 if there isn't one). */
  45831. Button* getMaximiseButton() const noexcept;
  45832. /** A set of colour IDs to use to change the colour of various aspects of the window.
  45833. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45834. methods.
  45835. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45836. */
  45837. enum ColourIds
  45838. {
  45839. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  45840. and feel class how this is used. */
  45841. };
  45842. #ifndef DOXYGEN
  45843. /** @internal */
  45844. void paint (Graphics& g);
  45845. /** @internal */
  45846. void resized();
  45847. /** @internal */
  45848. void lookAndFeelChanged();
  45849. /** @internal */
  45850. const BorderSize<int> getBorderThickness();
  45851. /** @internal */
  45852. const BorderSize<int> getContentComponentBorder();
  45853. /** @internal */
  45854. void mouseDoubleClick (const MouseEvent& e);
  45855. /** @internal */
  45856. void userTriedToCloseWindow();
  45857. /** @internal */
  45858. void activeWindowStatusChanged();
  45859. /** @internal */
  45860. int getDesktopWindowStyleFlags() const;
  45861. /** @internal */
  45862. void parentHierarchyChanged();
  45863. /** @internal */
  45864. const Rectangle<int> getTitleBarArea();
  45865. #endif
  45866. private:
  45867. int titleBarHeight, menuBarHeight, requiredButtons;
  45868. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  45869. ScopedPointer <Button> titleBarButtons [3];
  45870. Image titleBarIcon;
  45871. ScopedPointer <Component> menuBar;
  45872. MenuBarModel* menuBarModel;
  45873. class ButtonListenerProxy;
  45874. friend class ScopedPointer <ButtonListenerProxy>;
  45875. ScopedPointer <ButtonListenerProxy> buttonListener;
  45876. void repaintTitleBar();
  45877. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  45878. };
  45879. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45880. /*** End of inlined file: juce_DocumentWindow.h ***/
  45881. class MultiDocumentPanel;
  45882. class MDITabbedComponentInternal;
  45883. /**
  45884. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  45885. component.
  45886. It's like a normal DocumentWindow but has some extra functionality to make sure
  45887. everything works nicely inside a MultiDocumentPanel.
  45888. @see MultiDocumentPanel
  45889. */
  45890. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  45891. {
  45892. public:
  45893. /**
  45894. */
  45895. MultiDocumentPanelWindow (const Colour& backgroundColour);
  45896. /** Destructor. */
  45897. ~MultiDocumentPanelWindow();
  45898. /** @internal */
  45899. void maximiseButtonPressed();
  45900. /** @internal */
  45901. void closeButtonPressed();
  45902. /** @internal */
  45903. void activeWindowStatusChanged();
  45904. /** @internal */
  45905. void broughtToFront();
  45906. private:
  45907. void updateOrder();
  45908. MultiDocumentPanel* getOwner() const noexcept;
  45909. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  45910. };
  45911. /**
  45912. A component that contains a set of other components either in floating windows
  45913. or tabs.
  45914. This acts as a panel that can be used to hold a set of open document windows, with
  45915. different layout modes.
  45916. Use addDocument() and closeDocument() to add or remove components from the
  45917. panel - never use any of the Component methods to access the panel's child
  45918. components directly, as these are managed internally.
  45919. */
  45920. class JUCE_API MultiDocumentPanel : public Component,
  45921. private ComponentListener
  45922. {
  45923. public:
  45924. /** Creates an empty panel.
  45925. Use addDocument() and closeDocument() to add or remove components from the
  45926. panel - never use any of the Component methods to access the panel's child
  45927. components directly, as these are managed internally.
  45928. */
  45929. MultiDocumentPanel();
  45930. /** Destructor.
  45931. When deleted, this will call closeAllDocuments (false) to make sure all its
  45932. components are deleted. If you need to make sure all documents are saved
  45933. before closing, then you should call closeAllDocuments (true) and check that
  45934. it returns true before deleting the panel.
  45935. */
  45936. ~MultiDocumentPanel();
  45937. /** Tries to close all the documents.
  45938. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45939. be called for each open document, and any of these calls fails, this method
  45940. will stop and return false, leaving some documents still open.
  45941. If checkItsOkToCloseFirst is false, then all documents will be closed
  45942. unconditionally.
  45943. @see closeDocument
  45944. */
  45945. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  45946. /** Adds a document component to the panel.
  45947. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  45948. this will fail and return false. (If it does fail, the component passed-in will not be
  45949. deleted, even if deleteWhenRemoved was set to true).
  45950. The MultiDocumentPanel will deal with creating a window border to go around your component,
  45951. so just pass in the bare content component here, no need to give it a ResizableWindow
  45952. or DocumentWindow.
  45953. @param component the component to add
  45954. @param backgroundColour the background colour to use to fill the component's
  45955. window or tab
  45956. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  45957. or closeAllDocuments(), then it will be deleted. If false, then
  45958. the caller must handle the component's deletion
  45959. */
  45960. bool addDocument (Component* component,
  45961. const Colour& backgroundColour,
  45962. bool deleteWhenRemoved);
  45963. /** Closes one of the documents.
  45964. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45965. be called, and if it fails, this method will return false without closing the
  45966. document.
  45967. If checkItsOkToCloseFirst is false, then the documents will be closed
  45968. unconditionally.
  45969. The component will be deleted if the deleteWhenRemoved parameter was set to
  45970. true when it was added with addDocument.
  45971. @see addDocument, closeAllDocuments
  45972. */
  45973. bool closeDocument (Component* component,
  45974. bool checkItsOkToCloseFirst);
  45975. /** Returns the number of open document windows.
  45976. @see getDocument
  45977. */
  45978. int getNumDocuments() const noexcept;
  45979. /** Returns one of the open documents.
  45980. The order of the documents in this array may change when they are added, removed
  45981. or moved around.
  45982. @see getNumDocuments
  45983. */
  45984. Component* getDocument (int index) const noexcept;
  45985. /** Returns the document component that is currently focused or on top.
  45986. If currently using floating windows, then this will be the component in the currently
  45987. active window, or the top component if none are active.
  45988. If it's currently in tabbed mode, then it'll return the component in the active tab.
  45989. @see setActiveDocument
  45990. */
  45991. Component* getActiveDocument() const noexcept;
  45992. /** Makes one of the components active and brings it to the top.
  45993. @see getActiveDocument
  45994. */
  45995. void setActiveDocument (Component* component);
  45996. /** Callback which gets invoked when the currently-active document changes. */
  45997. virtual void activeDocumentChanged();
  45998. /** Sets a limit on how many windows can be open at once.
  45999. If this is zero or less there's no limit (the default). addDocument() will fail
  46000. if this number is exceeded.
  46001. */
  46002. void setMaximumNumDocuments (int maximumNumDocuments);
  46003. /** Sets an option to make the document fullscreen if there's only one document open.
  46004. If set to true, then if there's only one document, it'll fill the whole of this
  46005. component without tabs or a window border. If false, then tabs or a window
  46006. will always be shown, even if there's only one document. If there's more than
  46007. one document open, then this option makes no difference.
  46008. */
  46009. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  46010. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  46011. */
  46012. bool isFullscreenWhenOneDocument() const noexcept;
  46013. /** The different layout modes available. */
  46014. enum LayoutMode
  46015. {
  46016. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  46017. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  46018. };
  46019. /** Changes the panel's mode.
  46020. @see LayoutMode, getLayoutMode
  46021. */
  46022. void setLayoutMode (LayoutMode newLayoutMode);
  46023. /** Returns the current layout mode. */
  46024. LayoutMode getLayoutMode() const noexcept { return mode; }
  46025. /** Sets the background colour for the whole panel.
  46026. Each document has its own background colour, but this is the one used to fill the areas
  46027. behind them.
  46028. */
  46029. void setBackgroundColour (const Colour& newBackgroundColour);
  46030. /** Returns the current background colour.
  46031. @see setBackgroundColour
  46032. */
  46033. const Colour& getBackgroundColour() const noexcept { return backgroundColour; }
  46034. /** A subclass must override this to say whether its currently ok for a document
  46035. to be closed.
  46036. This method is called by closeDocument() and closeAllDocuments() to indicate that
  46037. a document should be saved if possible, ready for it to be closed.
  46038. If this method returns true, then it means the document is ok and can be closed.
  46039. If it returns false, then it means that the closeDocument() method should stop
  46040. and not close.
  46041. Normally, you'd use this method to ask the user if they want to save any changes,
  46042. then return true if the save operation went ok. If the user cancelled the save
  46043. operation you could return false here to abort the close operation.
  46044. If your component is based on the FileBasedDocument class, then you'd probably want
  46045. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  46046. FileBasedDocument::savedOk
  46047. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  46048. */
  46049. virtual bool tryToCloseDocument (Component* component) = 0;
  46050. /** Creates a new window to be used for a document.
  46051. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  46052. but you might want to override it to return a custom component.
  46053. */
  46054. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  46055. /** @internal */
  46056. void paint (Graphics& g);
  46057. /** @internal */
  46058. void resized();
  46059. /** @internal */
  46060. void componentNameChanged (Component&);
  46061. private:
  46062. LayoutMode mode;
  46063. Array <Component*> components;
  46064. ScopedPointer<TabbedComponent> tabComponent;
  46065. Colour backgroundColour;
  46066. int maximumNumDocuments, numDocsBeforeTabsUsed;
  46067. friend class MultiDocumentPanelWindow;
  46068. friend class MDITabbedComponentInternal;
  46069. Component* getContainerComp (Component* c) const;
  46070. void updateOrder();
  46071. void addWindow (Component* component);
  46072. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  46073. };
  46074. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  46075. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  46076. #endif
  46077. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  46078. #endif
  46079. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  46080. #endif
  46081. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46082. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  46083. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46084. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46085. /**
  46086. A component that resizes its parent component when dragged.
  46087. This component forms a bar along one edge of a component, allowing it to
  46088. be dragged by that edges to resize it.
  46089. To use it, just add it to your component, positioning it along the appropriate
  46090. edge. Make sure you reposition the resizer component each time the parent's size
  46091. changes, to keep it in the correct position.
  46092. @see ResizbleBorderComponent, ResizableCornerComponent
  46093. */
  46094. class JUCE_API ResizableEdgeComponent : public Component
  46095. {
  46096. public:
  46097. enum Edge
  46098. {
  46099. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  46100. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  46101. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  46102. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  46103. };
  46104. /** Creates a resizer bar.
  46105. Pass in the target component which you want to be resized when this one is
  46106. dragged. The target component will usually be this component's parent, but this
  46107. isn't mandatory.
  46108. Remember that when the target component is resized, it'll need to move and
  46109. resize this component to keep it in place, as this won't happen automatically.
  46110. If the constrainer parameter is non-zero, then this object will be used to enforce
  46111. limits on the size and position that the component can be stretched to. Make sure
  46112. that the constrainer isn't deleted while still in use by this object.
  46113. @see ComponentBoundsConstrainer
  46114. */
  46115. ResizableEdgeComponent (Component* componentToResize,
  46116. ComponentBoundsConstrainer* constrainer,
  46117. Edge edgeToResize);
  46118. /** Destructor. */
  46119. ~ResizableEdgeComponent();
  46120. bool isVertical() const noexcept;
  46121. protected:
  46122. /** @internal */
  46123. void paint (Graphics& g);
  46124. /** @internal */
  46125. void mouseDown (const MouseEvent& e);
  46126. /** @internal */
  46127. void mouseDrag (const MouseEvent& e);
  46128. /** @internal */
  46129. void mouseUp (const MouseEvent& e);
  46130. private:
  46131. WeakReference<Component> component;
  46132. ComponentBoundsConstrainer* constrainer;
  46133. Rectangle<int> originalBounds;
  46134. const Edge edge;
  46135. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  46136. };
  46137. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46138. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  46139. #endif
  46140. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  46141. #endif
  46142. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46143. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  46144. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46145. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46146. /**
  46147. For laying out a set of components, where the components have preferred sizes
  46148. and size limits, but where they are allowed to stretch to fill the available
  46149. space.
  46150. For example, if you have a component containing several other components, and
  46151. each one should be given a share of the total size, you could use one of these
  46152. to resize the child components when the parent component is resized. Then
  46153. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  46154. A StretchableLayoutManager operates only in one dimension, so if you have a set
  46155. of components stacked vertically on top of each other, you'd use one to manage their
  46156. heights. To build up complex arrangements of components, e.g. for applications
  46157. with multiple nested panels, you would use more than one StretchableLayoutManager.
  46158. E.g. by using two (one vertical, one horizontal), you could create a resizable
  46159. spreadsheet-style table.
  46160. E.g.
  46161. @code
  46162. class MyComp : public Component
  46163. {
  46164. StretchableLayoutManager myLayout;
  46165. MyComp()
  46166. {
  46167. myLayout.setItemLayout (0, // for item 0
  46168. 50, 100, // must be between 50 and 100 pixels in size
  46169. -0.6); // and its preferred size is 60% of the total available space
  46170. myLayout.setItemLayout (1, // for item 1
  46171. -0.2, -0.6, // size must be between 20% and 60% of the available space
  46172. 50); // and its preferred size is 50 pixels
  46173. }
  46174. void resized()
  46175. {
  46176. // make a list of two of our child components that we want to reposition
  46177. Component* comps[] = { myComp1, myComp2 };
  46178. // this will position the 2 components, one above the other, to fit
  46179. // vertically into the rectangle provided.
  46180. myLayout.layOutComponents (comps, 2,
  46181. 0, 0, getWidth(), getHeight(),
  46182. true);
  46183. }
  46184. };
  46185. @endcode
  46186. @see StretchableLayoutResizerBar
  46187. */
  46188. class JUCE_API StretchableLayoutManager
  46189. {
  46190. public:
  46191. /** Creates an empty layout.
  46192. You'll need to add some item properties to the layout before it can be used
  46193. to resize things - see setItemLayout().
  46194. */
  46195. StretchableLayoutManager();
  46196. /** Destructor. */
  46197. ~StretchableLayoutManager();
  46198. /** For a numbered item, this sets its size limits and preferred size.
  46199. @param itemIndex the index of the item to change.
  46200. @param minimumSize the minimum size that this item is allowed to be - a positive number
  46201. indicates an absolute size in pixels. A negative number indicates a
  46202. proportion of the available space (e.g -0.5 is 50%)
  46203. @param maximumSize the maximum size that this item is allowed to be - a positive number
  46204. indicates an absolute size in pixels. A negative number indicates a
  46205. proportion of the available space
  46206. @param preferredSize the size that this item would like to be, if there's enough room. A
  46207. positive number indicates an absolute size in pixels. A negative number
  46208. indicates a proportion of the available space
  46209. @see getItemLayout
  46210. */
  46211. void setItemLayout (int itemIndex,
  46212. double minimumSize,
  46213. double maximumSize,
  46214. double preferredSize);
  46215. /** For a numbered item, this returns its size limits and preferred size.
  46216. @param itemIndex the index of the item.
  46217. @param minimumSize the minimum size that this item is allowed to be - a positive number
  46218. indicates an absolute size in pixels. A negative number indicates a
  46219. proportion of the available space (e.g -0.5 is 50%)
  46220. @param maximumSize the maximum size that this item is allowed to be - a positive number
  46221. indicates an absolute size in pixels. A negative number indicates a
  46222. proportion of the available space
  46223. @param preferredSize the size that this item would like to be, if there's enough room. A
  46224. positive number indicates an absolute size in pixels. A negative number
  46225. indicates a proportion of the available space
  46226. @returns false if the item's properties hadn't been set
  46227. @see setItemLayout
  46228. */
  46229. bool getItemLayout (int itemIndex,
  46230. double& minimumSize,
  46231. double& maximumSize,
  46232. double& preferredSize) const;
  46233. /** Clears all the properties that have been set with setItemLayout() and resets
  46234. this object to its initial state.
  46235. */
  46236. void clearAllItems();
  46237. /** Takes a set of components that correspond to the layout's items, and positions
  46238. them to fill a space.
  46239. This will try to give each item its preferred size, whether that's a relative size
  46240. or an absolute one.
  46241. @param components an array of components that correspond to each of the
  46242. numbered items that the StretchableLayoutManager object
  46243. has been told about with setItemLayout()
  46244. @param numComponents the number of components in the array that is passed-in. This
  46245. should be the same as the number of items this object has been
  46246. told about.
  46247. @param x the left of the rectangle in which the components should
  46248. be laid out
  46249. @param y the top of the rectangle in which the components should
  46250. be laid out
  46251. @param width the width of the rectangle in which the components should
  46252. be laid out
  46253. @param height the height of the rectangle in which the components should
  46254. be laid out
  46255. @param vertically if true, the components will be positioned in a vertical stack,
  46256. so that they fill the height of the rectangle. If false, they
  46257. will be placed side-by-side in a horizontal line, filling the
  46258. available width
  46259. @param resizeOtherDimension if true, this means that the components will have their
  46260. other dimension resized to fit the space - i.e. if the 'vertically'
  46261. parameter is true, their x-positions and widths are adjusted to fit
  46262. the x and width parameters; if 'vertically' is false, their y-positions
  46263. and heights are adjusted to fit the y and height parameters.
  46264. */
  46265. void layOutComponents (Component** components,
  46266. int numComponents,
  46267. int x, int y, int width, int height,
  46268. bool vertically,
  46269. bool resizeOtherDimension);
  46270. /** Returns the current position of one of the items.
  46271. This is only a valid call after layOutComponents() has been called, as it
  46272. returns the last position that this item was placed at. If the layout was
  46273. vertical, the value returned will be the y position of the top of the item,
  46274. relative to the top of the rectangle in which the items were placed (so for
  46275. example, item 0 will always have position of 0, even in the rectangle passed
  46276. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  46277. the position returned is the item's left-hand position, again relative to the
  46278. x position of the rectangle used.
  46279. @see getItemCurrentSize, setItemPosition
  46280. */
  46281. int getItemCurrentPosition (int itemIndex) const;
  46282. /** Returns the current size of one of the items.
  46283. This is only meaningful after layOutComponents() has been called, as it
  46284. returns the last size that this item was given. If the layout was done
  46285. vertically, it'll return the item's height in pixels; if it was horizontal,
  46286. it'll return its width.
  46287. @see getItemCurrentRelativeSize
  46288. */
  46289. int getItemCurrentAbsoluteSize (int itemIndex) const;
  46290. /** Returns the current size of one of the items.
  46291. This is only meaningful after layOutComponents() has been called, as it
  46292. returns the last size that this item was given. If the layout was done
  46293. vertically, it'll return a negative value representing the item's height relative
  46294. to the last size used for laying the components out; if the layout was done
  46295. horizontally it'll be the proportion of its width.
  46296. @see getItemCurrentAbsoluteSize
  46297. */
  46298. double getItemCurrentRelativeSize (int itemIndex) const;
  46299. /** Moves one of the items, shifting along any other items as necessary in
  46300. order to get it to the desired position.
  46301. Calling this method will also update the preferred sizes of the items it
  46302. shuffles along, so that they reflect their new positions.
  46303. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  46304. about when it's dragged).
  46305. @param itemIndex the item to move
  46306. @param newPosition the absolute position that you'd like this item to move
  46307. to. The item might not be able to always reach exactly this position,
  46308. because other items may have minimum sizes that constrain how
  46309. far it can go
  46310. */
  46311. void setItemPosition (int itemIndex,
  46312. int newPosition);
  46313. private:
  46314. struct ItemLayoutProperties
  46315. {
  46316. int itemIndex;
  46317. int currentSize;
  46318. double minSize, maxSize, preferredSize;
  46319. };
  46320. OwnedArray <ItemLayoutProperties> items;
  46321. int totalSize;
  46322. static int sizeToRealSize (double size, int totalSpace);
  46323. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  46324. void setTotalSize (int newTotalSize);
  46325. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  46326. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  46327. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  46328. void updatePrefSizesToMatchCurrentPositions();
  46329. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  46330. };
  46331. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46332. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  46333. #endif
  46334. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46335. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  46336. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46337. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46338. /**
  46339. A component that acts as one of the vertical or horizontal bars you see being
  46340. used to resize panels in a window.
  46341. One of these acts with a StretchableLayoutManager to resize the other components.
  46342. @see StretchableLayoutManager
  46343. */
  46344. class JUCE_API StretchableLayoutResizerBar : public Component
  46345. {
  46346. public:
  46347. /** Creates a resizer bar for use on a specified layout.
  46348. @param layoutToUse the layout that will be affected when this bar
  46349. is dragged
  46350. @param itemIndexInLayout the item index in the layout that corresponds to
  46351. this bar component. You'll need to set up the item
  46352. properties in a suitable way for a divider bar, e.g.
  46353. for an 8-pixel wide bar which, you could call
  46354. myLayout->setItemLayout (barIndex, 8, 8, 8)
  46355. @param isBarVertical true if it's an upright bar that you drag left and
  46356. right; false for a horizontal one that you drag up and
  46357. down
  46358. */
  46359. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  46360. int itemIndexInLayout,
  46361. bool isBarVertical);
  46362. /** Destructor. */
  46363. ~StretchableLayoutResizerBar();
  46364. /** This is called when the bar is dragged.
  46365. This method must update the positions of any components whose position is
  46366. determined by the StretchableLayoutManager, because they might have just
  46367. moved.
  46368. The default implementation calls the resized() method of this component's
  46369. parent component, because that's often where you're likely to apply the
  46370. layout, but it can be overridden for more specific needs.
  46371. */
  46372. virtual void hasBeenMoved();
  46373. /** @internal */
  46374. void paint (Graphics& g);
  46375. /** @internal */
  46376. void mouseDown (const MouseEvent& e);
  46377. /** @internal */
  46378. void mouseDrag (const MouseEvent& e);
  46379. private:
  46380. StretchableLayoutManager* layout;
  46381. int itemIndex, mouseDownPos;
  46382. bool isVertical;
  46383. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  46384. };
  46385. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46386. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  46387. #endif
  46388. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46389. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  46390. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46391. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46392. /**
  46393. A utility class for fitting a set of objects whose sizes can vary between
  46394. a minimum and maximum size, into a space.
  46395. This is a trickier algorithm than it would first seem, so I've put it in this
  46396. class to allow it to be shared by various bits of code.
  46397. To use it, create one of these objects, call addItem() to add the list of items
  46398. you need, then call resizeToFit(), which will change all their sizes. You can
  46399. then retrieve the new sizes with getItemSize() and getNumItems().
  46400. It's currently used by the TableHeaderComponent for stretching out the table
  46401. headings to fill the table's width.
  46402. */
  46403. class StretchableObjectResizer
  46404. {
  46405. public:
  46406. /** Creates an empty object resizer. */
  46407. StretchableObjectResizer();
  46408. /** Destructor. */
  46409. ~StretchableObjectResizer();
  46410. /** Adds an item to the list.
  46411. The order parameter lets you specify groups of items that are resized first when some
  46412. space needs to be found. Those items with an order of 0 will be the first ones to be
  46413. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  46414. will then try resizing the items with an order of 1, then 2, and so on.
  46415. */
  46416. void addItem (double currentSize,
  46417. double minSize,
  46418. double maxSize,
  46419. int order = 0);
  46420. /** Resizes all the items to fit this amount of space.
  46421. This will attempt to fit them in without exceeding each item's miniumum and
  46422. maximum sizes. In cases where none of the items can be expanded or enlarged any
  46423. further, the final size may be greater or less than the size passed in.
  46424. After calling this method, you can retrieve the new sizes with the getItemSize()
  46425. method.
  46426. */
  46427. void resizeToFit (double targetSize);
  46428. /** Returns the number of items that have been added. */
  46429. int getNumItems() const noexcept { return items.size(); }
  46430. /** Returns the size of one of the items. */
  46431. double getItemSize (int index) const noexcept;
  46432. private:
  46433. struct Item
  46434. {
  46435. double size;
  46436. double minSize;
  46437. double maxSize;
  46438. int order;
  46439. };
  46440. OwnedArray <Item> items;
  46441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  46442. };
  46443. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46444. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  46445. #endif
  46446. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  46447. #endif
  46448. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  46449. #endif
  46450. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  46451. #endif
  46452. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  46453. /*** Start of inlined file: juce_LookAndFeel.h ***/
  46454. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  46455. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  46456. class ToggleButton;
  46457. class TextButton;
  46458. class AlertWindow;
  46459. class TextLayout;
  46460. class ScrollBar;
  46461. class BubbleComponent;
  46462. class ComboBox;
  46463. class Button;
  46464. class FilenameComponent;
  46465. class DocumentWindow;
  46466. class ResizableWindow;
  46467. class GroupComponent;
  46468. class MenuBarComponent;
  46469. class DropShadower;
  46470. class GlyphArrangement;
  46471. class PropertyComponent;
  46472. class TableHeaderComponent;
  46473. class Toolbar;
  46474. class ToolbarItemComponent;
  46475. class PopupMenu;
  46476. class ProgressBar;
  46477. class FileBrowserComponent;
  46478. class DirectoryContentsDisplayComponent;
  46479. class FilePreviewComponent;
  46480. class ImageButton;
  46481. class CallOutBox;
  46482. class Drawable;
  46483. class CaretComponent;
  46484. /**
  46485. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  46486. can be used to apply different 'skins' to the application.
  46487. */
  46488. class JUCE_API LookAndFeel
  46489. {
  46490. public:
  46491. /** Creates the default JUCE look and feel. */
  46492. LookAndFeel();
  46493. /** Destructor. */
  46494. virtual ~LookAndFeel();
  46495. /** Returns the current default look-and-feel for a component to use when it
  46496. hasn't got one explicitly set.
  46497. @see setDefaultLookAndFeel
  46498. */
  46499. static LookAndFeel& getDefaultLookAndFeel() noexcept;
  46500. /** Changes the default look-and-feel.
  46501. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  46502. set to null, it will revert to using the default one. The
  46503. object passed-in must be deleted by the caller when
  46504. it's no longer needed.
  46505. @see getDefaultLookAndFeel
  46506. */
  46507. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) noexcept;
  46508. /** Looks for a colour that has been registered with the given colour ID number.
  46509. If a colour has been set for this ID number using setColour(), then it is
  46510. returned. If none has been set, it will just return Colours::black.
  46511. The colour IDs for various purposes are stored as enums in the components that
  46512. they are relevent to - for an example, see Slider::ColourIds,
  46513. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  46514. If you're looking up a colour for use in drawing a component, it's usually
  46515. best not to call this directly, but to use the Component::findColour() method
  46516. instead. That will first check whether a suitable colour has been registered
  46517. directly with the component, and will fall-back on calling the component's
  46518. LookAndFeel's findColour() method if none is found.
  46519. @see setColour, Component::findColour, Component::setColour
  46520. */
  46521. const Colour findColour (int colourId) const noexcept;
  46522. /** Registers a colour to be used for a particular purpose.
  46523. For more details, see the comments for findColour().
  46524. @see findColour, Component::findColour, Component::setColour
  46525. */
  46526. void setColour (int colourId, const Colour& colour) noexcept;
  46527. /** Returns true if the specified colour ID has been explicitly set using the
  46528. setColour() method.
  46529. */
  46530. bool isColourSpecified (int colourId) const noexcept;
  46531. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  46532. /** Allows you to change the default sans-serif font.
  46533. If you need to supply your own Typeface object for any of the default fonts, rather
  46534. than just supplying the name (e.g. if you want to use an embedded font), then
  46535. you should instead override getTypefaceForFont() to create and return the typeface.
  46536. */
  46537. void setDefaultSansSerifTypefaceName (const String& newName);
  46538. /** Override this to get the chance to swap a component's mouse cursor for a
  46539. customised one.
  46540. */
  46541. virtual const MouseCursor getMouseCursorFor (Component& component);
  46542. /** Draws the lozenge-shaped background for a standard button. */
  46543. virtual void drawButtonBackground (Graphics& g,
  46544. Button& button,
  46545. const Colour& backgroundColour,
  46546. bool isMouseOverButton,
  46547. bool isButtonDown);
  46548. virtual const Font getFontForTextButton (TextButton& button);
  46549. /** Draws the text for a TextButton. */
  46550. virtual void drawButtonText (Graphics& g,
  46551. TextButton& button,
  46552. bool isMouseOverButton,
  46553. bool isButtonDown);
  46554. /** Draws the contents of a standard ToggleButton. */
  46555. virtual void drawToggleButton (Graphics& g,
  46556. ToggleButton& button,
  46557. bool isMouseOverButton,
  46558. bool isButtonDown);
  46559. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  46560. virtual void drawTickBox (Graphics& g,
  46561. Component& component,
  46562. float x, float y, float w, float h,
  46563. bool ticked,
  46564. bool isEnabled,
  46565. bool isMouseOverButton,
  46566. bool isButtonDown);
  46567. /* AlertWindow handling..
  46568. */
  46569. virtual AlertWindow* createAlertWindow (const String& title,
  46570. const String& message,
  46571. const String& button1,
  46572. const String& button2,
  46573. const String& button3,
  46574. AlertWindow::AlertIconType iconType,
  46575. int numButtons,
  46576. Component* associatedComponent);
  46577. virtual void drawAlertBox (Graphics& g,
  46578. AlertWindow& alert,
  46579. const Rectangle<int>& textArea,
  46580. TextLayout& textLayout);
  46581. virtual int getAlertBoxWindowFlags();
  46582. virtual int getAlertWindowButtonHeight();
  46583. virtual const Font getAlertWindowMessageFont();
  46584. virtual const Font getAlertWindowFont();
  46585. void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
  46586. bool isUsingNativeAlertWindows();
  46587. /** Draws a progress bar.
  46588. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  46589. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  46590. isn't known). It can use the current time as a basis for playing an animation.
  46591. (Used by progress bars in AlertWindow).
  46592. */
  46593. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46594. int width, int height,
  46595. double progress, const String& textToShow);
  46596. // Draws a small image that spins to indicate that something's happening..
  46597. // This method should use the current time to animate itself, so just keep
  46598. // repainting it every so often.
  46599. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  46600. int x, int y, int w, int h);
  46601. /** Draws one of the buttons on a scrollbar.
  46602. @param g the context to draw into
  46603. @param scrollbar the bar itself
  46604. @param width the width of the button
  46605. @param height the height of the button
  46606. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  46607. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46608. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  46609. @param isButtonDown whether the mouse button's held down
  46610. */
  46611. virtual void drawScrollbarButton (Graphics& g,
  46612. ScrollBar& scrollbar,
  46613. int width, int height,
  46614. int buttonDirection,
  46615. bool isScrollbarVertical,
  46616. bool isMouseOverButton,
  46617. bool isButtonDown);
  46618. /** Draws the thumb area of a scrollbar.
  46619. @param g the context to draw into
  46620. @param scrollbar the bar itself
  46621. @param x the x position of the left edge of the thumb area to draw in
  46622. @param y the y position of the top edge of the thumb area to draw in
  46623. @param width the width of the thumb area to draw in
  46624. @param height the height of the thumb area to draw in
  46625. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46626. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  46627. thumb, or its x position for horizontal bars
  46628. @param thumbSize for vertical bars, the height of the thumb, or its width for
  46629. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  46630. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  46631. currently dragging the thumb
  46632. @param isMouseDown whether the mouse is currently dragging the scrollbar
  46633. */
  46634. virtual void drawScrollbar (Graphics& g,
  46635. ScrollBar& scrollbar,
  46636. int x, int y,
  46637. int width, int height,
  46638. bool isScrollbarVertical,
  46639. int thumbStartPosition,
  46640. int thumbSize,
  46641. bool isMouseOver,
  46642. bool isMouseDown);
  46643. /** Returns the component effect to use for a scrollbar */
  46644. virtual ImageEffectFilter* getScrollbarEffect();
  46645. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  46646. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  46647. /** Returns the default thickness to use for a scrollbar. */
  46648. virtual int getDefaultScrollbarWidth();
  46649. /** Returns the length in pixels to use for a scrollbar button. */
  46650. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  46651. /** Returns a tick shape for use in yes/no boxes, etc. */
  46652. virtual const Path getTickShape (float height);
  46653. /** Returns a cross shape for use in yes/no boxes, etc. */
  46654. virtual const Path getCrossShape (float height);
  46655. /** Draws the + or - box in a treeview. */
  46656. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  46657. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  46658. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  46659. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
  46660. // These return a pointer to an internally cached drawable - make sure you don't keep
  46661. // a copy of this pointer anywhere, as it may become invalid in the future.
  46662. virtual const Drawable* getDefaultFolderImage();
  46663. virtual const Drawable* getDefaultDocumentFileImage();
  46664. virtual void createFileChooserHeaderText (const String& title,
  46665. const String& instructions,
  46666. GlyphArrangement& destArrangement,
  46667. int width);
  46668. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  46669. const String& filename, Image* icon,
  46670. const String& fileSizeDescription,
  46671. const String& fileTimeDescription,
  46672. bool isDirectory,
  46673. bool isItemSelected,
  46674. int itemIndex,
  46675. DirectoryContentsDisplayComponent& component);
  46676. virtual Button* createFileBrowserGoUpButton();
  46677. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  46678. DirectoryContentsDisplayComponent* fileListComponent,
  46679. FilePreviewComponent* previewComp,
  46680. ComboBox* currentPathBox,
  46681. TextEditor* filenameBox,
  46682. Button* goUpButton);
  46683. virtual void drawBubble (Graphics& g,
  46684. float tipX, float tipY,
  46685. float boxX, float boxY, float boxW, float boxH);
  46686. /** Fills the background of a popup menu component. */
  46687. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46688. /** Draws one of the items in a popup menu. */
  46689. virtual void drawPopupMenuItem (Graphics& g,
  46690. int width, int height,
  46691. bool isSeparator,
  46692. bool isActive,
  46693. bool isHighlighted,
  46694. bool isTicked,
  46695. bool hasSubMenu,
  46696. const String& text,
  46697. const String& shortcutKeyText,
  46698. Image* image,
  46699. const Colour* const textColour);
  46700. /** Returns the size and style of font to use in popup menus. */
  46701. virtual const Font getPopupMenuFont();
  46702. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  46703. int width, int height,
  46704. bool isScrollUpArrow);
  46705. /** Finds the best size for an item in a popup menu. */
  46706. virtual void getIdealPopupMenuItemSize (const String& text,
  46707. bool isSeparator,
  46708. int standardMenuItemHeight,
  46709. int& idealWidth,
  46710. int& idealHeight);
  46711. virtual int getMenuWindowFlags();
  46712. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46713. bool isMouseOverBar,
  46714. MenuBarComponent& menuBar);
  46715. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46716. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46717. virtual void drawMenuBarItem (Graphics& g,
  46718. int width, int height,
  46719. int itemIndex,
  46720. const String& itemText,
  46721. bool isMouseOverItem,
  46722. bool isMenuOpen,
  46723. bool isMouseOverBar,
  46724. MenuBarComponent& menuBar);
  46725. virtual void drawComboBox (Graphics& g, int width, int height,
  46726. bool isButtonDown,
  46727. int buttonX, int buttonY,
  46728. int buttonW, int buttonH,
  46729. ComboBox& box);
  46730. virtual const Font getComboBoxFont (ComboBox& box);
  46731. virtual Label* createComboBoxTextBox (ComboBox& box);
  46732. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  46733. virtual void drawLabel (Graphics& g, Label& label);
  46734. virtual void drawLinearSlider (Graphics& g,
  46735. int x, int y,
  46736. int width, int height,
  46737. float sliderPos,
  46738. float minSliderPos,
  46739. float maxSliderPos,
  46740. const Slider::SliderStyle style,
  46741. Slider& slider);
  46742. virtual void drawLinearSliderBackground (Graphics& g,
  46743. int x, int y,
  46744. int width, int height,
  46745. float sliderPos,
  46746. float minSliderPos,
  46747. float maxSliderPos,
  46748. const Slider::SliderStyle style,
  46749. Slider& slider);
  46750. virtual void drawLinearSliderThumb (Graphics& g,
  46751. int x, int y,
  46752. int width, int height,
  46753. float sliderPos,
  46754. float minSliderPos,
  46755. float maxSliderPos,
  46756. const Slider::SliderStyle style,
  46757. Slider& slider);
  46758. virtual int getSliderThumbRadius (Slider& slider);
  46759. virtual void drawRotarySlider (Graphics& g,
  46760. int x, int y,
  46761. int width, int height,
  46762. float sliderPosProportional,
  46763. float rotaryStartAngle,
  46764. float rotaryEndAngle,
  46765. Slider& slider);
  46766. virtual Button* createSliderButton (bool isIncrement);
  46767. virtual Label* createSliderTextBox (Slider& slider);
  46768. virtual ImageEffectFilter* getSliderEffect();
  46769. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  46770. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  46771. virtual Button* createFilenameComponentBrowseButton (const String& text);
  46772. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  46773. ComboBox* filenameBox, Button* browseButton);
  46774. virtual void drawCornerResizer (Graphics& g,
  46775. int w, int h,
  46776. bool isMouseOver,
  46777. bool isMouseDragging);
  46778. virtual void drawResizableFrame (Graphics& g,
  46779. int w, int h,
  46780. const BorderSize<int>& borders);
  46781. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  46782. const BorderSize<int>& border,
  46783. ResizableWindow& window);
  46784. virtual void drawResizableWindowBorder (Graphics& g,
  46785. int w, int h,
  46786. const BorderSize<int>& border,
  46787. ResizableWindow& window);
  46788. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  46789. Graphics& g, int w, int h,
  46790. int titleSpaceX, int titleSpaceW,
  46791. const Image* icon,
  46792. bool drawTitleTextOnLeft);
  46793. virtual Button* createDocumentWindowButton (int buttonType);
  46794. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46795. int titleBarX, int titleBarY,
  46796. int titleBarW, int titleBarH,
  46797. Button* minimiseButton,
  46798. Button* maximiseButton,
  46799. Button* closeButton,
  46800. bool positionTitleBarButtonsOnLeft);
  46801. virtual int getDefaultMenuBarHeight();
  46802. virtual DropShadower* createDropShadowerForComponent (Component* component);
  46803. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  46804. int w, int h,
  46805. bool isVerticalBar,
  46806. bool isMouseOver,
  46807. bool isMouseDragging);
  46808. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  46809. const String& text,
  46810. const Justification& position,
  46811. GroupComponent& group);
  46812. virtual void createTabButtonShape (Path& p,
  46813. int width, int height,
  46814. int tabIndex,
  46815. const String& text,
  46816. Button& button,
  46817. TabbedButtonBar::Orientation orientation,
  46818. bool isMouseOver,
  46819. bool isMouseDown,
  46820. bool isFrontTab);
  46821. virtual void fillTabButtonShape (Graphics& g,
  46822. const Path& path,
  46823. const Colour& preferredBackgroundColour,
  46824. int tabIndex,
  46825. const String& text,
  46826. Button& button,
  46827. TabbedButtonBar::Orientation orientation,
  46828. bool isMouseOver,
  46829. bool isMouseDown,
  46830. bool isFrontTab);
  46831. virtual void drawTabButtonText (Graphics& g,
  46832. int x, int y, int w, int h,
  46833. const Colour& preferredBackgroundColour,
  46834. int tabIndex,
  46835. const String& text,
  46836. Button& button,
  46837. TabbedButtonBar::Orientation orientation,
  46838. bool isMouseOver,
  46839. bool isMouseDown,
  46840. bool isFrontTab);
  46841. virtual int getTabButtonOverlap (int tabDepth);
  46842. virtual int getTabButtonSpaceAroundImage();
  46843. virtual int getTabButtonBestWidth (int tabIndex,
  46844. const String& text,
  46845. int tabDepth,
  46846. Button& button);
  46847. virtual void drawTabButton (Graphics& g,
  46848. int w, int h,
  46849. const Colour& preferredColour,
  46850. int tabIndex,
  46851. const String& text,
  46852. Button& button,
  46853. TabbedButtonBar::Orientation orientation,
  46854. bool isMouseOver,
  46855. bool isMouseDown,
  46856. bool isFrontTab);
  46857. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  46858. int w, int h,
  46859. TabbedButtonBar& tabBar,
  46860. TabbedButtonBar::Orientation orientation);
  46861. virtual Button* createTabBarExtrasButton();
  46862. virtual void drawImageButton (Graphics& g, Image* image,
  46863. int imageX, int imageY, int imageW, int imageH,
  46864. const Colour& overlayColour,
  46865. float imageOpacity,
  46866. ImageButton& button);
  46867. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  46868. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  46869. int width, int height,
  46870. bool isMouseOver, bool isMouseDown,
  46871. int columnFlags);
  46872. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  46873. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  46874. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  46875. bool isMouseOver, bool isMouseDown,
  46876. ToolbarItemComponent& component);
  46877. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  46878. const String& text, ToolbarItemComponent& component);
  46879. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  46880. bool isOpen, int width, int height);
  46881. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  46882. PropertyComponent& component);
  46883. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  46884. PropertyComponent& component);
  46885. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  46886. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  46887. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  46888. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  46889. /**
  46890. */
  46891. virtual void playAlertSound();
  46892. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  46893. static void drawGlassSphere (Graphics& g,
  46894. float x, float y,
  46895. float diameter,
  46896. const Colour& colour,
  46897. float outlineThickness) noexcept;
  46898. static void drawGlassPointer (Graphics& g,
  46899. float x, float y,
  46900. float diameter,
  46901. const Colour& colour, float outlineThickness,
  46902. int direction) noexcept;
  46903. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  46904. static void drawGlassLozenge (Graphics& g,
  46905. float x, float y,
  46906. float width, float height,
  46907. const Colour& colour,
  46908. float outlineThickness,
  46909. float cornerSize,
  46910. bool flatOnLeft, bool flatOnRight,
  46911. bool flatOnTop, bool flatOnBottom) noexcept;
  46912. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  46913. private:
  46914. friend class WeakReference<LookAndFeel>;
  46915. WeakReference<LookAndFeel>::Master weakReferenceMaster;
  46916. const WeakReference<LookAndFeel>::SharedRef& getWeakReference();
  46917. Array <int> colourIds;
  46918. Array <Colour> colours;
  46919. // default typeface names
  46920. String defaultSans, defaultSerif, defaultFixed;
  46921. ScopedPointer<Drawable> folderImage, documentImage;
  46922. bool useNativeAlertWindows;
  46923. void drawShinyButtonShape (Graphics& g,
  46924. float x, float y, float w, float h, float maxCornerSize,
  46925. const Colour& baseColour,
  46926. float strokeWidth,
  46927. bool flatOnLeft,
  46928. bool flatOnRight,
  46929. bool flatOnTop,
  46930. bool flatOnBottom) noexcept;
  46931. // This has been deprecated - see the new parameter list..
  46932. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  46933. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  46934. };
  46935. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  46936. /*** End of inlined file: juce_LookAndFeel.h ***/
  46937. #endif
  46938. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46939. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46940. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46941. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46942. /**
  46943. The original Juce look-and-feel.
  46944. */
  46945. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  46946. {
  46947. public:
  46948. /** Creates the default JUCE look and feel. */
  46949. OldSchoolLookAndFeel();
  46950. /** Destructor. */
  46951. virtual ~OldSchoolLookAndFeel();
  46952. /** Draws the lozenge-shaped background for a standard button. */
  46953. virtual void drawButtonBackground (Graphics& g,
  46954. Button& button,
  46955. const Colour& backgroundColour,
  46956. bool isMouseOverButton,
  46957. bool isButtonDown);
  46958. /** Draws the contents of a standard ToggleButton. */
  46959. virtual void drawToggleButton (Graphics& g,
  46960. ToggleButton& button,
  46961. bool isMouseOverButton,
  46962. bool isButtonDown);
  46963. virtual void drawTickBox (Graphics& g,
  46964. Component& component,
  46965. float x, float y, float w, float h,
  46966. bool ticked,
  46967. bool isEnabled,
  46968. bool isMouseOverButton,
  46969. bool isButtonDown);
  46970. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46971. int width, int height,
  46972. double progress, const String& textToShow);
  46973. virtual void drawScrollbarButton (Graphics& g,
  46974. ScrollBar& scrollbar,
  46975. int width, int height,
  46976. int buttonDirection,
  46977. bool isScrollbarVertical,
  46978. bool isMouseOverButton,
  46979. bool isButtonDown);
  46980. virtual void drawScrollbar (Graphics& g,
  46981. ScrollBar& scrollbar,
  46982. int x, int y,
  46983. int width, int height,
  46984. bool isScrollbarVertical,
  46985. int thumbStartPosition,
  46986. int thumbSize,
  46987. bool isMouseOver,
  46988. bool isMouseDown);
  46989. virtual ImageEffectFilter* getScrollbarEffect();
  46990. virtual void drawTextEditorOutline (Graphics& g,
  46991. int width, int height,
  46992. TextEditor& textEditor);
  46993. /** Fills the background of a popup menu component. */
  46994. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46995. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46996. bool isMouseOverBar,
  46997. MenuBarComponent& menuBar);
  46998. virtual void drawComboBox (Graphics& g, int width, int height,
  46999. bool isButtonDown,
  47000. int buttonX, int buttonY,
  47001. int buttonW, int buttonH,
  47002. ComboBox& box);
  47003. virtual const Font getComboBoxFont (ComboBox& box);
  47004. virtual void drawLinearSlider (Graphics& g,
  47005. int x, int y,
  47006. int width, int height,
  47007. float sliderPos,
  47008. float minSliderPos,
  47009. float maxSliderPos,
  47010. const Slider::SliderStyle style,
  47011. Slider& slider);
  47012. virtual int getSliderThumbRadius (Slider& slider);
  47013. virtual Button* createSliderButton (bool isIncrement);
  47014. virtual ImageEffectFilter* getSliderEffect();
  47015. virtual void drawCornerResizer (Graphics& g,
  47016. int w, int h,
  47017. bool isMouseOver,
  47018. bool isMouseDragging);
  47019. virtual Button* createDocumentWindowButton (int buttonType);
  47020. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  47021. int titleBarX, int titleBarY,
  47022. int titleBarW, int titleBarH,
  47023. Button* minimiseButton,
  47024. Button* maximiseButton,
  47025. Button* closeButton,
  47026. bool positionTitleBarButtonsOnLeft);
  47027. private:
  47028. DropShadowEffect scrollbarShadow;
  47029. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  47030. };
  47031. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  47032. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  47033. #endif
  47034. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47035. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  47036. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47037. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47038. /**
  47039. A menu bar component.
  47040. @see MenuBarModel
  47041. */
  47042. class JUCE_API MenuBarComponent : public Component,
  47043. private MenuBarModel::Listener,
  47044. private Timer
  47045. {
  47046. public:
  47047. /** Creates a menu bar.
  47048. @param model the model object to use to control this bar. You can
  47049. pass 0 into this if you like, and set the model later
  47050. using the setModel() method
  47051. */
  47052. MenuBarComponent (MenuBarModel* model);
  47053. /** Destructor. */
  47054. ~MenuBarComponent();
  47055. /** Changes the model object to use to control the bar.
  47056. This can be a null pointer, in which case the bar will be empty. Don't delete the object
  47057. that is passed-in while it's still being used by this MenuBar.
  47058. */
  47059. void setModel (MenuBarModel* newModel);
  47060. /** Returns the current menu bar model being used.
  47061. */
  47062. MenuBarModel* getModel() const noexcept;
  47063. /** Pops up one of the menu items.
  47064. This lets you manually open one of the menus - it could be triggered by a
  47065. key shortcut, for example.
  47066. */
  47067. void showMenu (int menuIndex);
  47068. /** @internal */
  47069. void paint (Graphics& g);
  47070. /** @internal */
  47071. void resized();
  47072. /** @internal */
  47073. void mouseEnter (const MouseEvent& e);
  47074. /** @internal */
  47075. void mouseExit (const MouseEvent& e);
  47076. /** @internal */
  47077. void mouseDown (const MouseEvent& e);
  47078. /** @internal */
  47079. void mouseDrag (const MouseEvent& e);
  47080. /** @internal */
  47081. void mouseUp (const MouseEvent& e);
  47082. /** @internal */
  47083. void mouseMove (const MouseEvent& e);
  47084. /** @internal */
  47085. void handleCommandMessage (int commandId);
  47086. /** @internal */
  47087. bool keyPressed (const KeyPress& key);
  47088. /** @internal */
  47089. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  47090. /** @internal */
  47091. void menuCommandInvoked (MenuBarModel* menuBarModel,
  47092. const ApplicationCommandTarget::InvocationInfo& info);
  47093. private:
  47094. MenuBarModel* model;
  47095. StringArray menuNames;
  47096. Array <int> xPositions;
  47097. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  47098. int lastMouseX, lastMouseY;
  47099. int getItemAt (int x, int y);
  47100. void setItemUnderMouse (int index);
  47101. void setOpenItem (int index);
  47102. void updateItemUnderMouse (int x, int y);
  47103. void timerCallback();
  47104. void repaintMenuItem (int index);
  47105. void menuDismissed (int topLevelIndex, int itemId);
  47106. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  47107. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  47108. };
  47109. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47110. /*** End of inlined file: juce_MenuBarComponent.h ***/
  47111. #endif
  47112. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  47113. #endif
  47114. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  47115. #endif
  47116. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  47117. #endif
  47118. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  47119. #endif
  47120. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  47121. #endif
  47122. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  47123. #endif
  47124. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47125. /*** Start of inlined file: juce_LassoComponent.h ***/
  47126. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47127. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47128. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  47129. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47130. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47131. /** Manages a list of selectable items.
  47132. Use one of these to keep a track of things that the user has highlighted, like
  47133. icons or things in a list.
  47134. The class is templated so that you can use it to hold either a set of pointers
  47135. to objects, or a set of ID numbers or handles, for cases where each item may
  47136. not always have a corresponding object.
  47137. To be informed when items are selected/deselected, register a ChangeListener with
  47138. this object.
  47139. @see SelectableObject
  47140. */
  47141. template <class SelectableItemType>
  47142. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  47143. {
  47144. public:
  47145. typedef SelectableItemType ItemType;
  47146. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  47147. /** Creates an empty set. */
  47148. SelectedItemSet()
  47149. {
  47150. }
  47151. /** Creates a set based on an array of items. */
  47152. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  47153. : selectedItems (items)
  47154. {
  47155. }
  47156. /** Creates a copy of another set. */
  47157. SelectedItemSet (const SelectedItemSet& other)
  47158. : selectedItems (other.selectedItems)
  47159. {
  47160. }
  47161. /** Creates a copy of another set. */
  47162. SelectedItemSet& operator= (const SelectedItemSet& other)
  47163. {
  47164. if (selectedItems != other.selectedItems)
  47165. {
  47166. selectedItems = other.selectedItems;
  47167. changed();
  47168. }
  47169. return *this;
  47170. }
  47171. /** Clears any other currently selected items, and selects this item.
  47172. If this item is already the only thing selected, no change notification
  47173. will be sent out.
  47174. @see addToSelection, addToSelectionBasedOnModifiers
  47175. */
  47176. void selectOnly (ParameterType item)
  47177. {
  47178. if (isSelected (item))
  47179. {
  47180. for (int i = selectedItems.size(); --i >= 0;)
  47181. {
  47182. if (selectedItems.getUnchecked(i) != item)
  47183. {
  47184. deselect (selectedItems.getUnchecked(i));
  47185. i = jmin (i, selectedItems.size());
  47186. }
  47187. }
  47188. }
  47189. else
  47190. {
  47191. deselectAll();
  47192. changed();
  47193. selectedItems.add (item);
  47194. itemSelected (item);
  47195. }
  47196. }
  47197. /** Selects an item.
  47198. If the item is already selected, no change notification will be sent out.
  47199. @see selectOnly, addToSelectionBasedOnModifiers
  47200. */
  47201. void addToSelection (ParameterType item)
  47202. {
  47203. if (! isSelected (item))
  47204. {
  47205. changed();
  47206. selectedItems.add (item);
  47207. itemSelected (item);
  47208. }
  47209. }
  47210. /** Selects or deselects an item.
  47211. This will use the modifier keys to decide whether to deselect other items
  47212. first.
  47213. So if the shift key is held down, the item will be added without deselecting
  47214. anything (same as calling addToSelection() )
  47215. If no modifiers are down, the current selection will be cleared first (same
  47216. as calling selectOnly() )
  47217. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  47218. so it'll be added to the set unless it's already there, in which case it'll be
  47219. deselected.
  47220. If the items that you're selecting can also be dragged, you may need to use the
  47221. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  47222. subtleties of this kind of usage.
  47223. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  47224. */
  47225. void addToSelectionBasedOnModifiers (ParameterType item,
  47226. const ModifierKeys& modifiers)
  47227. {
  47228. if (modifiers.isShiftDown())
  47229. {
  47230. addToSelection (item);
  47231. }
  47232. else if (modifiers.isCommandDown())
  47233. {
  47234. if (isSelected (item))
  47235. deselect (item);
  47236. else
  47237. addToSelection (item);
  47238. }
  47239. else
  47240. {
  47241. selectOnly (item);
  47242. }
  47243. }
  47244. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  47245. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  47246. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  47247. makes it easy to handle multiple-selection of sets of objects that can also
  47248. be dragged.
  47249. For example, if you have several items already selected, and you click on
  47250. one of them (without dragging), then you'd expect this to deselect the other, and
  47251. just select the item you clicked on. But if you had clicked on this item and
  47252. dragged it, you'd have expected them all to stay selected.
  47253. When you call this method, you'll need to store the boolean result, because the
  47254. addToSelectionOnMouseUp() method will need to be know this value.
  47255. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  47256. */
  47257. bool addToSelectionOnMouseDown (ParameterType item,
  47258. const ModifierKeys& modifiers)
  47259. {
  47260. if (isSelected (item))
  47261. {
  47262. return ! modifiers.isPopupMenu();
  47263. }
  47264. else
  47265. {
  47266. addToSelectionBasedOnModifiers (item, modifiers);
  47267. return false;
  47268. }
  47269. }
  47270. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  47271. Call this during a mouseUp callback, when you have previously called the
  47272. addToSelectionOnMouseDown() method during your mouseDown event.
  47273. See addToSelectionOnMouseDown() for more info
  47274. @param item the item to select (or deselect)
  47275. @param modifiers the modifiers from the mouse-up event
  47276. @param wasItemDragged true if your item was dragged during the mouse click
  47277. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  47278. back from the addToSelectionOnMouseDown() call that you
  47279. should have made during the matching mouseDown event
  47280. */
  47281. void addToSelectionOnMouseUp (ParameterType item,
  47282. const ModifierKeys& modifiers,
  47283. const bool wasItemDragged,
  47284. const bool resultOfMouseDownSelectMethod)
  47285. {
  47286. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  47287. addToSelectionBasedOnModifiers (item, modifiers);
  47288. }
  47289. /** Deselects an item. */
  47290. void deselect (ParameterType item)
  47291. {
  47292. const int i = selectedItems.indexOf (item);
  47293. if (i >= 0)
  47294. {
  47295. changed();
  47296. itemDeselected (selectedItems.remove (i));
  47297. }
  47298. }
  47299. /** Deselects all items. */
  47300. void deselectAll()
  47301. {
  47302. if (selectedItems.size() > 0)
  47303. {
  47304. changed();
  47305. for (int i = selectedItems.size(); --i >= 0;)
  47306. {
  47307. itemDeselected (selectedItems.remove (i));
  47308. i = jmin (i, selectedItems.size());
  47309. }
  47310. }
  47311. }
  47312. /** Returns the number of currently selected items.
  47313. @see getSelectedItem
  47314. */
  47315. int getNumSelected() const noexcept
  47316. {
  47317. return selectedItems.size();
  47318. }
  47319. /** Returns one of the currently selected items.
  47320. Returns 0 if the index is out-of-range.
  47321. @see getNumSelected
  47322. */
  47323. SelectableItemType getSelectedItem (const int index) const noexcept
  47324. {
  47325. return selectedItems [index];
  47326. }
  47327. /** True if this item is currently selected. */
  47328. bool isSelected (ParameterType item) const noexcept
  47329. {
  47330. return selectedItems.contains (item);
  47331. }
  47332. const Array <SelectableItemType>& getItemArray() const noexcept { return selectedItems; }
  47333. /** Can be overridden to do special handling when an item is selected.
  47334. For example, if the item is an object, you might want to call it and tell
  47335. it that it's being selected.
  47336. */
  47337. virtual void itemSelected (SelectableItemType item) { (void) item; }
  47338. /** Can be overridden to do special handling when an item is deselected.
  47339. For example, if the item is an object, you might want to call it and tell
  47340. it that it's being deselected.
  47341. */
  47342. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  47343. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  47344. */
  47345. void changed (const bool synchronous = false)
  47346. {
  47347. if (synchronous)
  47348. sendSynchronousChangeMessage();
  47349. else
  47350. sendChangeMessage();
  47351. }
  47352. private:
  47353. Array <SelectableItemType> selectedItems;
  47354. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  47355. };
  47356. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47357. /*** End of inlined file: juce_SelectedItemSet.h ***/
  47358. /**
  47359. A class used by the LassoComponent to manage the things that it selects.
  47360. This allows the LassoComponent to find out which items are within the lasso,
  47361. and to change the list of selected items.
  47362. @see LassoComponent, SelectedItemSet
  47363. */
  47364. template <class SelectableItemType>
  47365. class LassoSource
  47366. {
  47367. public:
  47368. /** Destructor. */
  47369. virtual ~LassoSource() {}
  47370. /** Returns the set of items that lie within a given lassoable region.
  47371. Your implementation of this method must find all the relevent items that lie
  47372. within the given rectangle. and add them to the itemsFound array.
  47373. The co-ordinates are relative to the top-left of the lasso component's parent
  47374. component. (i.e. they are the same as the size and position of the lasso
  47375. component itself).
  47376. */
  47377. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  47378. const Rectangle<int>& area) = 0;
  47379. /** Returns the SelectedItemSet that the lasso should update.
  47380. This set will be continuously updated by the LassoComponent as it gets
  47381. dragged around, so make sure that you've got a ChangeListener attached to
  47382. the set so that your UI objects will know when the selection changes and
  47383. be able to update themselves appropriately.
  47384. */
  47385. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  47386. };
  47387. /**
  47388. A component that acts as a rectangular selection region, which you drag with
  47389. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  47390. To use one of these:
  47391. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  47392. component, and call its beginLasso() method, giving it a
  47393. suitable LassoSource object that it can use to find out which items are in
  47394. the active area.
  47395. - Each time your parent component gets a mouseDrag event, call dragLasso()
  47396. to update the lasso's position - it will use its LassoSource to calculate and
  47397. update the current selection.
  47398. - After the drag has finished and you get a mouseUp callback, you should call
  47399. endLasso() to clean up. This will make the lasso component invisible, and you
  47400. can remove it from the parent component, or delete it.
  47401. The class takes into account the modifier keys that are being held down while
  47402. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  47403. be added to the original selection; if ctrl or command is pressed, they will be
  47404. xor'ed with any previously selected items.
  47405. @see LassoSource, SelectedItemSet
  47406. */
  47407. template <class SelectableItemType>
  47408. class LassoComponent : public Component
  47409. {
  47410. public:
  47411. /** Creates a Lasso component.
  47412. The fill colour is used to fill the lasso'ed rectangle, and the outline
  47413. colour is used to draw a line around its edge.
  47414. */
  47415. explicit LassoComponent (const int outlineThickness_ = 1)
  47416. : source (nullptr),
  47417. outlineThickness (outlineThickness_)
  47418. {
  47419. }
  47420. /** Destructor. */
  47421. ~LassoComponent()
  47422. {
  47423. }
  47424. /** Call this in your mouseDown event, to initialise a drag.
  47425. Pass in a suitable LassoSource object which the lasso will use to find
  47426. the items and change the selection.
  47427. After using this method to initialise the lasso, repeatedly call dragLasso()
  47428. in your component's mouseDrag callback.
  47429. @see dragLasso, endLasso, LassoSource
  47430. */
  47431. void beginLasso (const MouseEvent& e,
  47432. LassoSource <SelectableItemType>* const lassoSource)
  47433. {
  47434. jassert (source == nullptr); // this suggests that you didn't call endLasso() after the last drag...
  47435. jassert (lassoSource != nullptr); // the source can't be null!
  47436. jassert (getParentComponent() != nullptr); // you need to add this to a parent component for it to work!
  47437. source = lassoSource;
  47438. if (lassoSource != nullptr)
  47439. originalSelection = lassoSource->getLassoSelection().getItemArray();
  47440. setSize (0, 0);
  47441. dragStartPos = e.getMouseDownPosition();
  47442. }
  47443. /** Call this in your mouseDrag event, to update the lasso's position.
  47444. This must be repeatedly calling when the mouse is dragged, after you've
  47445. first initialised the lasso with beginLasso().
  47446. This method takes into account the modifier keys that are being held down, so
  47447. if shift is pressed, then the lassoed items will be added to any that were
  47448. previously selected; if ctrl or command is pressed, then they will be xor'ed
  47449. with previously selected items.
  47450. @see beginLasso, endLasso
  47451. */
  47452. void dragLasso (const MouseEvent& e)
  47453. {
  47454. if (source != nullptr)
  47455. {
  47456. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  47457. setVisible (true);
  47458. Array <SelectableItemType> itemsInLasso;
  47459. source->findLassoItemsInArea (itemsInLasso, getBounds());
  47460. if (e.mods.isShiftDown())
  47461. {
  47462. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  47463. itemsInLasso.addArray (originalSelection);
  47464. }
  47465. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  47466. {
  47467. Array <SelectableItemType> originalMinusNew (originalSelection);
  47468. originalMinusNew.removeValuesIn (itemsInLasso);
  47469. itemsInLasso.removeValuesIn (originalSelection);
  47470. itemsInLasso.addArray (originalMinusNew);
  47471. }
  47472. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  47473. }
  47474. }
  47475. /** Call this in your mouseUp event, after the lasso has been dragged.
  47476. @see beginLasso, dragLasso
  47477. */
  47478. void endLasso()
  47479. {
  47480. source = nullptr;
  47481. originalSelection.clear();
  47482. setVisible (false);
  47483. }
  47484. /** A set of colour IDs to use to change the colour of various aspects of the label.
  47485. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47486. methods.
  47487. Note that you can also use the constants from TextEditor::ColourIds to change the
  47488. colour of the text editor that is opened when a label is editable.
  47489. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47490. */
  47491. enum ColourIds
  47492. {
  47493. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  47494. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  47495. };
  47496. /** @internal */
  47497. void paint (Graphics& g)
  47498. {
  47499. g.fillAll (findColour (lassoFillColourId));
  47500. g.setColour (findColour (lassoOutlineColourId));
  47501. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  47502. // this suggests that you've left a lasso comp lying around after the
  47503. // mouse drag has finished.. Be careful to call endLasso() when you get a
  47504. // mouse-up event.
  47505. jassert (isMouseButtonDownAnywhere());
  47506. }
  47507. /** @internal */
  47508. bool hitTest (int, int) { return false; }
  47509. private:
  47510. Array <SelectableItemType> originalSelection;
  47511. LassoSource <SelectableItemType>* source;
  47512. int outlineThickness;
  47513. Point<int> dragStartPos;
  47514. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  47515. };
  47516. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47517. /*** End of inlined file: juce_LassoComponent.h ***/
  47518. #endif
  47519. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  47520. #endif
  47521. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  47522. #endif
  47523. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47524. /*** Start of inlined file: juce_MouseInputSource.h ***/
  47525. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47526. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47527. class MouseInputSourceInternal;
  47528. /**
  47529. Represents a linear source of mouse events from a mouse device or individual finger
  47530. in a multi-touch environment.
  47531. Each MouseEvent object contains a reference to the MouseInputSource that generated
  47532. it. In an environment with a single mouse for input, all events will come from the
  47533. same source, but in a multi-touch system, there may be multiple MouseInputSource
  47534. obects active, each representing a stream of events coming from a particular finger.
  47535. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  47536. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  47537. the only events that can happen between a mouseDown and its corresponding mouseUp are
  47538. mouseDrags, etc.
  47539. When there are multiple touches arriving from multiple MouseInputSources, their
  47540. event streams may arrive in an interleaved order, so you should use the getIndex()
  47541. method to find out which finger each event came from.
  47542. @see MouseEvent
  47543. */
  47544. class JUCE_API MouseInputSource
  47545. {
  47546. public:
  47547. /** Creates a MouseInputSource.
  47548. You should never actually create a MouseInputSource in your own code - the
  47549. library takes care of managing these objects.
  47550. */
  47551. MouseInputSource (int index, bool isMouseDevice);
  47552. /** Destructor. */
  47553. ~MouseInputSource();
  47554. /** Returns true if this object represents a normal desk-based mouse device. */
  47555. bool isMouse() const;
  47556. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  47557. bool isTouch() const;
  47558. /** Returns true if this source has an on-screen pointer that can hover over
  47559. items without clicking them.
  47560. */
  47561. bool canHover() const;
  47562. /** Returns true if this source may have a scroll wheel. */
  47563. bool hasMouseWheel() const;
  47564. /** Returns this source's index in the global list of possible sources.
  47565. If the system only has a single mouse, there will only be a single MouseInputSource
  47566. with an index of 0.
  47567. If the system supports multi-touch input, then the index will represent a finger
  47568. number, starting from 0. When the first touch event begins, it will have finger
  47569. number 0, and then if a second touch happens while the first is still down, it
  47570. will have index 1, etc.
  47571. */
  47572. int getIndex() const;
  47573. /** Returns true if this device is currently being pressed. */
  47574. bool isDragging() const;
  47575. /** Returns the last-known screen position of this source. */
  47576. const Point<int> getScreenPosition() const;
  47577. /** Returns a set of modifiers that indicate which buttons are currently
  47578. held down on this device.
  47579. */
  47580. const ModifierKeys getCurrentModifiers() const;
  47581. /** Returns the component that was last known to be under this pointer. */
  47582. Component* getComponentUnderMouse() const;
  47583. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  47584. This is asynchronous - the event will occur on the message thread.
  47585. */
  47586. void triggerFakeMove() const;
  47587. /** Returns the number of clicks that should be counted as belonging to the
  47588. current mouse event.
  47589. So the mouse is currently down and it's the second click of a double-click, this
  47590. will return 2.
  47591. */
  47592. int getNumberOfMultipleClicks() const noexcept;
  47593. /** Returns the time at which the last mouse-down occurred. */
  47594. const Time getLastMouseDownTime() const noexcept;
  47595. /** Returns the screen position at which the last mouse-down occurred. */
  47596. const Point<int> getLastMouseDownPosition() const noexcept;
  47597. /** Returns true if this mouse is currently down, and if it has been dragged more
  47598. than a couple of pixels from the place it was pressed.
  47599. */
  47600. bool hasMouseMovedSignificantlySincePressed() const noexcept;
  47601. /** Returns true if this input source uses a visible mouse cursor. */
  47602. bool hasMouseCursor() const noexcept;
  47603. /** Changes the mouse cursor, (if there is one). */
  47604. void showMouseCursor (const MouseCursor& cursor);
  47605. /** Hides the mouse cursor (if there is one). */
  47606. void hideCursor();
  47607. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  47608. void revealCursor();
  47609. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  47610. void forceMouseCursorUpdate();
  47611. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  47612. bool canDoUnboundedMovement() const noexcept;
  47613. /** Allows the mouse to move beyond the edges of the screen.
  47614. Calling this method when the mouse button is currently pressed will remove the cursor
  47615. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  47616. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  47617. can be used for things like custom slider controls or dragging objects around, where
  47618. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  47619. The unbounded mode is automatically turned off when the mouse button is released, or
  47620. it can be turned off explicitly by calling this method again.
  47621. @param isEnabled whether to turn this mode on or off
  47622. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  47623. hidden; if true, it will only be hidden when it
  47624. is moved beyond the edge of the screen
  47625. */
  47626. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  47627. /** @internal */
  47628. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  47629. /** @internal */
  47630. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  47631. private:
  47632. friend class Desktop;
  47633. friend class ComponentPeer;
  47634. friend class MouseInputSourceInternal;
  47635. ScopedPointer<MouseInputSourceInternal> pimpl;
  47636. static const Point<int> getCurrentMousePosition();
  47637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  47638. };
  47639. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47640. /*** End of inlined file: juce_MouseInputSource.h ***/
  47641. #endif
  47642. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  47643. #endif
  47644. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  47645. #endif
  47646. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  47647. #endif
  47648. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  47649. #endif
  47650. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  47651. #endif
  47652. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47653. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  47654. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47655. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47656. /**
  47657. A parallelogram defined by three RelativePoint positions.
  47658. @see RelativePoint, RelativeCoordinate
  47659. */
  47660. class JUCE_API RelativeParallelogram
  47661. {
  47662. public:
  47663. RelativeParallelogram();
  47664. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  47665. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  47666. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  47667. ~RelativeParallelogram();
  47668. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  47669. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  47670. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  47671. void getPath (Path& path, Expression::Scope* scope) const;
  47672. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  47673. bool isDynamic() const;
  47674. bool operator== (const RelativeParallelogram& other) const noexcept;
  47675. bool operator!= (const RelativeParallelogram& other) const noexcept;
  47676. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) noexcept;
  47677. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) noexcept;
  47678. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) noexcept;
  47679. RelativePoint topLeft, topRight, bottomLeft;
  47680. };
  47681. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47682. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  47683. #endif
  47684. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  47685. #endif
  47686. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47687. /*** Start of inlined file: juce_RelativePointPath.h ***/
  47688. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47689. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47690. class DrawablePath;
  47691. /**
  47692. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  47693. One of these paths can be converted into a Path object for drawing and manipulation, but
  47694. unlike a Path, its points can be dynamic instead of just fixed.
  47695. @see RelativePoint, RelativeCoordinate
  47696. */
  47697. class JUCE_API RelativePointPath
  47698. {
  47699. public:
  47700. RelativePointPath();
  47701. RelativePointPath (const RelativePointPath& other);
  47702. explicit RelativePointPath (const Path& path);
  47703. ~RelativePointPath();
  47704. bool operator== (const RelativePointPath& other) const noexcept;
  47705. bool operator!= (const RelativePointPath& other) const noexcept;
  47706. /** Resolves this points in this path and adds them to a normal Path object. */
  47707. void createPath (Path& path, Expression::Scope* scope) const;
  47708. /** Returns true if the path contains any non-fixed points. */
  47709. bool containsAnyDynamicPoints() const;
  47710. /** Quickly swaps the contents of this path with another. */
  47711. void swapWith (RelativePointPath& other) noexcept;
  47712. /** The types of element that may be contained in this path.
  47713. @see RelativePointPath::ElementBase
  47714. */
  47715. enum ElementType
  47716. {
  47717. nullElement,
  47718. startSubPathElement,
  47719. closeSubPathElement,
  47720. lineToElement,
  47721. quadraticToElement,
  47722. cubicToElement
  47723. };
  47724. /** Base class for the elements that make up a RelativePointPath.
  47725. */
  47726. class JUCE_API ElementBase
  47727. {
  47728. public:
  47729. ElementBase (ElementType type);
  47730. virtual ~ElementBase() {}
  47731. virtual const ValueTree createTree() const = 0;
  47732. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  47733. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  47734. virtual ElementBase* clone() const = 0;
  47735. bool isDynamic();
  47736. const ElementType type;
  47737. private:
  47738. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  47739. };
  47740. class JUCE_API StartSubPath : public ElementBase
  47741. {
  47742. public:
  47743. StartSubPath (const RelativePoint& pos);
  47744. const ValueTree createTree() const;
  47745. void addToPath (Path& path, Expression::Scope*) const;
  47746. RelativePoint* getControlPoints (int& numPoints);
  47747. ElementBase* clone() const;
  47748. RelativePoint startPos;
  47749. private:
  47750. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  47751. };
  47752. class JUCE_API CloseSubPath : public ElementBase
  47753. {
  47754. public:
  47755. CloseSubPath();
  47756. const ValueTree createTree() const;
  47757. void addToPath (Path& path, Expression::Scope*) const;
  47758. RelativePoint* getControlPoints (int& numPoints);
  47759. ElementBase* clone() const;
  47760. private:
  47761. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  47762. };
  47763. class JUCE_API LineTo : public ElementBase
  47764. {
  47765. public:
  47766. LineTo (const RelativePoint& endPoint);
  47767. const ValueTree createTree() const;
  47768. void addToPath (Path& path, Expression::Scope*) const;
  47769. RelativePoint* getControlPoints (int& numPoints);
  47770. ElementBase* clone() const;
  47771. RelativePoint endPoint;
  47772. private:
  47773. JUCE_DECLARE_NON_COPYABLE (LineTo);
  47774. };
  47775. class JUCE_API QuadraticTo : public ElementBase
  47776. {
  47777. public:
  47778. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  47779. const ValueTree createTree() const;
  47780. void addToPath (Path& path, Expression::Scope*) const;
  47781. RelativePoint* getControlPoints (int& numPoints);
  47782. ElementBase* clone() const;
  47783. RelativePoint controlPoints[2];
  47784. private:
  47785. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  47786. };
  47787. class JUCE_API CubicTo : public ElementBase
  47788. {
  47789. public:
  47790. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  47791. const ValueTree createTree() const;
  47792. void addToPath (Path& path, Expression::Scope*) const;
  47793. RelativePoint* getControlPoints (int& numPoints);
  47794. ElementBase* clone() const;
  47795. RelativePoint controlPoints[3];
  47796. private:
  47797. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  47798. };
  47799. void addElement (ElementBase* newElement);
  47800. OwnedArray <ElementBase> elements;
  47801. bool usesNonZeroWinding;
  47802. private:
  47803. class Positioner;
  47804. friend class Positioner;
  47805. bool containsDynamicPoints;
  47806. void applyTo (DrawablePath& path) const;
  47807. RelativePointPath& operator= (const RelativePointPath&);
  47808. JUCE_LEAK_DETECTOR (RelativePointPath);
  47809. };
  47810. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47811. /*** End of inlined file: juce_RelativePointPath.h ***/
  47812. #endif
  47813. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47814. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  47815. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47816. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47817. class Component;
  47818. /**
  47819. An rectangle stored as a set of RelativeCoordinate values.
  47820. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  47821. @see RelativeCoordinate, RelativePoint
  47822. */
  47823. class JUCE_API RelativeRectangle
  47824. {
  47825. public:
  47826. /** Creates a zero-size rectangle at the origin. */
  47827. RelativeRectangle();
  47828. /** Creates an absolute rectangle, relative to the origin. */
  47829. explicit RelativeRectangle (const Rectangle<float>& rect);
  47830. /** Creates a rectangle from four coordinates. */
  47831. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  47832. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  47833. /** Creates a rectangle from a stringified representation.
  47834. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  47835. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  47836. RelativeCoordinate class.
  47837. @see toString
  47838. */
  47839. explicit RelativeRectangle (const String& stringVersion);
  47840. bool operator== (const RelativeRectangle& other) const noexcept;
  47841. bool operator!= (const RelativeRectangle& other) const noexcept;
  47842. /** Calculates the absolute position of this rectangle.
  47843. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  47844. be needed to calculate the result.
  47845. */
  47846. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  47847. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  47848. Calling this will leave any anchor points unchanged, but will set any absolute
  47849. or relative positions to whatever values are necessary to make the resultant position
  47850. match the position that is provided.
  47851. */
  47852. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  47853. /** Returns true if this rectangle depends on any external symbols for its position.
  47854. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  47855. */
  47856. bool isDynamic() const;
  47857. /** Returns a string which represents this point.
  47858. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  47859. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  47860. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  47861. */
  47862. const String toString() const;
  47863. /** Renames a symbol if it is used by any of the coordinates.
  47864. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  47865. */
  47866. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  47867. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  47868. keep it positioned with this rectangle.
  47869. */
  47870. void applyToComponent (Component& component) const;
  47871. // The actual rectangle coords...
  47872. RelativeCoordinate left, right, top, bottom;
  47873. };
  47874. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47875. /*** End of inlined file: juce_RelativeRectangle.h ***/
  47876. #endif
  47877. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47878. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  47879. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47880. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47881. /**
  47882. A PropertyComponent that contains an on/off toggle button.
  47883. This type of property component can be used if you have a boolean value to
  47884. toggle on/off.
  47885. @see PropertyComponent
  47886. */
  47887. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  47888. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47889. {
  47890. protected:
  47891. /** Creates a button component.
  47892. If you use this constructor, you must override the getState() and setState()
  47893. methods.
  47894. @param propertyName the property name to be passed to the PropertyComponent
  47895. @param buttonTextWhenTrue the text shown in the button when the value is true
  47896. @param buttonTextWhenFalse the text shown in the button when the value is false
  47897. */
  47898. BooleanPropertyComponent (const String& propertyName,
  47899. const String& buttonTextWhenTrue,
  47900. const String& buttonTextWhenFalse);
  47901. public:
  47902. /** Creates a button component.
  47903. @param valueToControl a Value object that this property should refer to.
  47904. @param propertyName the property name to be passed to the PropertyComponent
  47905. @param buttonText the text shown in the ToggleButton component
  47906. */
  47907. BooleanPropertyComponent (const Value& valueToControl,
  47908. const String& propertyName,
  47909. const String& buttonText);
  47910. /** Destructor. */
  47911. ~BooleanPropertyComponent();
  47912. /** Called to change the state of the boolean value. */
  47913. virtual void setState (bool newState);
  47914. /** Must return the current value of the property. */
  47915. virtual bool getState() const;
  47916. /** @internal */
  47917. void paint (Graphics& g);
  47918. /** @internal */
  47919. void refresh();
  47920. /** @internal */
  47921. void buttonClicked (Button*);
  47922. private:
  47923. ToggleButton button;
  47924. String onText, offText;
  47925. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  47926. };
  47927. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47928. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  47929. #endif
  47930. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47931. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  47932. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47933. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47934. /**
  47935. A PropertyComponent that contains a button.
  47936. This type of property component can be used if you need a button to trigger some
  47937. kind of action.
  47938. @see PropertyComponent
  47939. */
  47940. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  47941. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47942. {
  47943. public:
  47944. /** Creates a button component.
  47945. @param propertyName the property name to be passed to the PropertyComponent
  47946. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  47947. */
  47948. ButtonPropertyComponent (const String& propertyName,
  47949. bool triggerOnMouseDown);
  47950. /** Destructor. */
  47951. ~ButtonPropertyComponent();
  47952. /** Called when the user clicks the button.
  47953. */
  47954. virtual void buttonClicked() = 0;
  47955. /** Returns the string that should be displayed in the button.
  47956. If you need to change this string, call refresh() to update the component.
  47957. */
  47958. virtual const String getButtonText() const = 0;
  47959. /** @internal */
  47960. void refresh();
  47961. /** @internal */
  47962. void buttonClicked (Button*);
  47963. private:
  47964. TextButton button;
  47965. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  47966. };
  47967. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47968. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  47969. #endif
  47970. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47971. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  47972. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47973. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47974. /**
  47975. A PropertyComponent that shows its value as a combo box.
  47976. This type of property component contains a list of options and has a
  47977. combo box to choose one.
  47978. Your subclass's constructor must add some strings to the choices StringArray
  47979. and these are shown in the list.
  47980. The getIndex() method will be called to find out which option is the currently
  47981. selected one. If you call refresh() it will call getIndex() to check whether
  47982. the value has changed, and will update the combo box if needed.
  47983. If the user selects a different item from the list, setIndex() will be
  47984. called to let your class process this.
  47985. @see PropertyComponent, PropertyPanel
  47986. */
  47987. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  47988. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47989. {
  47990. protected:
  47991. /** Creates the component.
  47992. Your subclass's constructor must add a list of options to the choices
  47993. member variable.
  47994. */
  47995. ChoicePropertyComponent (const String& propertyName);
  47996. public:
  47997. /** Creates the component.
  47998. @param valueToControl the value that the combo box will read and control
  47999. @param propertyName the name of the property
  48000. @param choices the list of possible values that the drop-down list will contain
  48001. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  48002. These are the values that will be read and written to the
  48003. valueToControl value. This array must contain the same number of items
  48004. as the choices array
  48005. */
  48006. ChoicePropertyComponent (const Value& valueToControl,
  48007. const String& propertyName,
  48008. const StringArray& choices,
  48009. const Array <var>& correspondingValues);
  48010. /** Destructor. */
  48011. ~ChoicePropertyComponent();
  48012. /** Called when the user selects an item from the combo box.
  48013. Your subclass must use this callback to update the value that this component
  48014. represents. The index is the index of the chosen item in the choices
  48015. StringArray.
  48016. */
  48017. virtual void setIndex (int newIndex);
  48018. /** Returns the index of the item that should currently be shown.
  48019. This is the index of the item in the choices StringArray that will be
  48020. shown.
  48021. */
  48022. virtual int getIndex() const;
  48023. /** Returns the list of options. */
  48024. const StringArray& getChoices() const;
  48025. /** @internal */
  48026. void refresh();
  48027. /** @internal */
  48028. void comboBoxChanged (ComboBox*);
  48029. protected:
  48030. /** The list of options that will be shown in the combo box.
  48031. Your subclass must populate this array in its constructor. If any empty
  48032. strings are added, these will be replaced with horizontal separators (see
  48033. ComboBox::addSeparator() for more info).
  48034. */
  48035. StringArray choices;
  48036. private:
  48037. ComboBox comboBox;
  48038. bool isCustomClass;
  48039. class RemapperValueSource;
  48040. void createComboBox();
  48041. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  48042. };
  48043. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48044. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  48045. #endif
  48046. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  48047. #endif
  48048. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  48049. #endif
  48050. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48051. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  48052. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48053. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48054. /**
  48055. A PropertyComponent that shows its value as a slider.
  48056. @see PropertyComponent, Slider
  48057. */
  48058. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  48059. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  48060. {
  48061. protected:
  48062. /** Creates the property component.
  48063. The ranges, interval and skew factor are passed to the Slider component.
  48064. If you need to customise the slider in other ways, your constructor can
  48065. access the slider member variable and change it directly.
  48066. */
  48067. SliderPropertyComponent (const String& propertyName,
  48068. double rangeMin,
  48069. double rangeMax,
  48070. double interval,
  48071. double skewFactor = 1.0);
  48072. public:
  48073. /** Creates the property component.
  48074. The ranges, interval and skew factor are passed to the Slider component.
  48075. If you need to customise the slider in other ways, your constructor can
  48076. access the slider member variable and change it directly.
  48077. */
  48078. SliderPropertyComponent (const Value& valueToControl,
  48079. const String& propertyName,
  48080. double rangeMin,
  48081. double rangeMax,
  48082. double interval,
  48083. double skewFactor = 1.0);
  48084. /** Destructor. */
  48085. ~SliderPropertyComponent();
  48086. /** Called when the user moves the slider to change its value.
  48087. Your subclass must use this method to update whatever item this property
  48088. represents.
  48089. */
  48090. virtual void setValue (double newValue);
  48091. /** Returns the value that the slider should show. */
  48092. virtual double getValue() const;
  48093. /** @internal */
  48094. void refresh();
  48095. /** @internal */
  48096. void sliderValueChanged (Slider*);
  48097. protected:
  48098. /** The slider component being used in this component.
  48099. Your subclass has access to this in case it needs to customise it in some way.
  48100. */
  48101. Slider slider;
  48102. private:
  48103. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  48104. };
  48105. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48106. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  48107. #endif
  48108. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48109. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  48110. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48111. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48112. /**
  48113. A PropertyComponent that shows its value as editable text.
  48114. @see PropertyComponent
  48115. */
  48116. class JUCE_API TextPropertyComponent : public PropertyComponent
  48117. {
  48118. protected:
  48119. /** Creates a text property component.
  48120. The maxNumChars is used to set the length of string allowable, and isMultiLine
  48121. sets whether the text editor allows carriage returns.
  48122. @see TextEditor
  48123. */
  48124. TextPropertyComponent (const String& propertyName,
  48125. int maxNumChars,
  48126. bool isMultiLine);
  48127. public:
  48128. /** Creates a text property component.
  48129. The maxNumChars is used to set the length of string allowable, and isMultiLine
  48130. sets whether the text editor allows carriage returns.
  48131. @see TextEditor
  48132. */
  48133. TextPropertyComponent (const Value& valueToControl,
  48134. const String& propertyName,
  48135. int maxNumChars,
  48136. bool isMultiLine);
  48137. /** Destructor. */
  48138. ~TextPropertyComponent();
  48139. /** Called when the user edits the text.
  48140. Your subclass must use this callback to change the value of whatever item
  48141. this property component represents.
  48142. */
  48143. virtual void setText (const String& newText);
  48144. /** Returns the text that should be shown in the text editor.
  48145. */
  48146. virtual const String getText() const;
  48147. /** @internal */
  48148. void refresh();
  48149. /** @internal */
  48150. void textWasEdited();
  48151. private:
  48152. ScopedPointer<Label> textEditor;
  48153. void createEditor (int maxNumChars, bool isMultiLine);
  48154. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  48155. };
  48156. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48157. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  48158. #endif
  48159. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48160. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  48161. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48162. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48163. #if JUCE_WINDOWS || DOXYGEN
  48164. /**
  48165. A Windows-specific class that can create and embed an ActiveX control inside
  48166. itself.
  48167. To use it, create one of these, put it in place and make sure it's visible in a
  48168. window, then use createControl() to instantiate an ActiveX control. The control
  48169. will then be moved and resized to follow the movements of this component.
  48170. Of course, since the control is a heavyweight window, it'll obliterate any
  48171. juce components that may overlap this component, but that's life.
  48172. */
  48173. class JUCE_API ActiveXControlComponent : public Component
  48174. {
  48175. public:
  48176. /** Create an initially-empty container. */
  48177. ActiveXControlComponent();
  48178. /** Destructor. */
  48179. ~ActiveXControlComponent();
  48180. /** Tries to create an ActiveX control and embed it in this peer.
  48181. The peer controlIID is a pointer to an IID structure - it's treated
  48182. as a void* because when including the Juce headers, you might not always
  48183. have included windows.h first, in which case IID wouldn't be defined.
  48184. e.g. @code
  48185. const IID myIID = __uuidof (QTControl);
  48186. myControlComp->createControl (&myIID);
  48187. @endcode
  48188. */
  48189. bool createControl (const void* controlIID);
  48190. /** Deletes the ActiveX control, if one has been created.
  48191. */
  48192. void deleteControl();
  48193. /** Returns true if a control is currently in use. */
  48194. bool isControlOpen() const noexcept { return control != nullptr; }
  48195. /** Does a QueryInterface call on the embedded control object.
  48196. This allows you to cast the control to whatever type of COM object you need.
  48197. The iid parameter is a pointer to an IID structure - it's treated
  48198. as a void* because when including the Juce headers, you might not always
  48199. have included windows.h first, in which case IID wouldn't be defined, but
  48200. you should just pass a pointer to an IID.
  48201. e.g. @code
  48202. const IID iid = __uuidof (IOleWindow);
  48203. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  48204. if (oleWindow != nullptr)
  48205. {
  48206. HWND hwnd;
  48207. oleWindow->GetWindow (&hwnd);
  48208. ...
  48209. oleWindow->Release();
  48210. }
  48211. @endcode
  48212. */
  48213. void* queryInterface (const void* iid) const;
  48214. /** Set this to false to stop mouse events being allowed through to the control.
  48215. */
  48216. void setMouseEventsAllowed (bool eventsCanReachControl);
  48217. /** Returns true if mouse events are allowed to get through to the control.
  48218. */
  48219. bool areMouseEventsAllowed() const noexcept { return mouseEventsAllowed; }
  48220. /** @internal */
  48221. void paint (Graphics& g);
  48222. /** @internal */
  48223. void* originalWndProc;
  48224. private:
  48225. class Pimpl;
  48226. friend class Pimpl;
  48227. friend class ScopedPointer <Pimpl>;
  48228. ScopedPointer <Pimpl> control;
  48229. bool mouseEventsAllowed;
  48230. void setControlBounds (const Rectangle<int>& bounds) const;
  48231. void setControlVisible (bool b) const;
  48232. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  48233. };
  48234. #endif
  48235. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48236. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  48237. #endif
  48238. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48239. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  48240. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48241. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48242. /**
  48243. A component containing controls to let the user change the audio settings of
  48244. an AudioDeviceManager object.
  48245. Very easy to use - just create one of these and show it to the user.
  48246. @see AudioDeviceManager
  48247. */
  48248. class JUCE_API AudioDeviceSelectorComponent : public Component,
  48249. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  48250. public ButtonListener,
  48251. public ChangeListener
  48252. {
  48253. public:
  48254. /** Creates the component.
  48255. If your app needs only output channels, you might ask for a maximum of 0 input
  48256. channels, and the component won't display any options for choosing the input
  48257. channels. And likewise if you're doing an input-only app.
  48258. @param deviceManager the device manager that this component should control
  48259. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  48260. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  48261. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  48262. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  48263. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  48264. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  48265. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  48266. treated as a set of separate mono channels.
  48267. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  48268. are shown, with an "advanced" button that shows the rest of them
  48269. */
  48270. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  48271. const int minAudioInputChannels,
  48272. const int maxAudioInputChannels,
  48273. const int minAudioOutputChannels,
  48274. const int maxAudioOutputChannels,
  48275. const bool showMidiInputOptions,
  48276. const bool showMidiOutputSelector,
  48277. const bool showChannelsAsStereoPairs,
  48278. const bool hideAdvancedOptionsWithButton);
  48279. /** Destructor */
  48280. ~AudioDeviceSelectorComponent();
  48281. /** @internal */
  48282. void resized();
  48283. /** @internal */
  48284. void comboBoxChanged (ComboBox*);
  48285. /** @internal */
  48286. void buttonClicked (Button*);
  48287. /** @internal */
  48288. void changeListenerCallback (ChangeBroadcaster*);
  48289. /** @internal */
  48290. void childBoundsChanged (Component*);
  48291. private:
  48292. AudioDeviceManager& deviceManager;
  48293. ScopedPointer<ComboBox> deviceTypeDropDown;
  48294. ScopedPointer<Label> deviceTypeDropDownLabel;
  48295. ScopedPointer<Component> audioDeviceSettingsComp;
  48296. String audioDeviceSettingsCompType;
  48297. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  48298. const bool showChannelsAsStereoPairs;
  48299. const bool hideAdvancedOptionsWithButton;
  48300. class MidiInputSelectorComponentListBox;
  48301. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  48302. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  48303. ScopedPointer<ComboBox> midiOutputSelector;
  48304. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  48305. void updateAllControls();
  48306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  48307. };
  48308. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48309. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  48310. #endif
  48311. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48312. /*** Start of inlined file: juce_BubbleComponent.h ***/
  48313. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48314. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48315. /**
  48316. A component for showing a message or other graphics inside a speech-bubble-shaped
  48317. outline, pointing at a location on the screen.
  48318. This is a base class that just draws and positions the bubble shape, but leaves
  48319. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  48320. that draws a text message.
  48321. To use it, create your subclass, then either add it to a parent component or
  48322. put it on the desktop with addToDesktop (0), use setPosition() to
  48323. resize and position it, then make it visible.
  48324. @see BubbleMessageComponent
  48325. */
  48326. class JUCE_API BubbleComponent : public Component
  48327. {
  48328. protected:
  48329. /** Creates a BubbleComponent.
  48330. Your subclass will need to implement the getContentSize() and paintContent()
  48331. methods to draw the bubble's contents.
  48332. */
  48333. BubbleComponent();
  48334. public:
  48335. /** Destructor. */
  48336. ~BubbleComponent();
  48337. /** A list of permitted placements for the bubble, relative to the co-ordinates
  48338. at which it should be pointing.
  48339. @see setAllowedPlacement
  48340. */
  48341. enum BubblePlacement
  48342. {
  48343. above = 1,
  48344. below = 2,
  48345. left = 4,
  48346. right = 8
  48347. };
  48348. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  48349. point at which it's pointing.
  48350. By default when setPosition() is called, the bubble will place itself either
  48351. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  48352. the values in BubblePlacement to restrict this choice.
  48353. E.g. if you only want your bubble to appear above or below the target area,
  48354. use setAllowedPlacement (above | below);
  48355. @see BubblePlacement
  48356. */
  48357. void setAllowedPlacement (int newPlacement);
  48358. /** Moves and resizes the bubble to point at a given component.
  48359. This will resize the bubble to fit its content, then find a position for it
  48360. so that it's next to, but doesn't overlap the given component.
  48361. It'll put itself either above, below, or to the side of the component depending
  48362. on where there's the most space, honouring any restrictions that were set
  48363. with setAllowedPlacement().
  48364. */
  48365. void setPosition (Component* componentToPointTo);
  48366. /** Moves and resizes the bubble to point at a given point.
  48367. This will resize the bubble to fit its content, then position it
  48368. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  48369. are relative to either the bubble component's parent component if it has one, or
  48370. they are screen co-ordinates if not.
  48371. It'll put itself either above, below, or to the side of this point, depending
  48372. on where there's the most space, honouring any restrictions that were set
  48373. with setAllowedPlacement().
  48374. */
  48375. void setPosition (int arrowTipX,
  48376. int arrowTipY);
  48377. /** Moves and resizes the bubble to point at a given rectangle.
  48378. This will resize the bubble to fit its content, then find a position for it
  48379. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  48380. co-ordinates are relative to either the bubble component's parent component
  48381. if it has one, or they are screen co-ordinates if not.
  48382. It'll put itself either above, below, or to the side of the component depending
  48383. on where there's the most space, honouring any restrictions that were set
  48384. with setAllowedPlacement().
  48385. */
  48386. void setPosition (const Rectangle<int>& rectangleToPointTo);
  48387. protected:
  48388. /** Subclasses should override this to return the size of the content they
  48389. want to draw inside the bubble.
  48390. */
  48391. virtual void getContentSize (int& width, int& height) = 0;
  48392. /** Subclasses should override this to draw their bubble's contents.
  48393. The graphics object's clip region and the dimensions passed in here are
  48394. set up to paint just the rectangle inside the bubble.
  48395. */
  48396. virtual void paintContent (Graphics& g, int width, int height) = 0;
  48397. public:
  48398. /** @internal */
  48399. void paint (Graphics& g);
  48400. private:
  48401. Rectangle<int> content;
  48402. int side, allowablePlacements;
  48403. float arrowTipX, arrowTipY;
  48404. DropShadowEffect shadow;
  48405. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  48406. };
  48407. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48408. /*** End of inlined file: juce_BubbleComponent.h ***/
  48409. #endif
  48410. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48411. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  48412. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48413. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48414. /**
  48415. A speech-bubble component that displays a short message.
  48416. This can be used to show a message with the tail of the speech bubble
  48417. pointing to a particular component or location on the screen.
  48418. @see BubbleComponent
  48419. */
  48420. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  48421. private Timer
  48422. {
  48423. public:
  48424. /** Creates a bubble component.
  48425. After creating one a BubbleComponent, do the following:
  48426. - add it to an appropriate parent component, or put it on the
  48427. desktop with Component::addToDesktop (0).
  48428. - use the showAt() method to show a message.
  48429. - it will make itself invisible after it times-out (and can optionally
  48430. also delete itself), or you can reuse it somewhere else by calling
  48431. showAt() again.
  48432. */
  48433. BubbleMessageComponent (int fadeOutLengthMs = 150);
  48434. /** Destructor. */
  48435. ~BubbleMessageComponent();
  48436. /** Shows a message bubble at a particular position.
  48437. This shows the bubble with its stem pointing to the given location
  48438. (co-ordinates being relative to its parent component).
  48439. For details about exactly how it decides where to position itself, see
  48440. BubbleComponent::updatePosition().
  48441. @param x the x co-ordinate of end of the bubble's tail
  48442. @param y the y co-ordinate of end of the bubble's tail
  48443. @param message the text to display
  48444. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  48445. from its parent compnent. If this is 0 or less, it
  48446. will stay there until manually removed.
  48447. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  48448. mouse button is pressed (anywhere on the screen)
  48449. @param deleteSelfAfterUse if true, then the component will delete itself after
  48450. it becomes invisible
  48451. */
  48452. void showAt (int x, int y,
  48453. const String& message,
  48454. int numMillisecondsBeforeRemoving,
  48455. bool removeWhenMouseClicked = true,
  48456. bool deleteSelfAfterUse = false);
  48457. /** Shows a message bubble next to a particular component.
  48458. This shows the bubble with its stem pointing at the given component.
  48459. For details about exactly how it decides where to position itself, see
  48460. BubbleComponent::updatePosition().
  48461. @param component the component that you want to point at
  48462. @param message the text to display
  48463. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  48464. from its parent compnent. If this is 0 or less, it
  48465. will stay there until manually removed.
  48466. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  48467. mouse button is pressed (anywhere on the screen)
  48468. @param deleteSelfAfterUse if true, then the component will delete itself after
  48469. it becomes invisible
  48470. */
  48471. void showAt (Component* component,
  48472. const String& message,
  48473. int numMillisecondsBeforeRemoving,
  48474. bool removeWhenMouseClicked = true,
  48475. bool deleteSelfAfterUse = false);
  48476. /** @internal */
  48477. void getContentSize (int& w, int& h);
  48478. /** @internal */
  48479. void paintContent (Graphics& g, int w, int h);
  48480. /** @internal */
  48481. void timerCallback();
  48482. private:
  48483. int fadeOutLength, mouseClickCounter;
  48484. TextLayout textLayout;
  48485. int64 expiryTime;
  48486. bool deleteAfterUse;
  48487. void init (int numMillisecondsBeforeRemoving,
  48488. bool removeWhenMouseClicked,
  48489. bool deleteSelfAfterUse);
  48490. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  48491. };
  48492. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48493. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  48494. #endif
  48495. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  48496. /*** Start of inlined file: juce_ColourSelector.h ***/
  48497. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  48498. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  48499. /**
  48500. A component that lets the user choose a colour.
  48501. This shows RGB sliders and a colourspace that the user can pick colours from.
  48502. This class is also a ChangeBroadcaster, so listeners can register to be told
  48503. when the colour changes.
  48504. */
  48505. class JUCE_API ColourSelector : public Component,
  48506. public ChangeBroadcaster,
  48507. protected SliderListener
  48508. {
  48509. public:
  48510. /** Options for the type of selector to show. These are passed into the constructor. */
  48511. enum ColourSelectorOptions
  48512. {
  48513. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  48514. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  48515. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  48516. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  48517. };
  48518. /** Creates a ColourSelector object.
  48519. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  48520. which of the selector's features should be visible.
  48521. The edgeGap value specifies the amount of space to leave around the edge.
  48522. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  48523. colourspace and hue selector components.
  48524. */
  48525. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  48526. int edgeGap = 4,
  48527. int gapAroundColourSpaceComponent = 7);
  48528. /** Destructor. */
  48529. ~ColourSelector();
  48530. /** Returns the colour that the user has currently selected.
  48531. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  48532. register to be told when the colour changes.
  48533. @see setCurrentColour
  48534. */
  48535. const Colour getCurrentColour() const;
  48536. /** Changes the colour that is currently being shown.
  48537. */
  48538. void setCurrentColour (const Colour& newColour);
  48539. /** Tells the selector how many preset colour swatches you want to have on the component.
  48540. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48541. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48542. their values.
  48543. */
  48544. virtual int getNumSwatches() const;
  48545. /** Called by the selector to find out the colour of one of the swatches.
  48546. Your subclass should return the colour of the swatch with the given index.
  48547. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48548. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48549. their values.
  48550. */
  48551. virtual const Colour getSwatchColour (int index) const;
  48552. /** Called by the selector when the user puts a new colour into one of the swatches.
  48553. Your subclass should change the colour of the swatch with the given index.
  48554. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48555. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48556. their values.
  48557. */
  48558. virtual void setSwatchColour (int index, const Colour& newColour) const;
  48559. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48560. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48561. methods.
  48562. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48563. */
  48564. enum ColourIds
  48565. {
  48566. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  48567. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  48568. };
  48569. private:
  48570. class ColourSpaceView;
  48571. class HueSelectorComp;
  48572. class SwatchComponent;
  48573. friend class ColourSpaceView;
  48574. friend class ScopedPointer<ColourSpaceView>;
  48575. friend class HueSelectorComp;
  48576. friend class ScopedPointer<HueSelectorComp>;
  48577. Colour colour;
  48578. float h, s, v;
  48579. ScopedPointer<Slider> sliders[4];
  48580. ScopedPointer<ColourSpaceView> colourSpace;
  48581. ScopedPointer<HueSelectorComp> hueSelector;
  48582. OwnedArray <SwatchComponent> swatchComponents;
  48583. const int flags;
  48584. int edgeGap;
  48585. Rectangle<int> previewArea;
  48586. void setHue (float newH);
  48587. void setSV (float newS, float newV);
  48588. void updateHSV();
  48589. void update();
  48590. void sliderValueChanged (Slider*);
  48591. void paint (Graphics& g);
  48592. void resized();
  48593. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  48594. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  48595. // This constructor is here temporarily to prevent old code compiling, because the parameters
  48596. // have changed - if you get an error here, update your code to use the new constructor instead..
  48597. ColourSelector (bool);
  48598. #endif
  48599. };
  48600. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  48601. /*** End of inlined file: juce_ColourSelector.h ***/
  48602. #endif
  48603. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  48604. #endif
  48605. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48606. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  48607. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48608. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48609. /**
  48610. A component that displays a piano keyboard, whose notes can be clicked on.
  48611. This component will mimic a physical midi keyboard, showing the current state of
  48612. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  48613. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  48614. Another feature is that the computer keyboard can also be used to play notes. By
  48615. default it maps the top two rows of a standard querty keyboard to the notes, but
  48616. these can be remapped if needed. It will only respond to keypresses when it has
  48617. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  48618. The component is also a ChangeBroadcaster, so if you want to be informed when the
  48619. keyboard is scrolled, you can register a ChangeListener for callbacks.
  48620. @see MidiKeyboardState
  48621. */
  48622. class JUCE_API MidiKeyboardComponent : public Component,
  48623. public MidiKeyboardStateListener,
  48624. public ChangeBroadcaster,
  48625. private Timer,
  48626. private AsyncUpdater
  48627. {
  48628. public:
  48629. /** The direction of the keyboard.
  48630. @see setOrientation
  48631. */
  48632. enum Orientation
  48633. {
  48634. horizontalKeyboard,
  48635. verticalKeyboardFacingLeft,
  48636. verticalKeyboardFacingRight,
  48637. };
  48638. /** Creates a MidiKeyboardComponent.
  48639. @param state the midi keyboard model that this component will represent
  48640. @param orientation whether the keyboard is horizonal or vertical
  48641. */
  48642. MidiKeyboardComponent (MidiKeyboardState& state,
  48643. Orientation orientation);
  48644. /** Destructor. */
  48645. ~MidiKeyboardComponent();
  48646. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  48647. on the component.
  48648. Values are 0 to 1.0, where 1.0 is the heaviest.
  48649. @see setMidiChannel
  48650. */
  48651. void setVelocity (float velocity, bool useMousePositionForVelocity);
  48652. /** Changes the midi channel number that will be used for events triggered by clicking
  48653. on the component.
  48654. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  48655. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  48656. Although this is the channel used for outgoing events, the component can display
  48657. incoming events from more than one channel - see setMidiChannelsToDisplay()
  48658. @see setVelocity
  48659. */
  48660. void setMidiChannel (int midiChannelNumber);
  48661. /** Returns the midi channel that the keyboard is using for midi messages.
  48662. @see setMidiChannel
  48663. */
  48664. int getMidiChannel() const noexcept { return midiChannel; }
  48665. /** Sets a mask to indicate which incoming midi channels should be represented by
  48666. key movements.
  48667. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  48668. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  48669. in this mask, the on-screen keys will also go down.
  48670. By default, this mask is set to 0xffff (all channels displayed).
  48671. @see setMidiChannel
  48672. */
  48673. void setMidiChannelsToDisplay (int midiChannelMask);
  48674. /** Returns the current set of midi channels represented by the component.
  48675. This is the value that was set with setMidiChannelsToDisplay().
  48676. */
  48677. int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
  48678. /** Changes the width used to draw the white keys. */
  48679. void setKeyWidth (float widthInPixels);
  48680. /** Returns the width that was set by setKeyWidth(). */
  48681. float getKeyWidth() const noexcept { return keyWidth; }
  48682. /** Changes the keyboard's current direction. */
  48683. void setOrientation (Orientation newOrientation);
  48684. /** Returns the keyboard's current direction. */
  48685. const Orientation getOrientation() const noexcept { return orientation; }
  48686. /** Sets the range of midi notes that the keyboard will be limited to.
  48687. By default the range is 0 to 127 (inclusive), but you can limit this if you
  48688. only want a restricted set of the keys to be shown.
  48689. Note that the values here are inclusive and must be between 0 and 127.
  48690. */
  48691. void setAvailableRange (int lowestNote,
  48692. int highestNote);
  48693. /** Returns the first note in the available range.
  48694. @see setAvailableRange
  48695. */
  48696. int getRangeStart() const noexcept { return rangeStart; }
  48697. /** Returns the last note in the available range.
  48698. @see setAvailableRange
  48699. */
  48700. int getRangeEnd() const noexcept { return rangeEnd; }
  48701. /** If the keyboard extends beyond the size of the component, this will scroll
  48702. it to show the given key at the start.
  48703. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  48704. base class to send a callback to any ChangeListeners that have been registered.
  48705. */
  48706. void setLowestVisibleKey (int noteNumber);
  48707. /** Returns the number of the first key shown in the component.
  48708. @see setLowestVisibleKey
  48709. */
  48710. int getLowestVisibleKey() const noexcept { return firstKey; }
  48711. /** Returns the length of the black notes.
  48712. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  48713. */
  48714. int getBlackNoteLength() const noexcept { return blackNoteLength; }
  48715. /** If set to true, then scroll buttons will appear at either end of the keyboard
  48716. if there are too many notes to fit them all in the component at once.
  48717. */
  48718. void setScrollButtonsVisible (bool canScroll);
  48719. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48720. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48721. methods.
  48722. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48723. */
  48724. enum ColourIds
  48725. {
  48726. whiteNoteColourId = 0x1005000,
  48727. blackNoteColourId = 0x1005001,
  48728. keySeparatorLineColourId = 0x1005002,
  48729. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  48730. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  48731. textLabelColourId = 0x1005005,
  48732. upDownButtonBackgroundColourId = 0x1005006,
  48733. upDownButtonArrowColourId = 0x1005007
  48734. };
  48735. /** Returns the position within the component of the left-hand edge of a key.
  48736. Depending on the keyboard's orientation, this may be a horizontal or vertical
  48737. distance, in either direction.
  48738. */
  48739. int getKeyStartPosition (const int midiNoteNumber) const;
  48740. /** Deletes all key-mappings.
  48741. @see setKeyPressForNote
  48742. */
  48743. void clearKeyMappings();
  48744. /** Maps a key-press to a given note.
  48745. @param key the key that should trigger the note
  48746. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  48747. be. The actual midi note that gets played will be
  48748. this value + (12 * the current base octave). To change
  48749. the base octave, see setKeyPressBaseOctave()
  48750. */
  48751. void setKeyPressForNote (const KeyPress& key,
  48752. int midiNoteOffsetFromC);
  48753. /** Removes any key-mappings for a given note.
  48754. For a description of what the note number means, see setKeyPressForNote().
  48755. */
  48756. void removeKeyPressForNote (int midiNoteOffsetFromC);
  48757. /** Changes the base note above which key-press-triggered notes are played.
  48758. The set of key-mappings that trigger notes can be moved up and down to cover
  48759. the entire scale using this method.
  48760. The value passed in is an octave number between 0 and 10 (inclusive), and
  48761. indicates which C is the base note to which the key-mapped notes are
  48762. relative.
  48763. */
  48764. void setKeyPressBaseOctave (int newOctaveNumber);
  48765. /** This sets the octave number which is shown as the octave number for middle C.
  48766. This affects only the default implementation of getWhiteNoteText(), which
  48767. passes this octave number to MidiMessage::getMidiNoteName() in order to
  48768. get the note text. See MidiMessage::getMidiNoteName() for more info about
  48769. the parameter.
  48770. By default this value is set to 3.
  48771. @see getOctaveForMiddleC
  48772. */
  48773. void setOctaveForMiddleC (int octaveNumForMiddleC);
  48774. /** This returns the value set by setOctaveForMiddleC().
  48775. @see setOctaveForMiddleC
  48776. */
  48777. int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
  48778. /** @internal */
  48779. void paint (Graphics& g);
  48780. /** @internal */
  48781. void resized();
  48782. /** @internal */
  48783. void mouseMove (const MouseEvent& e);
  48784. /** @internal */
  48785. void mouseDrag (const MouseEvent& e);
  48786. /** @internal */
  48787. void mouseDown (const MouseEvent& e);
  48788. /** @internal */
  48789. void mouseUp (const MouseEvent& e);
  48790. /** @internal */
  48791. void mouseEnter (const MouseEvent& e);
  48792. /** @internal */
  48793. void mouseExit (const MouseEvent& e);
  48794. /** @internal */
  48795. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  48796. /** @internal */
  48797. void timerCallback();
  48798. /** @internal */
  48799. bool keyStateChanged (bool isKeyDown);
  48800. /** @internal */
  48801. void focusLost (FocusChangeType cause);
  48802. /** @internal */
  48803. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  48804. /** @internal */
  48805. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  48806. /** @internal */
  48807. void handleAsyncUpdate();
  48808. /** @internal */
  48809. void colourChanged();
  48810. protected:
  48811. /** Draws a white note in the given rectangle.
  48812. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48813. currently pressed down.
  48814. When doing this, be sure to note the keyboard's orientation.
  48815. */
  48816. virtual void drawWhiteNote (int midiNoteNumber,
  48817. Graphics& g,
  48818. int x, int y, int w, int h,
  48819. bool isDown, bool isOver,
  48820. const Colour& lineColour,
  48821. const Colour& textColour);
  48822. /** Draws a black note in the given rectangle.
  48823. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48824. currently pressed down.
  48825. When doing this, be sure to note the keyboard's orientation.
  48826. */
  48827. virtual void drawBlackNote (int midiNoteNumber,
  48828. Graphics& g,
  48829. int x, int y, int w, int h,
  48830. bool isDown, bool isOver,
  48831. const Colour& noteFillColour);
  48832. /** Allows text to be drawn on the white notes.
  48833. By default this is used to label the C in each octave, but could be used for other things.
  48834. @see setOctaveForMiddleC
  48835. */
  48836. virtual const String getWhiteNoteText (const int midiNoteNumber);
  48837. /** Draws the up and down buttons that change the base note. */
  48838. virtual void drawUpDownButton (Graphics& g, int w, int h,
  48839. const bool isMouseOver,
  48840. const bool isButtonPressed,
  48841. const bool movesOctavesUp);
  48842. /** Callback when the mouse is clicked on a key.
  48843. You could use this to do things like handle right-clicks on keys, etc.
  48844. Return true if you want the click to trigger the note, or false if you
  48845. want to handle it yourself and not have the note played.
  48846. @see mouseDraggedToKey
  48847. */
  48848. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  48849. /** Callback when the mouse is dragged from one key onto another.
  48850. @see mouseDownOnKey
  48851. */
  48852. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  48853. /** Calculates the positon of a given midi-note.
  48854. This can be overridden to create layouts with custom key-widths.
  48855. @param midiNoteNumber the note to find
  48856. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  48857. @param x the x position of the left-hand edge of the key (this method
  48858. always works in terms of a horizontal keyboard)
  48859. @param w the width of the key
  48860. */
  48861. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  48862. int& x, int& w) const;
  48863. private:
  48864. friend class MidiKeyboardUpDownButton;
  48865. MidiKeyboardState& state;
  48866. int xOffset, blackNoteLength;
  48867. float keyWidth;
  48868. Orientation orientation;
  48869. int midiChannel, midiInChannelMask;
  48870. float velocity;
  48871. int noteUnderMouse, mouseDownNote;
  48872. BigInteger keysPressed, keysCurrentlyDrawnDown;
  48873. int rangeStart, rangeEnd, firstKey;
  48874. bool canScroll, mouseDragging, useMousePositionForVelocity;
  48875. ScopedPointer<Button> scrollDown, scrollUp;
  48876. Array <KeyPress> keyPresses;
  48877. Array <int> keyPressNotes;
  48878. int keyMappingOctave;
  48879. int octaveNumForMiddleC;
  48880. static const uint8 whiteNotes[];
  48881. static const uint8 blackNotes[];
  48882. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  48883. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  48884. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  48885. void resetAnyKeysInUse();
  48886. void updateNoteUnderMouse (const Point<int>& pos);
  48887. void repaintNote (const int midiNoteNumber);
  48888. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  48889. };
  48890. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48891. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  48892. #endif
  48893. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48894. /*** Start of inlined file: juce_NSViewComponent.h ***/
  48895. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48896. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48897. #if ! DOXYGEN
  48898. class NSViewComponentInternal;
  48899. #endif
  48900. #if JUCE_MAC || DOXYGEN
  48901. /**
  48902. A Mac-specific class that can create and embed an NSView inside itself.
  48903. To use it, create one of these, put it in place and make sure it's visible in a
  48904. window, then use setView() to assign an NSView to it. The view will then be
  48905. moved and resized to follow the movements of this component.
  48906. Of course, since the view is a native object, it'll obliterate any
  48907. juce components that may overlap this component, but that's life.
  48908. */
  48909. class JUCE_API NSViewComponent : public Component
  48910. {
  48911. public:
  48912. /** Create an initially-empty container. */
  48913. NSViewComponent();
  48914. /** Destructor. */
  48915. ~NSViewComponent();
  48916. /** Assigns an NSView to this peer.
  48917. The view will be retained and released by this component for as long as
  48918. it is needed. To remove the current view, just call setView (nullptr).
  48919. Note: a void* is used here to avoid including the cocoa headers as
  48920. part of the juce.h, but the method expects an NSView*.
  48921. */
  48922. void setView (void* nsView);
  48923. /** Returns the current NSView.
  48924. Note: a void* is returned here to avoid including the cocoa headers as
  48925. a requirement of juce.h, so you should just cast the object to an NSView*.
  48926. */
  48927. void* getView() const;
  48928. /** Resizes this component to fit the view that it contains. */
  48929. void resizeToFitView();
  48930. /** @internal */
  48931. void paint (Graphics& g);
  48932. private:
  48933. friend class NSViewComponentInternal;
  48934. ScopedPointer <NSViewComponentInternal> info;
  48935. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  48936. };
  48937. #endif
  48938. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48939. /*** End of inlined file: juce_NSViewComponent.h ***/
  48940. #endif
  48941. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48942. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  48943. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48944. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48945. // this is used to disable OpenGL, and is defined in juce_Config.h
  48946. #if JUCE_OPENGL || DOXYGEN
  48947. /**
  48948. Represents the various properties of an OpenGL bitmap format.
  48949. @see OpenGLComponent::setPixelFormat
  48950. */
  48951. class JUCE_API OpenGLPixelFormat
  48952. {
  48953. public:
  48954. /** Creates an OpenGLPixelFormat.
  48955. The default constructor just initialises the object as a simple 8-bit
  48956. RGBA format.
  48957. */
  48958. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  48959. int alphaBits = 8,
  48960. int depthBufferBits = 16,
  48961. int stencilBufferBits = 0);
  48962. OpenGLPixelFormat (const OpenGLPixelFormat&);
  48963. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  48964. bool operator== (const OpenGLPixelFormat&) const;
  48965. int redBits; /**< The number of bits per pixel to use for the red channel. */
  48966. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  48967. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  48968. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  48969. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  48970. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  48971. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  48972. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  48973. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  48974. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  48975. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  48976. /** Returns a list of all the pixel formats that can be used in this system.
  48977. A reference component is needed in case there are multiple screens with different
  48978. capabilities - in which case, the one that the component is on will be used.
  48979. */
  48980. static void getAvailablePixelFormats (Component* component,
  48981. OwnedArray <OpenGLPixelFormat>& results);
  48982. private:
  48983. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  48984. };
  48985. /**
  48986. A base class for types of OpenGL context.
  48987. An OpenGLComponent will supply its own context for drawing in its window.
  48988. */
  48989. class JUCE_API OpenGLContext
  48990. {
  48991. public:
  48992. /** Destructor. */
  48993. virtual ~OpenGLContext();
  48994. /** Makes this context the currently active one. */
  48995. virtual bool makeActive() const noexcept = 0;
  48996. /** If this context is currently active, it is disactivated. */
  48997. virtual bool makeInactive() const noexcept = 0;
  48998. /** Returns true if this context is currently active. */
  48999. virtual bool isActive() const noexcept = 0;
  49000. /** Swaps the buffers (if the context can do this). */
  49001. virtual void swapBuffers() = 0;
  49002. /** Sets whether the context checks the vertical sync before swapping.
  49003. The value is the number of frames to allow between buffer-swapping. This is
  49004. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  49005. and greater numbers indicate that it should swap less often.
  49006. Returns true if it sets the value successfully.
  49007. */
  49008. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  49009. /** Returns the current swap-sync interval.
  49010. See setSwapInterval() for info about the value returned.
  49011. */
  49012. virtual int getSwapInterval() const = 0;
  49013. /** Returns the pixel format being used by this context. */
  49014. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  49015. /** For windowed contexts, this moves the context within the bounds of
  49016. its parent window.
  49017. */
  49018. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  49019. /** For windowed contexts, this triggers a repaint of the window.
  49020. (Not relevent on all platforms).
  49021. */
  49022. virtual void repaint() = 0;
  49023. /** Returns an OS-dependent handle to the raw GL context.
  49024. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  49025. a GLXContext.
  49026. */
  49027. virtual void* getRawContext() const noexcept = 0;
  49028. /** Deletes the context.
  49029. This must only be called on the message thread, or will deadlock.
  49030. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  49031. to call any other OpenGL function afterwards.
  49032. This doesn't touch other resources, such as window handles, etc.
  49033. You'll probably never have to call this method directly.
  49034. */
  49035. virtual void deleteContext() = 0;
  49036. /** Returns the context that's currently in active use by the calling thread.
  49037. Returns 0 if there isn't an active context.
  49038. */
  49039. static OpenGLContext* getCurrentContext();
  49040. protected:
  49041. OpenGLContext() noexcept;
  49042. private:
  49043. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  49044. };
  49045. /**
  49046. A component that contains an OpenGL canvas.
  49047. Override this, add it to whatever component you want to, and use the renderOpenGL()
  49048. method to draw its contents.
  49049. */
  49050. class JUCE_API OpenGLComponent : public Component
  49051. {
  49052. public:
  49053. /** Used to select the type of openGL API to use, if more than one choice is available
  49054. on a particular platform.
  49055. */
  49056. enum OpenGLType
  49057. {
  49058. openGLDefault = 0,
  49059. #if JUCE_IOS
  49060. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  49061. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  49062. #endif
  49063. };
  49064. /** Creates an OpenGLComponent.
  49065. If useBackgroundThread is true, the component will launch a background thread
  49066. to do the rendering. If false, then renderOpenGL() will be called as part of the
  49067. normal paint() method.
  49068. */
  49069. OpenGLComponent (OpenGLType type = openGLDefault,
  49070. bool useBackgroundThread = false);
  49071. /** Destructor. */
  49072. ~OpenGLComponent();
  49073. /** Changes the pixel format used by this component.
  49074. @see OpenGLPixelFormat::getAvailablePixelFormats()
  49075. */
  49076. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  49077. /** Returns the pixel format that this component is currently using. */
  49078. const OpenGLPixelFormat getPixelFormat() const;
  49079. /** Specifies an OpenGL context which should be shared with the one that this
  49080. component is using.
  49081. This is an OpenGL feature that lets two contexts share their texture data.
  49082. Note that this pointer is stored by the component, and when the component
  49083. needs to recreate its internal context for some reason, the same context
  49084. will be used again to share lists. So if you pass a context in here,
  49085. don't delete the context while this component is still using it! You can
  49086. call shareWith (nullptr) to stop this component from sharing with it.
  49087. */
  49088. void shareWith (OpenGLContext* contextToShareListsWith);
  49089. /** Returns the context that this component is sharing with.
  49090. @see shareWith
  49091. */
  49092. OpenGLContext* getShareContext() const noexcept { return contextToShareListsWith; }
  49093. /** Flips the openGL buffers over. */
  49094. void swapBuffers();
  49095. /** Returns true if the component is performing the rendering on a background thread.
  49096. This property is specified in the constructor.
  49097. */
  49098. bool isUsingDedicatedThread() const noexcept { return useThread; }
  49099. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  49100. When this is called, makeCurrentContextActive() will already have been called
  49101. for you, so you just need to draw.
  49102. */
  49103. virtual void renderOpenGL() = 0;
  49104. /** This method is called when the component creates a new OpenGL context.
  49105. A new context may be created when the component is first used, or when it
  49106. is moved to a different window, or when the window is hidden and re-shown,
  49107. etc.
  49108. You can use this callback as an opportunity to set up things like textures
  49109. that your context needs.
  49110. New contexts are created on-demand by the makeCurrentContextActive() method - so
  49111. if the context is deleted, e.g. by changing the pixel format or window, no context
  49112. will be created until the next call to makeCurrentContextActive(), which will
  49113. synchronously create one and call this method. This means that if you're using
  49114. a non-GUI thread for rendering, you can make sure this method is be called by
  49115. your renderer thread.
  49116. When this callback happens, the context will already have been made current
  49117. using the makeCurrentContextActive() method, so there's no need to call it
  49118. again in your code.
  49119. */
  49120. virtual void newOpenGLContextCreated() = 0;
  49121. /** This method is called when the component shuts down its OpenGL context.
  49122. You can use this callback to delete textures and any other OpenGL objects you
  49123. created in the component's context. Be aware: if you are using a render
  49124. thread, this may be called on the thread.
  49125. When this callback happens, the context will have been made current
  49126. using the makeCurrentContextActive() method, so there's no need to call it
  49127. again in your code.
  49128. */
  49129. virtual void releaseOpenGLContext() {}
  49130. /** Returns the context that will draw into this component.
  49131. This may return 0 if the component is currently invisible or hasn't currently
  49132. got a context. The context object can be deleted and a new one created during
  49133. the lifetime of this component, and there may be times when it doesn't have one.
  49134. @see newOpenGLContextCreated()
  49135. */
  49136. OpenGLContext* getCurrentContext() const noexcept { return context; }
  49137. /** Makes this component the current openGL context.
  49138. You might want to use this in things like your resize() method, before calling
  49139. GL commands.
  49140. If this returns false, then the context isn't active, so you should avoid
  49141. making any calls.
  49142. This call may actually create a context if one isn't currently initialised. If
  49143. it does this, it will also synchronously call the newOpenGLContextCreated()
  49144. method to let you initialise it as necessary.
  49145. @see OpenGLContext::makeActive
  49146. */
  49147. bool makeCurrentContextActive();
  49148. /** Stops the current component being the active OpenGL context.
  49149. This is the opposite of makeCurrentContextActive()
  49150. @see OpenGLContext::makeInactive
  49151. */
  49152. void makeCurrentContextInactive();
  49153. /** Returns true if this component's context is the active openGL context for the
  49154. current thread.
  49155. @see OpenGLContext::isActive
  49156. */
  49157. bool isActiveContext() const noexcept;
  49158. /** Calls the rendering callback, and swaps the buffers afterwards.
  49159. This is called automatically by paint() when the component needs to be rendered.
  49160. Returns true if the operation succeeded.
  49161. */
  49162. virtual bool renderAndSwapBuffers();
  49163. /** This returns a critical section that can be used to lock the current context.
  49164. Because the context that is used by this component can change, e.g. when the
  49165. component is shown or hidden, then if you're rendering to it on a background
  49166. thread, this allows you to lock the context for the duration of your rendering
  49167. routine.
  49168. */
  49169. CriticalSection& getContextLock() noexcept { return contextLock; }
  49170. /** Delete the context.
  49171. You should only need to call this if you've written a custom thread - if so, make
  49172. sure that your thread calls this before it terminates.
  49173. */
  49174. void deleteContext();
  49175. /** Returns the native handle of an embedded heavyweight window, if there is one.
  49176. E.g. On windows, this will return the HWND of the sub-window containing
  49177. the opengl context, on the mac it'll be the NSOpenGLView.
  49178. */
  49179. void* getNativeWindowHandle() const;
  49180. protected:
  49181. /** Kicks off a thread to start rendering.
  49182. The default implementation creates and manages an internal thread that tries
  49183. to render at around 50fps, but this can be overloaded to create a custom thread.
  49184. */
  49185. virtual void startRenderThread();
  49186. /** Cleans up the rendering thread.
  49187. Used to shut down the thread that was started by startRenderThread(). If you've
  49188. created a custom thread, then you should overload this to clean it up and delete it.
  49189. */
  49190. virtual void stopRenderThread();
  49191. /** @internal */
  49192. void paint (Graphics& g);
  49193. private:
  49194. const OpenGLType type;
  49195. class OpenGLComponentRenderThread;
  49196. friend class OpenGLComponentRenderThread;
  49197. friend class ScopedPointer <OpenGLComponentRenderThread>;
  49198. ScopedPointer <OpenGLComponentRenderThread> renderThread;
  49199. class OpenGLComponentWatcher;
  49200. friend class OpenGLComponentWatcher;
  49201. friend class ScopedPointer <OpenGLComponentWatcher>;
  49202. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  49203. ScopedPointer <OpenGLContext> context;
  49204. OpenGLContext* contextToShareListsWith;
  49205. CriticalSection contextLock;
  49206. OpenGLPixelFormat preferredPixelFormat;
  49207. bool needToUpdateViewport, needToDeleteContext, threadStarted;
  49208. const bool useThread;
  49209. OpenGLContext* createContext();
  49210. void updateContext();
  49211. void updateContextPosition();
  49212. void stopBackgroundThread();
  49213. void recreateContextAsync();
  49214. void internalRepaint (int x, int y, int w, int h);
  49215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  49216. };
  49217. #endif
  49218. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49219. /*** End of inlined file: juce_OpenGLComponent.h ***/
  49220. #endif
  49221. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49222. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  49223. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49224. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49225. /**
  49226. A component with a set of buttons at the top for changing between pages of
  49227. preferences.
  49228. This is just a handy way of writing a Mac-style preferences panel where you
  49229. have a row of buttons along the top for the different preference categories,
  49230. each button having an icon above its name. Clicking these will show an
  49231. appropriate prefs page below it.
  49232. You can either put one of these inside your own component, or just use the
  49233. showInDialogBox() method to show it in a window and run it modally.
  49234. To use it, just add a set of named pages with the addSettingsPage() method,
  49235. and implement the createComponentForPage() method to create suitable components
  49236. for each of these pages.
  49237. */
  49238. class JUCE_API PreferencesPanel : public Component,
  49239. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  49240. {
  49241. public:
  49242. /** Creates an empty panel.
  49243. Use addSettingsPage() to add some pages to it in your constructor.
  49244. */
  49245. PreferencesPanel();
  49246. /** Destructor. */
  49247. ~PreferencesPanel();
  49248. /** Creates a page using a set of drawables to define the page's icon.
  49249. Note that the other version of this method is much easier if you're using
  49250. an image instead of a custom drawable.
  49251. @param pageTitle the name of this preferences page - you'll need to
  49252. make sure your createComponentForPage() method creates
  49253. a suitable component when it is passed this name
  49254. @param normalIcon the drawable to display in the page's button normally
  49255. @param overIcon the drawable to display in the page's button when the mouse is over
  49256. @param downIcon the drawable to display in the page's button when the button is down
  49257. @see DrawableButton
  49258. */
  49259. void addSettingsPage (const String& pageTitle,
  49260. const Drawable* normalIcon,
  49261. const Drawable* overIcon,
  49262. const Drawable* downIcon);
  49263. /** Creates a page using a set of drawables to define the page's icon.
  49264. The other version of this method gives you more control over the icon, but this
  49265. one is much easier if you're just loading it from a file.
  49266. @param pageTitle the name of this preferences page - you'll need to
  49267. make sure your createComponentForPage() method creates
  49268. a suitable component when it is passed this name
  49269. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  49270. For this to look good, you'll probably want to use a nice
  49271. transparent png file.
  49272. @param imageDataSize the size of the image data, in bytes
  49273. */
  49274. void addSettingsPage (const String& pageTitle,
  49275. const void* imageData,
  49276. int imageDataSize);
  49277. /** Utility method to display this panel in a DialogWindow.
  49278. Calling this will create a DialogWindow containing this panel with the
  49279. given size and title, and will run it modally, returning when the user
  49280. closes the dialog box.
  49281. */
  49282. void showInDialogBox (const String& dialogTitle,
  49283. int dialogWidth,
  49284. int dialogHeight,
  49285. const Colour& backgroundColour = Colours::white);
  49286. /** Subclasses must override this to return a component for each preferences page.
  49287. The subclass should return a pointer to a new component representing the named
  49288. page, which the panel will then display.
  49289. The panel will delete the component later when the user goes to another page
  49290. or deletes the panel.
  49291. */
  49292. virtual Component* createComponentForPage (const String& pageName) = 0;
  49293. /** Changes the current page being displayed. */
  49294. void setCurrentPage (const String& pageName);
  49295. /** Returns the size of the buttons shown along the top. */
  49296. int getButtonSize() const noexcept;
  49297. /** Changes the size of the buttons shown along the top. */
  49298. void setButtonSize (int newSize);
  49299. /** @internal */
  49300. void resized();
  49301. /** @internal */
  49302. void paint (Graphics& g);
  49303. /** @internal */
  49304. void buttonClicked (Button* button);
  49305. private:
  49306. String currentPageName;
  49307. ScopedPointer <Component> currentPage;
  49308. OwnedArray<DrawableButton> buttons;
  49309. int buttonSize;
  49310. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  49311. };
  49312. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49313. /*** End of inlined file: juce_PreferencesPanel.h ***/
  49314. #endif
  49315. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49316. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  49317. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49318. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49319. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  49320. // amalgamated build)
  49321. #ifndef DOXYGEN
  49322. #if JUCE_WINDOWS
  49323. typedef ActiveXControlComponent QTCompBaseClass;
  49324. #elif JUCE_MAC
  49325. typedef NSViewComponent QTCompBaseClass;
  49326. #endif
  49327. #endif
  49328. // this is used to disable QuickTime, and is defined in juce_Config.h
  49329. #if JUCE_QUICKTIME || DOXYGEN
  49330. /**
  49331. A window that can play back a QuickTime movie.
  49332. */
  49333. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  49334. {
  49335. public:
  49336. /** Creates a QuickTimeMovieComponent, initially blank.
  49337. Use the loadMovie() method to load a movie once you've added the
  49338. component to a window, (or put it on the desktop as a heavyweight window).
  49339. Loading a movie when the component isn't visible can cause problems, as
  49340. QuickTime needs a window handle to initialise properly.
  49341. */
  49342. QuickTimeMovieComponent();
  49343. /** Destructor. */
  49344. ~QuickTimeMovieComponent();
  49345. /** Returns true if QT is installed and working on this machine.
  49346. */
  49347. static bool isQuickTimeAvailable() noexcept;
  49348. /** Tries to load a QuickTime movie from a file into the player.
  49349. It's best to call this function once you've added the component to a window,
  49350. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49351. component isn't visible can cause problems, because QuickTime needs a window
  49352. handle to do its stuff.
  49353. @param movieFile the .mov file to open
  49354. @param isControllerVisible whether to show a controller bar at the bottom
  49355. @returns true if the movie opens successfully
  49356. */
  49357. bool loadMovie (const File& movieFile,
  49358. bool isControllerVisible);
  49359. /** Tries to load a QuickTime movie from a URL into the player.
  49360. It's best to call this function once you've added the component to a window,
  49361. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49362. component isn't visible can cause problems, because QuickTime needs a window
  49363. handle to do its stuff.
  49364. @param movieURL the .mov file to open
  49365. @param isControllerVisible whether to show a controller bar at the bottom
  49366. @returns true if the movie opens successfully
  49367. */
  49368. bool loadMovie (const URL& movieURL,
  49369. bool isControllerVisible);
  49370. /** Tries to load a QuickTime movie from a stream into the player.
  49371. It's best to call this function once you've added the component to a window,
  49372. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49373. component isn't visible can cause problems, because QuickTime needs a window
  49374. handle to do its stuff.
  49375. @param movieStream a stream containing a .mov file. The component may try
  49376. to read the whole stream before playing, rather than
  49377. streaming from it.
  49378. @param isControllerVisible whether to show a controller bar at the bottom
  49379. @returns true if the movie opens successfully
  49380. */
  49381. bool loadMovie (InputStream* movieStream,
  49382. bool isControllerVisible);
  49383. /** Closes the movie, if one is open. */
  49384. void closeMovie();
  49385. /** Returns the movie file that is currently open.
  49386. If there isn't one, this returns File::nonexistent
  49387. */
  49388. const File getCurrentMovieFile() const;
  49389. /** Returns true if there's currently a movie open. */
  49390. bool isMovieOpen() const;
  49391. /** Returns the length of the movie, in seconds. */
  49392. double getMovieDuration() const;
  49393. /** Returns the movie's natural size, in pixels.
  49394. You can use this to resize the component to show the movie at its preferred
  49395. scale.
  49396. If no movie is loaded, the size returned will be 0 x 0.
  49397. */
  49398. void getMovieNormalSize (int& width, int& height) const;
  49399. /** This will position the component within a given area, keeping its aspect
  49400. ratio correct according to the movie's normal size.
  49401. The component will be made as large as it can go within the space, and will
  49402. be aligned according to the justification value if this means there are gaps at
  49403. the top or sides.
  49404. */
  49405. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  49406. const RectanglePlacement& placement);
  49407. /** Starts the movie playing. */
  49408. void play();
  49409. /** Stops the movie playing. */
  49410. void stop();
  49411. /** Returns true if the movie is currently playing. */
  49412. bool isPlaying() const;
  49413. /** Moves the movie's position back to the start. */
  49414. void goToStart();
  49415. /** Sets the movie's position to a given time. */
  49416. void setPosition (double seconds);
  49417. /** Returns the current play position of the movie. */
  49418. double getPosition() const;
  49419. /** Changes the movie playback rate.
  49420. A value of 1 is normal speed, greater values play it proportionately faster,
  49421. smaller values play it slower.
  49422. */
  49423. void setSpeed (float newSpeed);
  49424. /** Changes the movie's playback volume.
  49425. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  49426. */
  49427. void setMovieVolume (float newVolume);
  49428. /** Returns the movie's playback volume.
  49429. @returns the volume in the range 0 (silent) to 1.0 (full)
  49430. */
  49431. float getMovieVolume() const;
  49432. /** Tells the movie whether it should loop. */
  49433. void setLooping (bool shouldLoop);
  49434. /** Returns true if the movie is currently looping.
  49435. @see setLooping
  49436. */
  49437. bool isLooping() const;
  49438. /** True if the native QuickTime controller bar is shown in the window.
  49439. @see loadMovie
  49440. */
  49441. bool isControllerVisible() const;
  49442. /** @internal */
  49443. void paint (Graphics& g);
  49444. private:
  49445. File movieFile;
  49446. bool movieLoaded, controllerVisible, looping;
  49447. #if JUCE_WINDOWS
  49448. void parentHierarchyChanged();
  49449. void visibilityChanged();
  49450. void createControlIfNeeded();
  49451. bool isControlCreated() const;
  49452. class Pimpl;
  49453. friend class ScopedPointer <Pimpl>;
  49454. ScopedPointer <Pimpl> pimpl;
  49455. #else
  49456. void* movie;
  49457. #endif
  49458. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  49459. };
  49460. #endif
  49461. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49462. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  49463. #endif
  49464. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49465. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  49466. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49467. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49468. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  49469. /**
  49470. On Windows only, this component sits in the taskbar tray as a small icon.
  49471. To use it, just create one of these components, but don't attempt to make it
  49472. visible, add it to a parent, or put it on the desktop.
  49473. You can then call setIconImage() to create an icon for it in the taskbar.
  49474. To change the icon's tooltip, you can use setIconTooltip().
  49475. To respond to mouse-events, you can override the normal mouseDown(),
  49476. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  49477. position will not be valid, you can use this to respond to clicks. Traditionally
  49478. you'd use a left-click to show your application's window, and a right-click
  49479. to show a pop-up menu.
  49480. */
  49481. class JUCE_API SystemTrayIconComponent : public Component
  49482. {
  49483. public:
  49484. SystemTrayIconComponent();
  49485. /** Destructor. */
  49486. ~SystemTrayIconComponent();
  49487. /** Changes the image shown in the taskbar.
  49488. */
  49489. void setIconImage (const Image& newImage);
  49490. /** Changes the tooltip that Windows shows above the icon. */
  49491. void setIconTooltip (const String& tooltip);
  49492. #if JUCE_LINUX
  49493. /** @internal */
  49494. void paint (Graphics& g);
  49495. #endif
  49496. private:
  49497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  49498. };
  49499. #endif
  49500. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49501. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  49502. #endif
  49503. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49504. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  49505. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49506. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49507. #if JUCE_WEB_BROWSER || DOXYGEN
  49508. #if ! DOXYGEN
  49509. class WebBrowserComponentInternal;
  49510. #endif
  49511. /**
  49512. A component that displays an embedded web browser.
  49513. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  49514. Windows, probably IE.
  49515. */
  49516. class JUCE_API WebBrowserComponent : public Component
  49517. {
  49518. public:
  49519. /** Creates a WebBrowserComponent.
  49520. Once it's created and visible, send the browser to a URL using goToURL().
  49521. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  49522. component is taken offscreen, it'll clear the current page
  49523. and replace it with a blank page - this can be handy to stop
  49524. the browser using resources in the background when it's not
  49525. actually being used.
  49526. */
  49527. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  49528. /** Destructor. */
  49529. ~WebBrowserComponent();
  49530. /** Sends the browser to a particular URL.
  49531. @param url the URL to go to.
  49532. @param headers an optional set of parameters to put in the HTTP header. If
  49533. you supply this, it should be a set of string in the form
  49534. "HeaderKey: HeaderValue"
  49535. @param postData an optional block of data that will be attached to the HTTP
  49536. POST request
  49537. */
  49538. void goToURL (const String& url,
  49539. const StringArray* headers = nullptr,
  49540. const MemoryBlock* postData = nullptr);
  49541. /** Stops the current page loading.
  49542. */
  49543. void stop();
  49544. /** Sends the browser back one page.
  49545. */
  49546. void goBack();
  49547. /** Sends the browser forward one page.
  49548. */
  49549. void goForward();
  49550. /** Refreshes the browser.
  49551. */
  49552. void refresh();
  49553. /** This callback is called when the browser is about to navigate
  49554. to a new location.
  49555. You can override this method to perform some action when the user
  49556. tries to go to a particular URL. To allow the operation to carry on,
  49557. return true, or return false to stop the navigation happening.
  49558. */
  49559. virtual bool pageAboutToLoad (const String& newURL);
  49560. /** @internal */
  49561. void paint (Graphics& g);
  49562. /** @internal */
  49563. void resized();
  49564. /** @internal */
  49565. void parentHierarchyChanged();
  49566. /** @internal */
  49567. void visibilityChanged();
  49568. private:
  49569. WebBrowserComponentInternal* browser;
  49570. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  49571. String lastURL;
  49572. StringArray lastHeaders;
  49573. MemoryBlock lastPostData;
  49574. void reloadLastURL();
  49575. void checkWindowAssociation();
  49576. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  49577. };
  49578. #endif
  49579. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49580. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  49581. #endif
  49582. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  49583. #endif
  49584. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  49585. /*** Start of inlined file: juce_CallOutBox.h ***/
  49586. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  49587. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  49588. /**
  49589. A box with a small arrow that can be used as a temporary pop-up window to show
  49590. extra controls when a button or other component is clicked.
  49591. Using one of these is similar to having a popup menu attached to a button or
  49592. other component - but it looks fancier, and has an arrow that can indicate the
  49593. object that it applies to.
  49594. Normally, you'd create one of these on the stack and run it modally, e.g.
  49595. @code
  49596. void mouseUp (const MouseEvent& e)
  49597. {
  49598. MyContentComponent content;
  49599. content.setSize (300, 300);
  49600. CallOutBox callOut (content, *this, nullptr);
  49601. callOut.runModalLoop();
  49602. }
  49603. @endcode
  49604. The call-out will resize and position itself when the content changes size.
  49605. */
  49606. class JUCE_API CallOutBox : public Component
  49607. {
  49608. public:
  49609. /** Creates a CallOutBox.
  49610. @param contentComponent the component to display inside the call-out. This should
  49611. already have a size set (although the call-out will also
  49612. update itself when the component's size is changed later).
  49613. Obviously this component must not be deleted until the
  49614. call-out box has been deleted.
  49615. @param componentToPointTo the component that the call-out's arrow should point towards
  49616. @param parentComponent if non-zero, this is the component to add the call-out to. If
  49617. this is zero, the call-out will be added to the desktop.
  49618. */
  49619. CallOutBox (Component& contentComponent,
  49620. Component& componentToPointTo,
  49621. Component* parentComponent);
  49622. /** Destructor. */
  49623. ~CallOutBox();
  49624. /** Changes the length of the arrow. */
  49625. void setArrowSize (float newSize);
  49626. /** Updates the position and size of the box.
  49627. You shouldn't normally need to call this, unless you need more precise control over the
  49628. layout.
  49629. @param newAreaToPointTo the rectangle to make the box's arrow point to
  49630. @param newAreaToFitIn the area within which the box's position should be constrained
  49631. */
  49632. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  49633. const Rectangle<int>& newAreaToFitIn);
  49634. /** @internal */
  49635. void paint (Graphics& g);
  49636. /** @internal */
  49637. void resized();
  49638. /** @internal */
  49639. void moved();
  49640. /** @internal */
  49641. void childBoundsChanged (Component*);
  49642. /** @internal */
  49643. bool hitTest (int x, int y);
  49644. /** @internal */
  49645. void inputAttemptWhenModal();
  49646. /** @internal */
  49647. bool keyPressed (const KeyPress& key);
  49648. /** @internal */
  49649. void handleCommandMessage (int commandId);
  49650. private:
  49651. int borderSpace;
  49652. float arrowSize;
  49653. Component& content;
  49654. Path outline;
  49655. Point<float> targetPoint;
  49656. Rectangle<int> availableArea, targetArea;
  49657. Image background;
  49658. void refreshPath();
  49659. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  49660. };
  49661. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  49662. /*** End of inlined file: juce_CallOutBox.h ***/
  49663. #endif
  49664. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49665. /*** Start of inlined file: juce_ComponentPeer.h ***/
  49666. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49667. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  49668. class ComponentBoundsConstrainer;
  49669. /**
  49670. The Component class uses a ComponentPeer internally to create and manage a real
  49671. operating-system window.
  49672. This is an abstract base class - the platform specific code contains implementations of
  49673. it for the various platforms.
  49674. User-code should very rarely need to have any involvement with this class.
  49675. @see Component::createNewPeer
  49676. */
  49677. class JUCE_API ComponentPeer
  49678. {
  49679. public:
  49680. /** A combination of these flags is passed to the ComponentPeer constructor. */
  49681. enum StyleFlags
  49682. {
  49683. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  49684. entry on the taskbar (ignored on MacOSX) */
  49685. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  49686. tooltip, etc. */
  49687. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  49688. through it (may not be possible on some platforms). */
  49689. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  49690. title bar and frame\. if not specified, the window will be
  49691. borderless. */
  49692. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  49693. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  49694. minimise button on it. */
  49695. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  49696. maximise button on it. */
  49697. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  49698. close button on it. */
  49699. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  49700. not be possible on all platforms). */
  49701. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  49702. do its own repainting, but only to repaint when the
  49703. performAnyPendingRepaintsNow() method is called. */
  49704. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  49705. be used for things like plugin windows, to stop them interfering
  49706. with the host's shortcut keys */
  49707. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  49708. };
  49709. /** Creates a peer.
  49710. The component is the one that we intend to represent, and the style flags are
  49711. a combination of the values in the StyleFlags enum
  49712. */
  49713. ComponentPeer (Component* component, int styleFlags);
  49714. /** Destructor. */
  49715. virtual ~ComponentPeer();
  49716. /** Returns the component being represented by this peer. */
  49717. Component* getComponent() const noexcept { return component; }
  49718. /** Returns the set of style flags that were set when the window was created.
  49719. @see Component::addToDesktop
  49720. */
  49721. int getStyleFlags() const noexcept { return styleFlags; }
  49722. /** Returns a unique ID for this peer.
  49723. Each peer that is created is given a different ID.
  49724. */
  49725. uint32 getUniqueID() const noexcept { return uniqueID; }
  49726. /** Returns the raw handle to whatever kind of window is being used.
  49727. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  49728. but rememeber there's no guarantees what you'll get back.
  49729. */
  49730. virtual void* getNativeHandle() const = 0;
  49731. /** Shows or hides the window. */
  49732. virtual void setVisible (bool shouldBeVisible) = 0;
  49733. /** Changes the title of the window. */
  49734. virtual void setTitle (const String& title) = 0;
  49735. /** Moves the window without changing its size.
  49736. If the native window is contained in another window, then the co-ordinates are
  49737. relative to the parent window's origin, not the screen origin.
  49738. This should result in a callback to handleMovedOrResized().
  49739. */
  49740. virtual void setPosition (int x, int y) = 0;
  49741. /** Resizes the window without changing its position.
  49742. This should result in a callback to handleMovedOrResized().
  49743. */
  49744. virtual void setSize (int w, int h) = 0;
  49745. /** Moves and resizes the window.
  49746. If the native window is contained in another window, then the co-ordinates are
  49747. relative to the parent window's origin, not the screen origin.
  49748. This should result in a callback to handleMovedOrResized().
  49749. */
  49750. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  49751. /** Returns the current position and size of the window.
  49752. If the native window is contained in another window, then the co-ordinates are
  49753. relative to the parent window's origin, not the screen origin.
  49754. */
  49755. virtual const Rectangle<int> getBounds() const = 0;
  49756. /** Returns the x-position of this window, relative to the screen's origin. */
  49757. virtual const Point<int> getScreenPosition() const = 0;
  49758. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  49759. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  49760. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  49761. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  49762. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  49763. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  49764. /** Converts a screen area to a position relative to the top-left of this component. */
  49765. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  49766. /** Minimises the window. */
  49767. virtual void setMinimised (bool shouldBeMinimised) = 0;
  49768. /** True if the window is currently minimised. */
  49769. virtual bool isMinimised() const = 0;
  49770. /** Enable/disable fullscreen mode for the window. */
  49771. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  49772. /** True if the window is currently full-screen. */
  49773. virtual bool isFullScreen() const = 0;
  49774. /** Sets the size to restore to if fullscreen mode is turned off. */
  49775. void setNonFullScreenBounds (const Rectangle<int>& newBounds) noexcept;
  49776. /** Returns the size to restore to if fullscreen mode is turned off. */
  49777. const Rectangle<int>& getNonFullScreenBounds() const noexcept;
  49778. /** Attempts to change the icon associated with this window.
  49779. */
  49780. virtual void setIcon (const Image& newIcon) = 0;
  49781. /** Sets a constrainer to use if the peer can resize itself.
  49782. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  49783. */
  49784. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) noexcept;
  49785. /** Returns the current constrainer, if one has been set. */
  49786. ComponentBoundsConstrainer* getConstrainer() const noexcept { return constrainer; }
  49787. /** Checks if a point is in the window.
  49788. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  49789. is false, then this returns false if the point is actually inside a child of this
  49790. window.
  49791. */
  49792. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  49793. /** Returns the size of the window frame that's around this window.
  49794. Whether or not the window has a normal window frame depends on the flags
  49795. that were set when the window was created by Component::addToDesktop()
  49796. */
  49797. virtual const BorderSize<int> getFrameSize() const = 0;
  49798. /** This is called when the window's bounds change.
  49799. A peer implementation must call this when the window is moved and resized, so that
  49800. this method can pass the message on to the component.
  49801. */
  49802. void handleMovedOrResized();
  49803. /** This is called if the screen resolution changes.
  49804. A peer implementation must call this if the monitor arrangement changes or the available
  49805. screen size changes.
  49806. */
  49807. void handleScreenSizeChange();
  49808. /** This is called to repaint the component into the given context. */
  49809. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  49810. /** Sets this window to either be always-on-top or normal.
  49811. Some kinds of window might not be able to do this, so should return false.
  49812. */
  49813. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  49814. /** Brings the window to the top, optionally also giving it focus. */
  49815. virtual void toFront (bool makeActive) = 0;
  49816. /** Moves the window to be just behind another one. */
  49817. virtual void toBehind (ComponentPeer* other) = 0;
  49818. /** Called when the window is brought to the front, either by the OS or by a call
  49819. to toFront().
  49820. */
  49821. void handleBroughtToFront();
  49822. /** True if the window has the keyboard focus. */
  49823. virtual bool isFocused() const = 0;
  49824. /** Tries to give the window keyboard focus. */
  49825. virtual void grabFocus() = 0;
  49826. /** Called when the window gains keyboard focus. */
  49827. void handleFocusGain();
  49828. /** Called when the window loses keyboard focus. */
  49829. void handleFocusLoss();
  49830. Component* getLastFocusedSubcomponent() const noexcept;
  49831. /** Called when a key is pressed.
  49832. For keycode info, see the KeyPress class.
  49833. Returns true if the keystroke was used.
  49834. */
  49835. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  49836. /** Called whenever a key is pressed or released.
  49837. Returns true if the keystroke was used.
  49838. */
  49839. bool handleKeyUpOrDown (bool isKeyDown);
  49840. /** Called whenever a modifier key is pressed or released. */
  49841. void handleModifierKeysChange();
  49842. /** Tells the window that text input may be required at the given position.
  49843. This may cause things like a virtual on-screen keyboard to appear, depending
  49844. on the OS.
  49845. */
  49846. virtual void textInputRequired (const Point<int>& position) = 0;
  49847. /** If there's some kind of OS input-method in progress, this should dismiss it. */
  49848. virtual void dismissPendingTextInput();
  49849. /** Returns the currently focused TextInputTarget, or null if none is found. */
  49850. TextInputTarget* findCurrentTextInputTarget();
  49851. /** Invalidates a region of the window to be repainted asynchronously. */
  49852. virtual void repaint (const Rectangle<int>& area) = 0;
  49853. /** This can be called (from the message thread) to cause the immediate redrawing
  49854. of any areas of this window that need repainting.
  49855. You shouldn't ever really need to use this, it's mainly for special purposes
  49856. like supporting audio plugins where the host's event loop is out of our control.
  49857. */
  49858. virtual void performAnyPendingRepaintsNow() = 0;
  49859. /** Changes the window's transparency. */
  49860. virtual void setAlpha (float newAlpha) = 0;
  49861. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  49862. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  49863. void handleUserClosingWindow();
  49864. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  49865. void handleFileDragExit (const StringArray& files);
  49866. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  49867. /** Resets the masking region.
  49868. The subclass should call this every time it's about to call the handlePaint
  49869. method.
  49870. @see addMaskedRegion
  49871. */
  49872. void clearMaskedRegion();
  49873. /** Adds a rectangle to the set of areas not to paint over.
  49874. A component can call this on its peer during its paint() method, to signal
  49875. that the painting code should ignore a given region. The reason
  49876. for this is to stop embedded windows (such as OpenGL) getting painted over.
  49877. The masked region is cleared each time before a paint happens, so a component
  49878. will have to make sure it calls this every time it's painted.
  49879. */
  49880. void addMaskedRegion (int x, int y, int w, int h);
  49881. /** Returns the number of currently-active peers.
  49882. @see getPeer
  49883. */
  49884. static int getNumPeers() noexcept;
  49885. /** Returns one of the currently-active peers.
  49886. @see getNumPeers
  49887. */
  49888. static ComponentPeer* getPeer (int index) noexcept;
  49889. /** Checks if this peer object is valid.
  49890. @see getNumPeers
  49891. */
  49892. static bool isValidPeer (const ComponentPeer* peer) noexcept;
  49893. virtual const StringArray getAvailableRenderingEngines();
  49894. virtual int getCurrentRenderingEngine() const;
  49895. virtual void setCurrentRenderingEngine (int index);
  49896. protected:
  49897. Component* const component;
  49898. const int styleFlags;
  49899. RectangleList maskedRegion;
  49900. Rectangle<int> lastNonFullscreenBounds;
  49901. uint32 lastPaintTime;
  49902. ComponentBoundsConstrainer* constrainer;
  49903. static void updateCurrentModifiers() noexcept;
  49904. private:
  49905. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  49906. Component* lastDragAndDropCompUnderMouse;
  49907. const uint32 uniqueID;
  49908. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  49909. friend class Component;
  49910. friend class Desktop;
  49911. static ComponentPeer* getPeerFor (const Component* component) noexcept;
  49912. void setLastDragDropTarget (Component* comp);
  49913. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  49914. };
  49915. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  49916. /*** End of inlined file: juce_ComponentPeer.h ***/
  49917. #endif
  49918. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49919. /*** Start of inlined file: juce_DialogWindow.h ***/
  49920. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49921. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  49922. /**
  49923. A dialog-box style window.
  49924. This class is a convenient way of creating a DocumentWindow with a close button
  49925. that can be triggered by pressing the escape key.
  49926. Any of the methods available to a DocumentWindow or ResizableWindow are also
  49927. available to this, so it can be made resizable, have a menu bar, etc.
  49928. To add items to the box, see the ResizableWindow::setContentOwned() or
  49929. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  49930. class - always put them in a content component!
  49931. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  49932. the user clicking the close button - for more info, see the DocumentWindow
  49933. help.
  49934. @see DocumentWindow, ResizableWindow
  49935. */
  49936. class JUCE_API DialogWindow : public DocumentWindow
  49937. {
  49938. public:
  49939. /** Creates a DialogWindow.
  49940. @param name the name to give the component - this is also
  49941. the title shown at the top of the window. To change
  49942. this later, use setName()
  49943. @param backgroundColour the colour to use for filling the window's background.
  49944. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49945. close button to be triggered
  49946. @param addToDesktop if true, the window will be automatically added to the
  49947. desktop; if false, you can use it as a child component
  49948. */
  49949. DialogWindow (const String& name,
  49950. const Colour& backgroundColour,
  49951. bool escapeKeyTriggersCloseButton,
  49952. bool addToDesktop = true);
  49953. /** Destructor.
  49954. If a content component has been set with setContentOwned(), it will be deleted.
  49955. */
  49956. ~DialogWindow();
  49957. /** Easy way of quickly showing a dialog box containing a given component.
  49958. This will open and display a DialogWindow containing a given component, making it
  49959. modal, but returning immediately to allow the dialog to finish in its own time. If
  49960. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  49961. instead.
  49962. To close the dialog programatically, you should call exitModalState (returnValue) on
  49963. the DialogWindow that is created. To find a pointer to this window from your
  49964. contentComponent, you can do something like this:
  49965. @code
  49966. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  49967. if (dw != nullptr)
  49968. dw->exitModalState (1234);
  49969. @endcode
  49970. @param dialogTitle the dialog box's title
  49971. @param contentComponent the content component for the dialog box. Make sure
  49972. that this has been set to the size you want it to
  49973. be before calling this method. The component won't
  49974. be deleted by this call, so you can re-use it or delete
  49975. it afterwards
  49976. @param componentToCentreAround if this is non-zero, it indicates a component that
  49977. you'd like to show this dialog box in front of. See the
  49978. DocumentWindow::centreAroundComponent() method for more
  49979. info on this parameter
  49980. @param backgroundColour a colour to use for the dialog box's background colour
  49981. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49982. close button to be triggered
  49983. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49984. a corner resizer
  49985. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49986. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49987. */
  49988. static void showDialog (const String& dialogTitle,
  49989. Component* contentComponent,
  49990. Component* componentToCentreAround,
  49991. const Colour& backgroundColour,
  49992. bool escapeKeyTriggersCloseButton,
  49993. bool shouldBeResizable = false,
  49994. bool useBottomRightCornerResizer = false);
  49995. /** Easy way of quickly showing a dialog box containing a given component.
  49996. This will open and display a DialogWindow containing a given component, returning
  49997. when the user clicks its close button.
  49998. It returns the value that was returned by the dialog box's runModalLoop() call.
  49999. To close the dialog programatically, you should call exitModalState (returnValue) on
  50000. the DialogWindow that is created. To find a pointer to this window from your
  50001. contentComponent, you can do something like this:
  50002. @code
  50003. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  50004. if (dw != nullptr)
  50005. dw->exitModalState (1234);
  50006. @endcode
  50007. @param dialogTitle the dialog box's title
  50008. @param contentComponent the content component for the dialog box. Make sure
  50009. that this has been set to the size you want it to
  50010. be before calling this method. The component won't
  50011. be deleted by this call, so you can re-use it or delete
  50012. it afterwards
  50013. @param componentToCentreAround if this is non-zero, it indicates a component that
  50014. you'd like to show this dialog box in front of. See the
  50015. DocumentWindow::centreAroundComponent() method for more
  50016. info on this parameter
  50017. @param backgroundColour a colour to use for the dialog box's background colour
  50018. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50019. close button to be triggered
  50020. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  50021. a corner resizer
  50022. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  50023. to use a border or corner resizer component. See ResizableWindow::setResizable()
  50024. */
  50025. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  50026. static int showModalDialog (const String& dialogTitle,
  50027. Component* contentComponent,
  50028. Component* componentToCentreAround,
  50029. const Colour& backgroundColour,
  50030. bool escapeKeyTriggersCloseButton,
  50031. bool shouldBeResizable = false,
  50032. bool useBottomRightCornerResizer = false);
  50033. #endif
  50034. protected:
  50035. /** @internal */
  50036. void resized();
  50037. private:
  50038. bool escapeKeyTriggersCloseButton;
  50039. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  50040. };
  50041. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  50042. /*** End of inlined file: juce_DialogWindow.h ***/
  50043. #endif
  50044. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  50045. #endif
  50046. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50047. /*** Start of inlined file: juce_NativeMessageBox.h ***/
  50048. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50049. #define __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50050. class NativeMessageBox
  50051. {
  50052. public:
  50053. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  50054. If the callback parameter is null, the box is shown modally, and the method will
  50055. block until the user has clicked the button (or pressed the escape or return keys).
  50056. If the callback parameter is non-null, the box will be displayed and placed into a
  50057. modal state, but this method will return immediately, and the callback will be invoked
  50058. later when the user dismisses the box.
  50059. @param iconType the type of icon to show
  50060. @param title the headline to show at the top of the box
  50061. @param message a longer, more descriptive message to show underneath the title
  50062. @param associatedComponent if this is non-null, it specifies the component that the
  50063. alert window should be associated with. Depending on the look
  50064. and feel, this might be used for positioning of the alert window.
  50065. */
  50066. #if JUCE_MODAL_LOOPS_PERMITTED
  50067. static void JUCE_CALLTYPE showMessageBox (AlertWindow::AlertIconType iconType,
  50068. const String& title,
  50069. const String& message,
  50070. Component* associatedComponent = nullptr);
  50071. #endif
  50072. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  50073. If the callback parameter is null, the box is shown modally, and the method will
  50074. block until the user has clicked the button (or pressed the escape or return keys).
  50075. If the callback parameter is non-null, the box will be displayed and placed into a
  50076. modal state, but this method will return immediately, and the callback will be invoked
  50077. later when the user dismisses the box.
  50078. @param iconType the type of icon to show
  50079. @param title the headline to show at the top of the box
  50080. @param message a longer, more descriptive message to show underneath the title
  50081. @param associatedComponent if this is non-null, it specifies the component that the
  50082. alert window should be associated with. Depending on the look
  50083. and feel, this might be used for positioning of the alert window.
  50084. */
  50085. static void JUCE_CALLTYPE showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  50086. const String& title,
  50087. const String& message,
  50088. Component* associatedComponent = nullptr);
  50089. /** Shows a dialog box with two buttons.
  50090. Ideal for ok/cancel or yes/no choices. The return key can also be used
  50091. to trigger the first button, and the escape key for the second button.
  50092. If the callback parameter is null, the box is shown modally, and the method will
  50093. block until the user has clicked the button (or pressed the escape or return keys).
  50094. If the callback parameter is non-null, the box will be displayed and placed into a
  50095. modal state, but this method will return immediately, and the callback will be invoked
  50096. later when the user dismisses the box.
  50097. @param iconType the type of icon to show
  50098. @param title the headline to show at the top of the box
  50099. @param message a longer, more descriptive message to show underneath the title
  50100. @param associatedComponent if this is non-null, it specifies the component that the
  50101. alert window should be associated with. Depending on the look
  50102. and feel, this might be used for positioning of the alert window.
  50103. @param callback if this is non-null, the menu will be launched asynchronously,
  50104. returning immediately, and the callback will receive a call to its
  50105. modalStateFinished() when the box is dismissed, with its parameter
  50106. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  50107. will be owned and deleted by the system, so make sure that it works
  50108. safely and doesn't keep any references to objects that might be deleted
  50109. before it gets called.
  50110. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  50111. is not null, the method always returns false, and the user's choice is delivered
  50112. later by the callback.
  50113. */
  50114. static bool JUCE_CALLTYPE showOkCancelBox (AlertWindow::AlertIconType iconType,
  50115. const String& title,
  50116. const String& message,
  50117. #if JUCE_MODAL_LOOPS_PERMITTED
  50118. Component* associatedComponent = nullptr,
  50119. ModalComponentManager::Callback* callback = nullptr);
  50120. #else
  50121. Component* associatedComponent,
  50122. ModalComponentManager::Callback* callback);
  50123. #endif
  50124. /** Shows a dialog box with three buttons.
  50125. Ideal for yes/no/cancel boxes.
  50126. The escape key can be used to trigger the third button.
  50127. If the callback parameter is null, the box is shown modally, and the method will
  50128. block until the user has clicked the button (or pressed the escape or return keys).
  50129. If the callback parameter is non-null, the box will be displayed and placed into a
  50130. modal state, but this method will return immediately, and the callback will be invoked
  50131. later when the user dismisses the box.
  50132. @param iconType the type of icon to show
  50133. @param title the headline to show at the top of the box
  50134. @param message a longer, more descriptive message to show underneath the title
  50135. @param associatedComponent if this is non-null, it specifies the component that the
  50136. alert window should be associated with. Depending on the look
  50137. and feel, this might be used for positioning of the alert window.
  50138. @param callback if this is non-null, the menu will be launched asynchronously,
  50139. returning immediately, and the callback will receive a call to its
  50140. modalStateFinished() when the box is dismissed, with its parameter
  50141. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  50142. if it was cancelled, The callback object will be owned and deleted by the
  50143. system, so make sure that it works safely and doesn't keep any references
  50144. to objects that might be deleted before it gets called.
  50145. @returns If the callback parameter has been set, this returns 0. Otherwise, it returns one
  50146. of the following values:
  50147. - 0 if 'cancel' was pressed
  50148. - 1 if 'yes' was pressed
  50149. - 2 if 'no' was pressed
  50150. */
  50151. static int JUCE_CALLTYPE showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  50152. const String& title,
  50153. const String& message,
  50154. #if JUCE_MODAL_LOOPS_PERMITTED
  50155. Component* associatedComponent = nullptr,
  50156. ModalComponentManager::Callback* callback = nullptr);
  50157. #else
  50158. Component* associatedComponent,
  50159. ModalComponentManager::Callback* callback);
  50160. #endif
  50161. };
  50162. #endif // __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50163. /*** End of inlined file: juce_NativeMessageBox.h ***/
  50164. #endif
  50165. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  50166. #endif
  50167. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  50168. /*** Start of inlined file: juce_SplashScreen.h ***/
  50169. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  50170. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  50171. /** A component for showing a splash screen while your app starts up.
  50172. This will automatically position itself, and delete itself when the app has
  50173. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  50174. this).
  50175. To use it, just create one of these in your JUCEApplication::initialise() method,
  50176. call its show() method and let the object delete itself later.
  50177. E.g. @code
  50178. void MyApp::initialise (const String& commandLine)
  50179. {
  50180. SplashScreen* splash = new SplashScreen();
  50181. splash->show ("welcome to my app",
  50182. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  50183. 4000, false);
  50184. .. no need to delete the splash screen - it'll do that itself.
  50185. }
  50186. @endcode
  50187. */
  50188. class JUCE_API SplashScreen : public Component,
  50189. public Timer,
  50190. private DeletedAtShutdown
  50191. {
  50192. public:
  50193. /** Creates a SplashScreen object.
  50194. After creating one of these (or your subclass of it), call one of the show()
  50195. methods to display it.
  50196. */
  50197. SplashScreen();
  50198. /** Destructor. */
  50199. ~SplashScreen();
  50200. /** Creates a SplashScreen object that will display an image.
  50201. As soon as this is called, the SplashScreen will be displayed in the centre of the
  50202. screen. This method will also dispatch any pending messages to make sure that when
  50203. it returns, the splash screen has been completely drawn, and your initialisation
  50204. code can carry on.
  50205. @param title the name to give the component
  50206. @param backgroundImage an image to draw on the component. The component's size
  50207. will be set to the size of this image, and if the image is
  50208. semi-transparent, the component will be made semi-transparent
  50209. too. This image will be deleted (or released from the ImageCache
  50210. if that's how it was created) by the splash screen object when
  50211. it is itself deleted.
  50212. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  50213. should stay visible for. If the initialisation takes longer than
  50214. this time, the splash screen will wait for it to finish before
  50215. disappearing, but if initialisation is very quick, this lets
  50216. you make sure that people get a good look at your splash.
  50217. @param useDropShadow if true, the window will have a drop shadow
  50218. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  50219. the mouse (anywhere)
  50220. */
  50221. void show (const String& title,
  50222. const Image& backgroundImage,
  50223. int minimumTimeToDisplayFor,
  50224. bool useDropShadow,
  50225. bool removeOnMouseClick = true);
  50226. /** Creates a SplashScreen object with a specified size.
  50227. For a custom splash screen, you can use this method to display it at a certain size
  50228. and then override the paint() method yourself to do whatever's necessary.
  50229. As soon as this is called, the SplashScreen will be displayed in the centre of the
  50230. screen. This method will also dispatch any pending messages to make sure that when
  50231. it returns, the splash screen has been completely drawn, and your initialisation
  50232. code can carry on.
  50233. @param title the name to give the component
  50234. @param width the width to use
  50235. @param height the height to use
  50236. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  50237. should stay visible for. If the initialisation takes longer than
  50238. this time, the splash screen will wait for it to finish before
  50239. disappearing, but if initialisation is very quick, this lets
  50240. you make sure that people get a good look at your splash.
  50241. @param useDropShadow if true, the window will have a drop shadow
  50242. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  50243. the mouse (anywhere)
  50244. */
  50245. void show (const String& title,
  50246. int width,
  50247. int height,
  50248. int minimumTimeToDisplayFor,
  50249. bool useDropShadow,
  50250. bool removeOnMouseClick = true);
  50251. /** @internal */
  50252. void paint (Graphics& g);
  50253. /** @internal */
  50254. void timerCallback();
  50255. private:
  50256. Image backgroundImage;
  50257. Time earliestTimeToDelete;
  50258. int originalClickCounter;
  50259. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  50260. };
  50261. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  50262. /*** End of inlined file: juce_SplashScreen.h ***/
  50263. #endif
  50264. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50265. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  50266. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50267. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50268. /**
  50269. A thread that automatically pops up a modal dialog box with a progress bar
  50270. and cancel button while it's busy running.
  50271. These are handy for performing some sort of task while giving the user feedback
  50272. about how long there is to go, etc.
  50273. E.g. @code
  50274. class MyTask : public ThreadWithProgressWindow
  50275. {
  50276. public:
  50277. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  50278. {
  50279. }
  50280. ~MyTask()
  50281. {
  50282. }
  50283. void run()
  50284. {
  50285. for (int i = 0; i < thingsToDo; ++i)
  50286. {
  50287. // must check this as often as possible, because this is
  50288. // how we know if the user's pressed 'cancel'
  50289. if (threadShouldExit())
  50290. break;
  50291. // this will update the progress bar on the dialog box
  50292. setProgress (i / (double) thingsToDo);
  50293. // ... do the business here...
  50294. }
  50295. }
  50296. };
  50297. void doTheTask()
  50298. {
  50299. MyTask m;
  50300. if (m.runThread())
  50301. {
  50302. // thread finished normally..
  50303. }
  50304. else
  50305. {
  50306. // user pressed the cancel button..
  50307. }
  50308. }
  50309. @endcode
  50310. @see Thread, AlertWindow
  50311. */
  50312. class JUCE_API ThreadWithProgressWindow : public Thread,
  50313. private Timer
  50314. {
  50315. public:
  50316. /** Creates the thread.
  50317. Initially, the dialog box won't be visible, it'll only appear when the
  50318. runThread() method is called.
  50319. @param windowTitle the title to go at the top of the dialog box
  50320. @param hasProgressBar whether the dialog box should have a progress bar (see
  50321. setProgress() )
  50322. @param hasCancelButton whether the dialog box should have a cancel button
  50323. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  50324. the thread to stop before killing it forcibly (see
  50325. Thread::stopThread() )
  50326. @param cancelButtonText the text that should be shown in the cancel button
  50327. (if it has one)
  50328. */
  50329. ThreadWithProgressWindow (const String& windowTitle,
  50330. bool hasProgressBar,
  50331. bool hasCancelButton,
  50332. int timeOutMsWhenCancelling = 10000,
  50333. const String& cancelButtonText = "Cancel");
  50334. /** Destructor. */
  50335. ~ThreadWithProgressWindow();
  50336. /** Starts the thread and waits for it to finish.
  50337. This will start the thread, make the dialog box appear, and wait until either
  50338. the thread finishes normally, or until the cancel button is pressed.
  50339. Before returning, the dialog box will be hidden.
  50340. @param threadPriority the priority to use when starting the thread - see
  50341. Thread::startThread() for values
  50342. @returns true if the thread finished normally; false if the user pressed cancel
  50343. */
  50344. bool runThread (int threadPriority = 5);
  50345. /** The thread should call this periodically to update the position of the progress bar.
  50346. @param newProgress the progress, from 0.0 to 1.0
  50347. @see setStatusMessage
  50348. */
  50349. void setProgress (double newProgress);
  50350. /** The thread can call this to change the message that's displayed in the dialog box.
  50351. */
  50352. void setStatusMessage (const String& newStatusMessage);
  50353. /** Returns the AlertWindow that is being used.
  50354. */
  50355. AlertWindow* getAlertWindow() const noexcept { return alertWindow; }
  50356. private:
  50357. void timerCallback();
  50358. double progress;
  50359. ScopedPointer <AlertWindow> alertWindow;
  50360. String message;
  50361. CriticalSection messageLock;
  50362. const int timeOutMsWhenCancelling;
  50363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  50364. };
  50365. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50366. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  50367. #endif
  50368. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  50369. #endif
  50370. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  50371. #endif
  50372. #ifndef __JUCE_COLOUR_JUCEHEADER__
  50373. #endif
  50374. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  50375. #endif
  50376. #ifndef __JUCE_COLOURS_JUCEHEADER__
  50377. #endif
  50378. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  50379. #endif
  50380. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  50381. /*** Start of inlined file: juce_EdgeTable.h ***/
  50382. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  50383. #define __JUCE_EDGETABLE_JUCEHEADER__
  50384. class Path;
  50385. class Image;
  50386. /**
  50387. A table of horizontal scan-line segments - used for rasterising Paths.
  50388. @see Path, Graphics
  50389. */
  50390. class JUCE_API EdgeTable
  50391. {
  50392. public:
  50393. /** Creates an edge table containing a path.
  50394. A table is created with a fixed vertical range, and only sections of the path
  50395. which lie within this range will be added to the table.
  50396. @param clipLimits only the region of the path that lies within this area will be added
  50397. @param pathToAdd the path to add to the table
  50398. @param transform a transform to apply to the path being added
  50399. */
  50400. EdgeTable (const Rectangle<int>& clipLimits,
  50401. const Path& pathToAdd,
  50402. const AffineTransform& transform);
  50403. /** Creates an edge table containing a rectangle. */
  50404. EdgeTable (const Rectangle<int>& rectangleToAdd);
  50405. /** Creates an edge table containing a rectangle list. */
  50406. EdgeTable (const RectangleList& rectanglesToAdd);
  50407. /** Creates an edge table containing a rectangle. */
  50408. EdgeTable (const Rectangle<float>& rectangleToAdd);
  50409. /** Creates a copy of another edge table. */
  50410. EdgeTable (const EdgeTable& other);
  50411. /** Copies from another edge table. */
  50412. EdgeTable& operator= (const EdgeTable& other);
  50413. /** Destructor. */
  50414. ~EdgeTable();
  50415. void clipToRectangle (const Rectangle<int>& r);
  50416. void excludeRectangle (const Rectangle<int>& r);
  50417. void clipToEdgeTable (const EdgeTable& other);
  50418. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  50419. bool isEmpty() noexcept;
  50420. const Rectangle<int>& getMaximumBounds() const noexcept { return bounds; }
  50421. void translate (float dx, int dy) noexcept;
  50422. /** Reduces the amount of space the table has allocated.
  50423. This will shrink the table down to use as little memory as possible - useful for
  50424. read-only tables that get stored and re-used for rendering.
  50425. */
  50426. void optimiseTable();
  50427. /** Iterates the lines in the table, for rendering.
  50428. This function will iterate each line in the table, and call a user-defined class
  50429. to render each pixel or continuous line of pixels that the table contains.
  50430. @param iterationCallback this templated class must contain the following methods:
  50431. @code
  50432. inline void setEdgeTableYPos (int y);
  50433. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  50434. inline void handleEdgeTablePixelFull (int x) const;
  50435. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  50436. inline void handleEdgeTableLineFull (int x, int width) const;
  50437. @endcode
  50438. (these don't necessarily have to be 'const', but it might help it go faster)
  50439. */
  50440. template <class EdgeTableIterationCallback>
  50441. void iterate (EdgeTableIterationCallback& iterationCallback) const noexcept
  50442. {
  50443. const int* lineStart = table;
  50444. for (int y = 0; y < bounds.getHeight(); ++y)
  50445. {
  50446. const int* line = lineStart;
  50447. lineStart += lineStrideElements;
  50448. int numPoints = line[0];
  50449. if (--numPoints > 0)
  50450. {
  50451. int x = *++line;
  50452. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  50453. int levelAccumulator = 0;
  50454. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  50455. while (--numPoints >= 0)
  50456. {
  50457. const int level = *++line;
  50458. jassert (isPositiveAndBelow (level, (int) 256));
  50459. const int endX = *++line;
  50460. jassert (endX >= x);
  50461. const int endOfRun = (endX >> 8);
  50462. if (endOfRun == (x >> 8))
  50463. {
  50464. // small segment within the same pixel, so just save it for the next
  50465. // time round..
  50466. levelAccumulator += (endX - x) * level;
  50467. }
  50468. else
  50469. {
  50470. // plot the fist pixel of this segment, including any accumulated
  50471. // levels from smaller segments that haven't been drawn yet
  50472. levelAccumulator += (0x100 - (x & 0xff)) * level;
  50473. levelAccumulator >>= 8;
  50474. x >>= 8;
  50475. if (levelAccumulator > 0)
  50476. {
  50477. if (levelAccumulator >= 255)
  50478. iterationCallback.handleEdgeTablePixelFull (x);
  50479. else
  50480. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  50481. }
  50482. // if there's a run of similar pixels, do it all in one go..
  50483. if (level > 0)
  50484. {
  50485. jassert (endOfRun <= bounds.getRight());
  50486. const int numPix = endOfRun - ++x;
  50487. if (numPix > 0)
  50488. iterationCallback.handleEdgeTableLine (x, numPix, level);
  50489. }
  50490. // save the bit at the end to be drawn next time round the loop.
  50491. levelAccumulator = (endX & 0xff) * level;
  50492. }
  50493. x = endX;
  50494. }
  50495. levelAccumulator >>= 8;
  50496. if (levelAccumulator > 0)
  50497. {
  50498. x >>= 8;
  50499. jassert (x >= bounds.getX() && x < bounds.getRight());
  50500. if (levelAccumulator >= 255)
  50501. iterationCallback.handleEdgeTablePixelFull (x);
  50502. else
  50503. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  50504. }
  50505. }
  50506. }
  50507. }
  50508. private:
  50509. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  50510. HeapBlock<int> table;
  50511. Rectangle<int> bounds;
  50512. int maxEdgesPerLine, lineStrideElements;
  50513. bool needToCheckEmptinesss;
  50514. void addEdgePoint (int x, int y, int winding);
  50515. void remapTableForNumEdges (int newNumEdgesPerLine);
  50516. void intersectWithEdgeTableLine (int y, const int* otherLine);
  50517. void clipEdgeTableLineToRange (int* line, int x1, int x2) noexcept;
  50518. void sanitiseLevels (bool useNonZeroWinding) noexcept;
  50519. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) noexcept;
  50520. JUCE_LEAK_DETECTOR (EdgeTable);
  50521. };
  50522. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  50523. /*** End of inlined file: juce_EdgeTable.h ***/
  50524. #endif
  50525. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  50526. /*** Start of inlined file: juce_FillType.h ***/
  50527. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  50528. #define __JUCE_FILLTYPE_JUCEHEADER__
  50529. /**
  50530. Represents a colour or fill pattern to use for rendering paths.
  50531. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  50532. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  50533. @see Graphics::setFillType, DrawablePath::setFill
  50534. */
  50535. class JUCE_API FillType
  50536. {
  50537. public:
  50538. /** Creates a default fill type, of solid black. */
  50539. FillType() noexcept;
  50540. /** Creates a fill type of a solid colour.
  50541. @see setColour
  50542. */
  50543. FillType (const Colour& colour) noexcept;
  50544. /** Creates a gradient fill type.
  50545. @see setGradient
  50546. */
  50547. FillType (const ColourGradient& gradient);
  50548. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  50549. and rotation of the pattern.
  50550. @see setTiledImage
  50551. */
  50552. FillType (const Image& image, const AffineTransform& transform) noexcept;
  50553. /** Creates a copy of another FillType. */
  50554. FillType (const FillType& other);
  50555. /** Makes a copy of another FillType. */
  50556. FillType& operator= (const FillType& other);
  50557. /** Destructor. */
  50558. ~FillType() noexcept;
  50559. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  50560. bool isColour() const noexcept { return gradient == nullptr && image.isNull(); }
  50561. /** Returns true if this is a gradient fill. */
  50562. bool isGradient() const noexcept { return gradient != nullptr; }
  50563. /** Returns true if this is a tiled image pattern fill. */
  50564. bool isTiledImage() const noexcept { return image.isValid(); }
  50565. /** Turns this object into a solid colour fill.
  50566. If the object was an image or gradient, those fields will no longer be valid. */
  50567. void setColour (const Colour& newColour) noexcept;
  50568. /** Turns this object into a gradient fill. */
  50569. void setGradient (const ColourGradient& newGradient);
  50570. /** Turns this object into a tiled image fill type. The transform allows you to set
  50571. the scaling, offset and rotation of the pattern.
  50572. */
  50573. void setTiledImage (const Image& image, const AffineTransform& transform) noexcept;
  50574. /** Changes the opacity that should be used.
  50575. If the fill is a solid colour, this just changes the opacity of that colour. For
  50576. gradients and image tiles, it changes the opacity that will be used for them.
  50577. */
  50578. void setOpacity (float newOpacity) noexcept;
  50579. /** Returns the current opacity to be applied to the colour, gradient, or image.
  50580. @see setOpacity
  50581. */
  50582. float getOpacity() const noexcept { return colour.getFloatAlpha(); }
  50583. /** Returns true if this fill type is completely transparent. */
  50584. bool isInvisible() const noexcept;
  50585. /** The solid colour being used.
  50586. If the fill type is not a solid colour, the alpha channel of this colour indicates
  50587. the opacity that should be used for the fill, and the RGB channels are ignored.
  50588. */
  50589. Colour colour;
  50590. /** Returns the gradient that should be used for filling.
  50591. This will be zero if the object is some other type of fill.
  50592. If a gradient is active, the overall opacity with which it should be applied
  50593. is indicated by the alpha channel of the colour variable.
  50594. */
  50595. ScopedPointer <ColourGradient> gradient;
  50596. /** The image that should be used for tiling.
  50597. If an image fill is active, the overall opacity with which it should be applied
  50598. is indicated by the alpha channel of the colour variable.
  50599. */
  50600. Image image;
  50601. /** The transform that should be applied to the image or gradient that's being drawn. */
  50602. AffineTransform transform;
  50603. bool operator== (const FillType& other) const;
  50604. bool operator!= (const FillType& other) const;
  50605. private:
  50606. JUCE_LEAK_DETECTOR (FillType);
  50607. };
  50608. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  50609. /*** End of inlined file: juce_FillType.h ***/
  50610. #endif
  50611. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  50612. #endif
  50613. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  50614. #endif
  50615. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50616. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  50617. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50618. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50619. /**
  50620. Interface class for graphics context objects, used internally by the Graphics class.
  50621. Users are not supposed to create instances of this class directly - do your drawing
  50622. via the Graphics object instead.
  50623. It's a base class for different types of graphics context, that may perform software-based
  50624. or OS-accelerated rendering.
  50625. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  50626. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  50627. context.
  50628. */
  50629. class JUCE_API LowLevelGraphicsContext
  50630. {
  50631. protected:
  50632. LowLevelGraphicsContext();
  50633. public:
  50634. virtual ~LowLevelGraphicsContext();
  50635. /** Returns true if this device is vector-based, e.g. a printer. */
  50636. virtual bool isVectorDevice() const = 0;
  50637. /** Moves the origin to a new position.
  50638. The co-ords are relative to the current origin, and indicate the new position
  50639. of (0, 0).
  50640. */
  50641. virtual void setOrigin (int x, int y) = 0;
  50642. virtual void addTransform (const AffineTransform& transform) = 0;
  50643. virtual float getScaleFactor() = 0;
  50644. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  50645. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  50646. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  50647. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  50648. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  50649. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  50650. virtual const Rectangle<int> getClipBounds() const = 0;
  50651. virtual bool isClipEmpty() const = 0;
  50652. virtual void saveState() = 0;
  50653. virtual void restoreState() = 0;
  50654. virtual void beginTransparencyLayer (float opacity) = 0;
  50655. virtual void endTransparencyLayer() = 0;
  50656. virtual void setFill (const FillType& fillType) = 0;
  50657. virtual void setOpacity (float newOpacity) = 0;
  50658. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  50659. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  50660. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  50661. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  50662. virtual void drawLine (const Line <float>& line) = 0;
  50663. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  50664. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  50665. virtual void setFont (const Font& newFont) = 0;
  50666. virtual Font getFont() = 0;
  50667. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  50668. };
  50669. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50670. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  50671. #endif
  50672. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50673. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50674. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50675. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50676. /**
  50677. An implementation of LowLevelGraphicsContext that turns the drawing operations
  50678. into a PostScript document.
  50679. */
  50680. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  50681. {
  50682. public:
  50683. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  50684. const String& documentTitle,
  50685. int totalWidth,
  50686. int totalHeight);
  50687. ~LowLevelGraphicsPostScriptRenderer();
  50688. bool isVectorDevice() const;
  50689. void setOrigin (int x, int y);
  50690. void addTransform (const AffineTransform& transform);
  50691. float getScaleFactor();
  50692. bool clipToRectangle (const Rectangle<int>& r);
  50693. bool clipToRectangleList (const RectangleList& clipRegion);
  50694. void excludeClipRectangle (const Rectangle<int>& r);
  50695. void clipToPath (const Path& path, const AffineTransform& transform);
  50696. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50697. void saveState();
  50698. void restoreState();
  50699. void beginTransparencyLayer (float opacity);
  50700. void endTransparencyLayer();
  50701. bool clipRegionIntersects (const Rectangle<int>& r);
  50702. const Rectangle<int> getClipBounds() const;
  50703. bool isClipEmpty() const;
  50704. void setFill (const FillType& fillType);
  50705. void setOpacity (float opacity);
  50706. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50707. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50708. void fillPath (const Path& path, const AffineTransform& transform);
  50709. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50710. void drawLine (const Line <float>& line);
  50711. void drawVerticalLine (int x, float top, float bottom);
  50712. void drawHorizontalLine (int x, float top, float bottom);
  50713. Font getFont();
  50714. void setFont (const Font& newFont);
  50715. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50716. protected:
  50717. OutputStream& out;
  50718. int totalWidth, totalHeight;
  50719. bool needToClip;
  50720. Colour lastColour;
  50721. struct SavedState
  50722. {
  50723. SavedState();
  50724. ~SavedState();
  50725. RectangleList clip;
  50726. int xOffset, yOffset;
  50727. FillType fillType;
  50728. Font font;
  50729. private:
  50730. SavedState& operator= (const SavedState&);
  50731. };
  50732. OwnedArray <SavedState> stateStack;
  50733. void writeClip();
  50734. void writeColour (const Colour& colour);
  50735. void writePath (const Path& path) const;
  50736. void writeXY (float x, float y) const;
  50737. void writeTransform (const AffineTransform& trans) const;
  50738. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  50739. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  50740. };
  50741. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50742. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50743. #endif
  50744. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50745. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50746. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50747. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50748. /**
  50749. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  50750. its rendering in memory.
  50751. User code is not supposed to create instances of this class directly - do all your
  50752. rendering via the Graphics class instead.
  50753. */
  50754. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  50755. {
  50756. public:
  50757. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  50758. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  50759. ~LowLevelGraphicsSoftwareRenderer();
  50760. bool isVectorDevice() const;
  50761. void setOrigin (int x, int y);
  50762. void addTransform (const AffineTransform& transform);
  50763. float getScaleFactor();
  50764. bool clipToRectangle (const Rectangle<int>& r);
  50765. bool clipToRectangleList (const RectangleList& clipRegion);
  50766. void excludeClipRectangle (const Rectangle<int>& r);
  50767. void clipToPath (const Path& path, const AffineTransform& transform);
  50768. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50769. bool clipRegionIntersects (const Rectangle<int>& r);
  50770. const Rectangle<int> getClipBounds() const;
  50771. bool isClipEmpty() const;
  50772. void saveState();
  50773. void restoreState();
  50774. void beginTransparencyLayer (float opacity);
  50775. void endTransparencyLayer();
  50776. void setFill (const FillType& fillType);
  50777. void setOpacity (float opacity);
  50778. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50779. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50780. void fillPath (const Path& path, const AffineTransform& transform);
  50781. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50782. void drawLine (const Line <float>& line);
  50783. void drawVerticalLine (int x, float top, float bottom);
  50784. void drawHorizontalLine (int x, float top, float bottom);
  50785. void setFont (const Font& newFont);
  50786. Font getFont();
  50787. void drawGlyph (int glyphNumber, float x, float y);
  50788. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50789. protected:
  50790. Image image;
  50791. class GlyphCache;
  50792. class CachedGlyph;
  50793. class SavedState;
  50794. friend class ScopedPointer <SavedState>;
  50795. friend class OwnedArray <SavedState>;
  50796. friend class OwnedArray <CachedGlyph>;
  50797. ScopedPointer <SavedState> currentState;
  50798. OwnedArray <SavedState> stateStack;
  50799. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  50800. };
  50801. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50802. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50803. #endif
  50804. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  50805. #endif
  50806. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  50807. #endif
  50808. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50809. /*** Start of inlined file: juce_DrawableComposite.h ***/
  50810. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50811. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50812. /**
  50813. A drawable object which acts as a container for a set of other Drawables.
  50814. @see Drawable
  50815. */
  50816. class JUCE_API DrawableComposite : public Drawable
  50817. {
  50818. public:
  50819. /** Creates a composite Drawable. */
  50820. DrawableComposite();
  50821. /** Creates a copy of a DrawableComposite. */
  50822. DrawableComposite (const DrawableComposite& other);
  50823. /** Destructor. */
  50824. ~DrawableComposite();
  50825. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  50826. @see setContentArea
  50827. */
  50828. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  50829. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  50830. @see setBoundingBox
  50831. */
  50832. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50833. /** Changes the bounding box transform to match the content area, so that any sub-items will
  50834. be drawn at their untransformed positions.
  50835. */
  50836. void resetBoundingBoxToContentArea();
  50837. /** Returns the main content rectangle.
  50838. The content area is actually defined by the markers named "left", "right", "top" and
  50839. "bottom", but this method is a shortcut that returns them all at once.
  50840. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  50841. */
  50842. const RelativeRectangle getContentArea() const;
  50843. /** Changes the main content area.
  50844. The content area is actually defined by the markers named "left", "right", "top" and
  50845. "bottom", but this method is a shortcut that sets them all at once.
  50846. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  50847. */
  50848. void setContentArea (const RelativeRectangle& newArea);
  50849. /** Resets the content area and the bounding transform to fit around the area occupied
  50850. by the child components (ignoring any markers).
  50851. */
  50852. void resetContentAreaAndBoundingBoxToFitChildren();
  50853. /** The name of the marker that defines the left edge of the content area. */
  50854. static const char* const contentLeftMarkerName;
  50855. /** The name of the marker that defines the right edge of the content area. */
  50856. static const char* const contentRightMarkerName;
  50857. /** The name of the marker that defines the top edge of the content area. */
  50858. static const char* const contentTopMarkerName;
  50859. /** The name of the marker that defines the bottom edge of the content area. */
  50860. static const char* const contentBottomMarkerName;
  50861. /** @internal */
  50862. Drawable* createCopy() const;
  50863. /** @internal */
  50864. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50865. /** @internal */
  50866. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50867. /** @internal */
  50868. static const Identifier valueTreeType;
  50869. /** @internal */
  50870. const Rectangle<float> getDrawableBounds() const;
  50871. /** @internal */
  50872. void childBoundsChanged (Component*);
  50873. /** @internal */
  50874. void childrenChanged();
  50875. /** @internal */
  50876. void parentHierarchyChanged();
  50877. /** @internal */
  50878. MarkerList* getMarkers (bool xAxis);
  50879. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  50880. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50881. {
  50882. public:
  50883. ValueTreeWrapper (const ValueTree& state);
  50884. ValueTree getChildList() const;
  50885. ValueTree getChildListCreating (UndoManager* undoManager);
  50886. const RelativeParallelogram getBoundingBox() const;
  50887. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50888. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  50889. const RelativeRectangle getContentArea() const;
  50890. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  50891. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  50892. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  50893. static const Identifier topLeft, topRight, bottomLeft;
  50894. private:
  50895. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  50896. };
  50897. private:
  50898. RelativeParallelogram bounds;
  50899. MarkerList markersX, markersY;
  50900. bool updateBoundsReentrant;
  50901. friend class Drawable::Positioner<DrawableComposite>;
  50902. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50903. void recalculateCoordinates (Expression::Scope*);
  50904. void updateBoundsToFitChildren();
  50905. DrawableComposite& operator= (const DrawableComposite&);
  50906. JUCE_LEAK_DETECTOR (DrawableComposite);
  50907. };
  50908. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50909. /*** End of inlined file: juce_DrawableComposite.h ***/
  50910. #endif
  50911. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50912. /*** Start of inlined file: juce_DrawableImage.h ***/
  50913. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50914. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50915. /**
  50916. A drawable object which is a bitmap image.
  50917. @see Drawable
  50918. */
  50919. class JUCE_API DrawableImage : public Drawable
  50920. {
  50921. public:
  50922. DrawableImage();
  50923. DrawableImage (const DrawableImage& other);
  50924. /** Destructor. */
  50925. ~DrawableImage();
  50926. /** Sets the image that this drawable will render. */
  50927. void setImage (const Image& imageToUse);
  50928. /** Returns the current image. */
  50929. const Image getImage() const { return image; }
  50930. /** Sets the opacity to use when drawing the image. */
  50931. void setOpacity (float newOpacity);
  50932. /** Returns the image's opacity. */
  50933. float getOpacity() const noexcept { return opacity; }
  50934. /** Sets a colour to draw over the image's alpha channel.
  50935. By default this is transparent so isn't drawn, but if you set a non-transparent
  50936. colour here, then it will be overlaid on the image, using the image's alpha
  50937. channel as a mask.
  50938. This is handy for doing things like darkening or lightening an image by overlaying
  50939. it with semi-transparent black or white.
  50940. */
  50941. void setOverlayColour (const Colour& newOverlayColour);
  50942. /** Returns the overlay colour. */
  50943. const Colour& getOverlayColour() const noexcept { return overlayColour; }
  50944. /** Sets the bounding box within which the image should be displayed. */
  50945. void setBoundingBox (const RelativeParallelogram& newBounds);
  50946. /** Returns the position to which the image's top-left corner should be remapped in the target
  50947. coordinate space when rendering this object.
  50948. @see setTransform
  50949. */
  50950. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50951. /** @internal */
  50952. void paint (Graphics& g);
  50953. /** @internal */
  50954. bool hitTest (int x, int y);
  50955. /** @internal */
  50956. Drawable* createCopy() const;
  50957. /** @internal */
  50958. const Rectangle<float> getDrawableBounds() const;
  50959. /** @internal */
  50960. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50961. /** @internal */
  50962. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50963. /** @internal */
  50964. static const Identifier valueTreeType;
  50965. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  50966. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50967. {
  50968. public:
  50969. ValueTreeWrapper (const ValueTree& state);
  50970. const var getImageIdentifier() const;
  50971. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  50972. Value getImageIdentifierValue (UndoManager* undoManager);
  50973. float getOpacity() const;
  50974. void setOpacity (float newOpacity, UndoManager* undoManager);
  50975. Value getOpacityValue (UndoManager* undoManager);
  50976. const Colour getOverlayColour() const;
  50977. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  50978. Value getOverlayColourValue (UndoManager* undoManager);
  50979. const RelativeParallelogram getBoundingBox() const;
  50980. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50981. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  50982. };
  50983. private:
  50984. Image image;
  50985. float opacity;
  50986. Colour overlayColour;
  50987. RelativeParallelogram bounds;
  50988. friend class Drawable::Positioner<DrawableImage>;
  50989. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50990. void recalculateCoordinates (Expression::Scope*);
  50991. DrawableImage& operator= (const DrawableImage&);
  50992. JUCE_LEAK_DETECTOR (DrawableImage);
  50993. };
  50994. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50995. /*** End of inlined file: juce_DrawableImage.h ***/
  50996. #endif
  50997. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50998. /*** Start of inlined file: juce_DrawablePath.h ***/
  50999. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  51000. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  51001. /*** Start of inlined file: juce_DrawableShape.h ***/
  51002. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51003. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51004. /**
  51005. A base class implementing common functionality for Drawable classes which
  51006. consist of some kind of filled and stroked outline.
  51007. @see DrawablePath, DrawableRectangle
  51008. */
  51009. class JUCE_API DrawableShape : public Drawable
  51010. {
  51011. protected:
  51012. DrawableShape();
  51013. DrawableShape (const DrawableShape&);
  51014. public:
  51015. /** Destructor. */
  51016. ~DrawableShape();
  51017. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  51018. */
  51019. class RelativeFillType
  51020. {
  51021. public:
  51022. RelativeFillType();
  51023. RelativeFillType (const FillType& fill);
  51024. RelativeFillType (const RelativeFillType&);
  51025. RelativeFillType& operator= (const RelativeFillType&);
  51026. bool operator== (const RelativeFillType&) const;
  51027. bool operator!= (const RelativeFillType&) const;
  51028. bool isDynamic() const;
  51029. bool recalculateCoords (Expression::Scope* scope);
  51030. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  51031. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  51032. FillType fill;
  51033. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  51034. };
  51035. /** Sets a fill type for the path.
  51036. This colour is used to fill the path - if you don't want the path to be
  51037. filled (e.g. if you're just drawing an outline), set this to a transparent
  51038. colour.
  51039. @see setPath, setStrokeFill
  51040. */
  51041. void setFill (const FillType& newFill);
  51042. /** Sets a fill type for the path.
  51043. This colour is used to fill the path - if you don't want the path to be
  51044. filled (e.g. if you're just drawing an outline), set this to a transparent
  51045. colour.
  51046. @see setPath, setStrokeFill
  51047. */
  51048. void setFill (const RelativeFillType& newFill);
  51049. /** Returns the current fill type.
  51050. @see setFill
  51051. */
  51052. const RelativeFillType& getFill() const noexcept { return mainFill; }
  51053. /** Sets the fill type with which the outline will be drawn.
  51054. @see setFill
  51055. */
  51056. void setStrokeFill (const FillType& newStrokeFill);
  51057. /** Sets the fill type with which the outline will be drawn.
  51058. @see setFill
  51059. */
  51060. void setStrokeFill (const RelativeFillType& newStrokeFill);
  51061. /** Returns the current stroke fill.
  51062. @see setStrokeFill
  51063. */
  51064. const RelativeFillType& getStrokeFill() const noexcept { return strokeFill; }
  51065. /** Changes the properties of the outline that will be drawn around the path.
  51066. If the stroke has 0 thickness, no stroke will be drawn.
  51067. @see setStrokeThickness, setStrokeColour
  51068. */
  51069. void setStrokeType (const PathStrokeType& newStrokeType);
  51070. /** Changes the stroke thickness.
  51071. This is a shortcut for calling setStrokeType.
  51072. */
  51073. void setStrokeThickness (float newThickness);
  51074. /** Returns the current outline style. */
  51075. const PathStrokeType& getStrokeType() const noexcept { return strokeType; }
  51076. /** @internal */
  51077. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  51078. {
  51079. public:
  51080. FillAndStrokeState (const ValueTree& state);
  51081. ValueTree getFillState (const Identifier& fillOrStrokeType);
  51082. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  51083. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  51084. ComponentBuilder::ImageProvider*, UndoManager*);
  51085. const PathStrokeType getStrokeType() const;
  51086. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  51087. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  51088. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  51089. };
  51090. /** @internal */
  51091. const Rectangle<float> getDrawableBounds() const;
  51092. /** @internal */
  51093. void paint (Graphics& g);
  51094. /** @internal */
  51095. bool hitTest (int x, int y);
  51096. protected:
  51097. /** Called when the cached path should be updated. */
  51098. void pathChanged();
  51099. /** Called when the cached stroke should be updated. */
  51100. void strokeChanged();
  51101. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  51102. bool isStrokeVisible() const noexcept;
  51103. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  51104. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  51105. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  51106. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  51107. PathStrokeType strokeType;
  51108. Path path, strokePath;
  51109. private:
  51110. class RelativePositioner;
  51111. RelativeFillType mainFill, strokeFill;
  51112. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  51113. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  51114. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  51115. DrawableShape& operator= (const DrawableShape&);
  51116. };
  51117. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51118. /*** End of inlined file: juce_DrawableShape.h ***/
  51119. /**
  51120. A drawable object which renders a filled or outlined shape.
  51121. For details on how to change the fill and stroke, see the DrawableShape class.
  51122. @see Drawable, DrawableShape
  51123. */
  51124. class JUCE_API DrawablePath : public DrawableShape
  51125. {
  51126. public:
  51127. /** Creates a DrawablePath. */
  51128. DrawablePath();
  51129. DrawablePath (const DrawablePath& other);
  51130. /** Destructor. */
  51131. ~DrawablePath();
  51132. /** Changes the path that will be drawn.
  51133. @see setFillColour, setStrokeType
  51134. */
  51135. void setPath (const Path& newPath);
  51136. /** Sets the path using a RelativePointPath.
  51137. Calling this will set up a Component::Positioner to automatically update the path
  51138. if any of the points in the source path are dynamic.
  51139. */
  51140. void setPath (const RelativePointPath& newPath);
  51141. /** Returns the current path. */
  51142. const Path& getPath() const;
  51143. /** Returns the current path for the outline. */
  51144. const Path& getStrokePath() const;
  51145. /** @internal */
  51146. Drawable* createCopy() const;
  51147. /** @internal */
  51148. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51149. /** @internal */
  51150. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51151. /** @internal */
  51152. static const Identifier valueTreeType;
  51153. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  51154. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  51155. {
  51156. public:
  51157. ValueTreeWrapper (const ValueTree& state);
  51158. bool usesNonZeroWinding() const;
  51159. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  51160. class Element
  51161. {
  51162. public:
  51163. explicit Element (const ValueTree& state);
  51164. ~Element();
  51165. const Identifier getType() const noexcept { return state.getType(); }
  51166. int getNumControlPoints() const noexcept;
  51167. const RelativePoint getControlPoint (int index) const;
  51168. Value getControlPointValue (int index, UndoManager*) const;
  51169. const RelativePoint getStartPoint() const;
  51170. const RelativePoint getEndPoint() const;
  51171. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  51172. float getLength (Expression::Scope*) const;
  51173. ValueTreeWrapper getParent() const;
  51174. Element getPreviousElement() const;
  51175. const String getModeOfEndPoint() const;
  51176. void setModeOfEndPoint (const String& newMode, UndoManager*);
  51177. void convertToLine (UndoManager*);
  51178. void convertToCubic (Expression::Scope*, UndoManager*);
  51179. void convertToPathBreak (UndoManager* undoManager);
  51180. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  51181. void removePoint (UndoManager* undoManager);
  51182. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  51183. static const Identifier mode, startSubPathElement, closeSubPathElement,
  51184. lineToElement, quadraticToElement, cubicToElement;
  51185. static const char* cornerMode;
  51186. static const char* roundedMode;
  51187. static const char* symmetricMode;
  51188. ValueTree state;
  51189. };
  51190. ValueTree getPathState();
  51191. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  51192. void writeTo (RelativePointPath& path) const;
  51193. static const Identifier nonZeroWinding, point1, point2, point3;
  51194. };
  51195. private:
  51196. ScopedPointer<RelativePointPath> relativePath;
  51197. class RelativePositioner;
  51198. friend class RelativePositioner;
  51199. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  51200. DrawablePath& operator= (const DrawablePath&);
  51201. JUCE_LEAK_DETECTOR (DrawablePath);
  51202. };
  51203. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  51204. /*** End of inlined file: juce_DrawablePath.h ***/
  51205. #endif
  51206. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51207. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  51208. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51209. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51210. /**
  51211. A Drawable object which draws a rectangle.
  51212. For details on how to change the fill and stroke, see the DrawableShape class.
  51213. @see Drawable, DrawableShape
  51214. */
  51215. class JUCE_API DrawableRectangle : public DrawableShape
  51216. {
  51217. public:
  51218. DrawableRectangle();
  51219. DrawableRectangle (const DrawableRectangle& other);
  51220. /** Destructor. */
  51221. ~DrawableRectangle();
  51222. /** Sets the rectangle's bounds. */
  51223. void setRectangle (const RelativeParallelogram& newBounds);
  51224. /** Returns the rectangle's bounds. */
  51225. const RelativeParallelogram& getRectangle() const noexcept { return bounds; }
  51226. /** Returns the corner size to be used. */
  51227. const RelativePoint getCornerSize() const { return cornerSize; }
  51228. /** Sets a new corner size for the rectangle */
  51229. void setCornerSize (const RelativePoint& newSize);
  51230. /** @internal */
  51231. Drawable* createCopy() const;
  51232. /** @internal */
  51233. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51234. /** @internal */
  51235. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51236. /** @internal */
  51237. static const Identifier valueTreeType;
  51238. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  51239. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  51240. {
  51241. public:
  51242. ValueTreeWrapper (const ValueTree& state);
  51243. const RelativeParallelogram getRectangle() const;
  51244. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  51245. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  51246. const RelativePoint getCornerSize() const;
  51247. Value getCornerSizeValue (UndoManager*) const;
  51248. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  51249. };
  51250. private:
  51251. friend class Drawable::Positioner<DrawableRectangle>;
  51252. RelativeParallelogram bounds;
  51253. RelativePoint cornerSize;
  51254. void rebuildPath();
  51255. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51256. void recalculateCoordinates (Expression::Scope*);
  51257. DrawableRectangle& operator= (const DrawableRectangle&);
  51258. JUCE_LEAK_DETECTOR (DrawableRectangle);
  51259. };
  51260. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51261. /*** End of inlined file: juce_DrawableRectangle.h ***/
  51262. #endif
  51263. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51264. #endif
  51265. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  51266. /*** Start of inlined file: juce_DrawableText.h ***/
  51267. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  51268. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  51269. /**
  51270. A drawable object which renders a line of text.
  51271. @see Drawable
  51272. */
  51273. class JUCE_API DrawableText : public Drawable
  51274. {
  51275. public:
  51276. /** Creates a DrawableText object. */
  51277. DrawableText();
  51278. DrawableText (const DrawableText& other);
  51279. /** Destructor. */
  51280. ~DrawableText();
  51281. /** Sets the text to display.*/
  51282. void setText (const String& newText);
  51283. /** Sets the colour of the text. */
  51284. void setColour (const Colour& newColour);
  51285. /** Returns the current text colour. */
  51286. const Colour& getColour() const noexcept { return colour; }
  51287. /** Sets the font to use.
  51288. Note that the font height and horizontal scale are actually based upon the position
  51289. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  51290. the height and scale control point will be moved to match the dimensions of the font supplied;
  51291. if it is false, then the new font's height and scale are ignored.
  51292. */
  51293. void setFont (const Font& newFont, bool applySizeAndScale);
  51294. /** Changes the justification of the text within the bounding box. */
  51295. void setJustification (const Justification& newJustification);
  51296. /** Returns the parallelogram that defines the text bounding box. */
  51297. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51298. /** Sets the bounding box that contains the text. */
  51299. void setBoundingBox (const RelativeParallelogram& newBounds);
  51300. /** Returns the point within the bounds that defines the font's size and scale. */
  51301. const RelativePoint& getFontSizeControlPoint() const noexcept { return fontSizeControlPoint; }
  51302. /** Sets the control point that defines the font's height and horizontal scale.
  51303. This position is a point within the bounding box parallelogram, whose Y position (relative
  51304. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  51305. and its X defines the font's horizontal scale.
  51306. */
  51307. void setFontSizeControlPoint (const RelativePoint& newPoint);
  51308. /** @internal */
  51309. void paint (Graphics& g);
  51310. /** @internal */
  51311. Drawable* createCopy() const;
  51312. /** @internal */
  51313. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51314. /** @internal */
  51315. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51316. /** @internal */
  51317. static const Identifier valueTreeType;
  51318. /** @internal */
  51319. const Rectangle<float> getDrawableBounds() const;
  51320. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  51321. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51322. {
  51323. public:
  51324. ValueTreeWrapper (const ValueTree& state);
  51325. String getText() const;
  51326. void setText (const String& newText, UndoManager* undoManager);
  51327. Value getTextValue (UndoManager* undoManager);
  51328. Colour getColour() const;
  51329. void setColour (const Colour& newColour, UndoManager* undoManager);
  51330. Justification getJustification() const;
  51331. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  51332. Font getFont() const;
  51333. void setFont (const Font& newFont, UndoManager* undoManager);
  51334. Value getFontValue (UndoManager* undoManager);
  51335. RelativeParallelogram getBoundingBox() const;
  51336. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51337. RelativePoint getFontSizeControlPoint() const;
  51338. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  51339. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  51340. };
  51341. private:
  51342. RelativeParallelogram bounds;
  51343. RelativePoint fontSizeControlPoint;
  51344. Point<float> resolvedPoints[3];
  51345. Font font, scaledFont;
  51346. String text;
  51347. Colour colour;
  51348. Justification justification;
  51349. friend class Drawable::Positioner<DrawableText>;
  51350. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51351. void recalculateCoordinates (Expression::Scope*);
  51352. void refreshBounds();
  51353. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  51354. DrawableText& operator= (const DrawableText&);
  51355. JUCE_LEAK_DETECTOR (DrawableText);
  51356. };
  51357. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  51358. /*** End of inlined file: juce_DrawableText.h ***/
  51359. #endif
  51360. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  51361. #endif
  51362. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  51363. /*** Start of inlined file: juce_GlowEffect.h ***/
  51364. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  51365. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  51366. /**
  51367. A component effect that adds a coloured blur around the component's contents.
  51368. (This will only work on non-opaque components).
  51369. @see Component::setComponentEffect, DropShadowEffect
  51370. */
  51371. class JUCE_API GlowEffect : public ImageEffectFilter
  51372. {
  51373. public:
  51374. /** Creates a default 'glow' effect.
  51375. To customise its appearance, use the setGlowProperties() method.
  51376. */
  51377. GlowEffect();
  51378. /** Destructor. */
  51379. ~GlowEffect();
  51380. /** Sets the glow's radius and colour.
  51381. The radius is how large the blur should be, and the colour is
  51382. used to render it (for a less intense glow, lower the colour's
  51383. opacity).
  51384. */
  51385. void setGlowProperties (float newRadius,
  51386. const Colour& newColour);
  51387. /** @internal */
  51388. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  51389. private:
  51390. float radius;
  51391. Colour colour;
  51392. JUCE_LEAK_DETECTOR (GlowEffect);
  51393. };
  51394. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  51395. /*** End of inlined file: juce_GlowEffect.h ***/
  51396. #endif
  51397. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  51398. #endif
  51399. #ifndef __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51400. /*** Start of inlined file: juce_CustomTypeface.h ***/
  51401. #ifndef __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51402. #define __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51403. class InputStream;
  51404. class OutputStream;
  51405. /**
  51406. A typeface that can be populated with custom glyphs.
  51407. You can create a CustomTypeface if you need one that contains your own glyphs,
  51408. or if you need to load a typeface from a Juce-formatted binary stream.
  51409. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  51410. to copy glyphs into this face.
  51411. @see Typeface, Font
  51412. */
  51413. class JUCE_API CustomTypeface : public Typeface
  51414. {
  51415. public:
  51416. /** Creates a new, empty typeface. */
  51417. CustomTypeface();
  51418. /** Loads a typeface from a previously saved stream.
  51419. The stream must have been created by writeToStream().
  51420. @see writeToStream
  51421. */
  51422. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  51423. /** Destructor. */
  51424. ~CustomTypeface();
  51425. /** Resets this typeface, deleting all its glyphs and settings. */
  51426. void clear();
  51427. /** Sets the vital statistics for the typeface.
  51428. @param name the typeface's name
  51429. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  51430. the value that will be returned by Typeface::getAscent(). The
  51431. descent is assumed to be (1.0 - ascent)
  51432. @param isBold should be true if the typeface is bold
  51433. @param isItalic should be true if the typeface is italic
  51434. @param defaultCharacter the character to be used as a replacement if there's
  51435. no glyph available for the character that's being drawn
  51436. */
  51437. void setCharacteristics (const String& name, float ascent,
  51438. bool isBold, bool isItalic,
  51439. juce_wchar defaultCharacter) noexcept;
  51440. /** Adds a glyph to the typeface.
  51441. The path that is passed in is normalised so that the font height is 1.0, and its
  51442. origin is the anchor point of the character on its baseline.
  51443. The width is the nominal width of the character, and any extra kerning values that
  51444. are specified will be added to this width.
  51445. */
  51446. void addGlyph (juce_wchar character, const Path& path, float width) noexcept;
  51447. /** Specifies an extra kerning amount to be used between a pair of characters.
  51448. The amount will be added to the nominal width of the first character when laying out a string.
  51449. */
  51450. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) noexcept;
  51451. /** Adds a range of glyphs from another typeface.
  51452. This will attempt to pull in the paths and kerning information from another typeface and
  51453. add it to this one.
  51454. */
  51455. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) noexcept;
  51456. /** Saves this typeface as a Juce-formatted font file.
  51457. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  51458. constructor.
  51459. */
  51460. bool writeToStream (OutputStream& outputStream);
  51461. // The following methods implement the basic Typeface behaviour.
  51462. float getAscent() const;
  51463. float getDescent() const;
  51464. float getStringWidth (const String& text);
  51465. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  51466. bool getOutlineForGlyph (int glyphNumber, Path& path);
  51467. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  51468. protected:
  51469. juce_wchar defaultCharacter;
  51470. float ascent;
  51471. bool isBold, isItalic;
  51472. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  51473. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  51474. particular character and there's no corresponding glyph, they'll call this
  51475. method so that a subclass can try to add that glyph, returning true if it
  51476. manages to do so.
  51477. */
  51478. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  51479. private:
  51480. class GlyphInfo;
  51481. friend class OwnedArray<GlyphInfo>;
  51482. OwnedArray <GlyphInfo> glyphs;
  51483. short lookupTable [128];
  51484. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) noexcept;
  51485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  51486. };
  51487. #endif // __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51488. /*** End of inlined file: juce_CustomTypeface.h ***/
  51489. #endif
  51490. #ifndef __JUCE_FONT_JUCEHEADER__
  51491. #endif
  51492. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  51493. #endif
  51494. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  51495. #endif
  51496. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  51497. #endif
  51498. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  51499. #endif
  51500. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  51501. #endif
  51502. #ifndef __JUCE_LINE_JUCEHEADER__
  51503. #endif
  51504. #ifndef __JUCE_PATH_JUCEHEADER__
  51505. #endif
  51506. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  51507. /*** Start of inlined file: juce_PathIterator.h ***/
  51508. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  51509. #define __JUCE_PATHITERATOR_JUCEHEADER__
  51510. /**
  51511. Flattens a Path object into a series of straight-line sections.
  51512. Use one of these to iterate through a Path object, and it will convert
  51513. all the curves into line sections so it's easy to render or perform
  51514. geometric operations on.
  51515. @see Path
  51516. */
  51517. class JUCE_API PathFlatteningIterator
  51518. {
  51519. public:
  51520. /** Creates a PathFlatteningIterator.
  51521. After creation, use the next() method to initialise the fields in the
  51522. object with the first line's position.
  51523. @param path the path to iterate along
  51524. @param transform a transform to apply to each point in the path being iterated
  51525. @param tolerance the amount by which the curves are allowed to deviate from the lines
  51526. into which they are being broken down - a higher tolerance contains
  51527. less lines, so can be generated faster, but will be less smooth.
  51528. */
  51529. PathFlatteningIterator (const Path& path,
  51530. const AffineTransform& transform = AffineTransform::identity,
  51531. float tolerance = defaultTolerance);
  51532. /** Destructor. */
  51533. ~PathFlatteningIterator();
  51534. /** Fetches the next line segment from the path.
  51535. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  51536. so that they describe the new line segment.
  51537. @returns false when there are no more lines to fetch.
  51538. */
  51539. bool next();
  51540. float x1; /**< The x position of the start of the current line segment. */
  51541. float y1; /**< The y position of the start of the current line segment. */
  51542. float x2; /**< The x position of the end of the current line segment. */
  51543. float y2; /**< The y position of the end of the current line segment. */
  51544. /** Indicates whether the current line segment is closing a sub-path.
  51545. If the current line is the one that connects the end of a sub-path
  51546. back to the start again, this will be true.
  51547. */
  51548. bool closesSubPath;
  51549. /** The index of the current line within the current sub-path.
  51550. E.g. you can use this to see whether the line is the first one in the
  51551. subpath by seeing if it's 0.
  51552. */
  51553. int subPathIndex;
  51554. /** Returns true if the current segment is the last in the current sub-path. */
  51555. bool isLastInSubpath() const noexcept;
  51556. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  51557. static const float defaultTolerance;
  51558. private:
  51559. const Path& path;
  51560. const AffineTransform transform;
  51561. float* points;
  51562. const float toleranceSquared;
  51563. float subPathCloseX, subPathCloseY;
  51564. const bool isIdentityTransform;
  51565. HeapBlock <float> stackBase;
  51566. float* stackPos;
  51567. size_t index, stackSize;
  51568. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  51569. };
  51570. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  51571. /*** End of inlined file: juce_PathIterator.h ***/
  51572. #endif
  51573. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  51574. #endif
  51575. #ifndef __JUCE_POINT_JUCEHEADER__
  51576. #endif
  51577. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  51578. #endif
  51579. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  51580. #endif
  51581. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  51582. /*** Start of inlined file: juce_CameraDevice.h ***/
  51583. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  51584. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  51585. #if JUCE_USE_CAMERA || DOXYGEN
  51586. /**
  51587. Controls any video capture devices that might be available.
  51588. Use getAvailableDevices() to list the devices that are attached to the
  51589. system, then call openDevice to open one for use. Once you have a CameraDevice
  51590. object, you can get a viewer component from it, and use its methods to
  51591. stream to a file or capture still-frames.
  51592. */
  51593. class JUCE_API CameraDevice
  51594. {
  51595. public:
  51596. /** Destructor. */
  51597. virtual ~CameraDevice();
  51598. /** Returns a list of the available cameras on this machine.
  51599. You can open one of these devices by calling openDevice().
  51600. */
  51601. static const StringArray getAvailableDevices();
  51602. /** Opens a camera device.
  51603. The index parameter indicates which of the items returned by getAvailableDevices()
  51604. to open.
  51605. The size constraints allow the method to choose between different resolutions if
  51606. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  51607. then these will be ignored.
  51608. */
  51609. static CameraDevice* openDevice (int deviceIndex,
  51610. int minWidth = 128, int minHeight = 64,
  51611. int maxWidth = 1024, int maxHeight = 768);
  51612. /** Returns the name of this device */
  51613. String getName() const { return name; }
  51614. /** Creates a component that can be used to display a preview of the
  51615. video from this camera.
  51616. */
  51617. Component* createViewerComponent();
  51618. /** Starts recording video to the specified file.
  51619. You should use getFileExtension() to find out the correct extension to
  51620. use for your filename.
  51621. If the file exists, it will be deleted before the recording starts.
  51622. This method may not start recording instantly, so if you need to know the
  51623. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  51624. after the recording has finished.
  51625. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  51626. or may not be used, depending on the driver.
  51627. */
  51628. void startRecordingToFile (const File& file, int quality = 2);
  51629. /** Stops recording, after a call to startRecordingToFile().
  51630. */
  51631. void stopRecording();
  51632. /** Returns the file extension that should be used for the files
  51633. that you pass to startRecordingToFile().
  51634. This may be platform-specific, e.g. ".mov" or ".avi".
  51635. */
  51636. static const String getFileExtension();
  51637. /** After calling stopRecording(), this method can be called to return the timestamp
  51638. of the first frame that was written to the file.
  51639. */
  51640. const Time getTimeOfFirstRecordedFrame() const;
  51641. /**
  51642. Receives callbacks with images from a CameraDevice.
  51643. @see CameraDevice::addListener
  51644. */
  51645. class JUCE_API Listener
  51646. {
  51647. public:
  51648. Listener() {}
  51649. virtual ~Listener() {}
  51650. /** This method is called when a new image arrives.
  51651. This may be called by any thread, so be careful about thread-safety,
  51652. and make sure that you process the data as quickly as possible to
  51653. avoid glitching!
  51654. */
  51655. virtual void imageReceived (const Image& image) = 0;
  51656. };
  51657. /** Adds a listener to receive images from the camera.
  51658. Be very careful not to delete the listener without first removing it by calling
  51659. removeListener().
  51660. */
  51661. void addListener (Listener* listenerToAdd);
  51662. /** Removes a listener that was previously added with addListener().
  51663. */
  51664. void removeListener (Listener* listenerToRemove);
  51665. protected:
  51666. #ifndef DOXYGEN
  51667. CameraDevice (const String& name, int index);
  51668. #endif
  51669. private:
  51670. void* internal;
  51671. bool isRecording;
  51672. String name;
  51673. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  51674. };
  51675. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  51676. typedef CameraDevice::Listener CameraImageListener;
  51677. #endif
  51678. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  51679. /*** End of inlined file: juce_CameraDevice.h ***/
  51680. #endif
  51681. #ifndef __JUCE_IMAGE_JUCEHEADER__
  51682. #endif
  51683. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  51684. /*** Start of inlined file: juce_ImageCache.h ***/
  51685. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  51686. #define __JUCE_IMAGECACHE_JUCEHEADER__
  51687. /**
  51688. A global cache of images that have been loaded from files or memory.
  51689. If you're loading an image and may need to use the image in more than one
  51690. place, this is used to allow the same image to be shared rather than loading
  51691. multiple copies into memory.
  51692. Another advantage is that after images are released, they will be kept in
  51693. memory for a few seconds before it is actually deleted, so if you're repeatedly
  51694. loading/deleting the same image, it'll reduce the chances of having to reload it
  51695. each time.
  51696. @see Image, ImageFileFormat
  51697. */
  51698. class JUCE_API ImageCache
  51699. {
  51700. public:
  51701. /** Loads an image from a file, (or just returns the image if it's already cached).
  51702. If the cache already contains an image that was loaded from this file,
  51703. that image will be returned. Otherwise, this method will try to load the
  51704. file, add it to the cache, and return it.
  51705. Remember that the image returned is shared, so drawing into it might
  51706. affect other things that are using it! If you want to draw on it, first
  51707. call Image::duplicateIfShared()
  51708. @param file the file to try to load
  51709. @returns the image, or null if it there was an error loading it
  51710. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51711. */
  51712. static Image getFromFile (const File& file);
  51713. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  51714. If the cache already contains an image that was loaded from this block of memory,
  51715. that image will be returned. Otherwise, this method will try to load the
  51716. file, add it to the cache, and return it.
  51717. Remember that the image returned is shared, so drawing into it might
  51718. affect other things that are using it! If you want to draw on it, first
  51719. call Image::duplicateIfShared()
  51720. @param imageData the block of memory containing the image data
  51721. @param dataSize the data size in bytes
  51722. @returns the image, or an invalid image if it there was an error loading it
  51723. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51724. */
  51725. static Image getFromMemory (const void* imageData, int dataSize);
  51726. /** Checks the cache for an image with a particular hashcode.
  51727. If there's an image in the cache with this hashcode, it will be returned,
  51728. otherwise it will return an invalid image.
  51729. @param hashCode the hash code that was associated with the image by addImageToCache()
  51730. @see addImageToCache
  51731. */
  51732. static Image getFromHashCode (int64 hashCode);
  51733. /** Adds an image to the cache with a user-defined hash-code.
  51734. The image passed-in will be referenced (not copied) by the cache, so it's probably
  51735. a good idea not to draw into it after adding it, otherwise this will affect all
  51736. instances of it that may be in use.
  51737. @param image the image to add
  51738. @param hashCode the hash-code to associate with it
  51739. @see getFromHashCode
  51740. */
  51741. static void addImageToCache (const Image& image, int64 hashCode);
  51742. /** Changes the amount of time before an unused image will be removed from the cache.
  51743. By default this is about 5 seconds.
  51744. */
  51745. static void setCacheTimeout (int millisecs);
  51746. private:
  51747. class Pimpl;
  51748. friend class Pimpl;
  51749. ImageCache();
  51750. ~ImageCache();
  51751. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  51752. };
  51753. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  51754. /*** End of inlined file: juce_ImageCache.h ***/
  51755. #endif
  51756. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51757. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  51758. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51759. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51760. /**
  51761. Represents a filter kernel to use in convoluting an image.
  51762. @see Image::applyConvolution
  51763. */
  51764. class JUCE_API ImageConvolutionKernel
  51765. {
  51766. public:
  51767. /** Creates an empty convulution kernel.
  51768. @param size the length of each dimension of the kernel, so e.g. if the size
  51769. is 5, it will create a 5x5 kernel
  51770. */
  51771. ImageConvolutionKernel (int size);
  51772. /** Destructor. */
  51773. ~ImageConvolutionKernel();
  51774. /** Resets all values in the kernel to zero. */
  51775. void clear();
  51776. /** Returns one of the kernel values. */
  51777. float getKernelValue (int x, int y) const noexcept;
  51778. /** Sets the value of a specific cell in the kernel.
  51779. The x and y parameters must be in the range 0 < x < getKernelSize().
  51780. @see setOverallSum
  51781. */
  51782. void setKernelValue (int x, int y, float value) noexcept;
  51783. /** Rescales all values in the kernel to make the total add up to a fixed value.
  51784. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  51785. */
  51786. void setOverallSum (float desiredTotalSum);
  51787. /** Multiplies all values in the kernel by a value. */
  51788. void rescaleAllValues (float multiplier);
  51789. /** Intialises the kernel for a gaussian blur.
  51790. @param blurRadius this may be larger or smaller than the kernel's actual
  51791. size but this will obviously be wasteful or clip at the
  51792. edges. Ideally the kernel should be just larger than
  51793. (blurRadius * 2).
  51794. */
  51795. void createGaussianBlur (float blurRadius);
  51796. /** Returns the size of the kernel.
  51797. E.g. if it's a 3x3 kernel, this returns 3.
  51798. */
  51799. int getKernelSize() const { return size; }
  51800. /** Applies the kernel to an image.
  51801. @param destImage the image that will receive the resultant convoluted pixels.
  51802. @param sourceImage the source image to read from - this can be the same image as
  51803. the destination, but if different, it must be exactly the same
  51804. size and format.
  51805. @param destinationArea the region of the image to apply the filter to
  51806. */
  51807. void applyToImage (Image& destImage,
  51808. const Image& sourceImage,
  51809. const Rectangle<int>& destinationArea) const;
  51810. private:
  51811. HeapBlock <float> values;
  51812. const int size;
  51813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  51814. };
  51815. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51816. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  51817. #endif
  51818. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51819. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  51820. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51821. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51822. /**
  51823. Base-class for codecs that can read and write image file formats such
  51824. as PNG, JPEG, etc.
  51825. This class also contains static methods to make it easy to load images
  51826. from files, streams or from memory.
  51827. @see Image, ImageCache
  51828. */
  51829. class JUCE_API ImageFileFormat
  51830. {
  51831. protected:
  51832. /** Creates an ImageFormat. */
  51833. ImageFileFormat() {}
  51834. public:
  51835. /** Destructor. */
  51836. virtual ~ImageFileFormat() {}
  51837. /** Returns a description of this file format.
  51838. E.g. "JPEG", "PNG"
  51839. */
  51840. virtual String getFormatName() = 0;
  51841. /** Returns true if the given stream seems to contain data that this format
  51842. understands.
  51843. The format class should only read the first few bytes of the stream and sniff
  51844. for header bytes that it understands.
  51845. @see decodeImage
  51846. */
  51847. virtual bool canUnderstand (InputStream& input) = 0;
  51848. /** Tries to decode and return an image from the given stream.
  51849. This will be called for an image format after calling its canUnderStand() method
  51850. to see if it can handle the stream.
  51851. @param input the stream to read the data from. The stream will be positioned
  51852. at the start of the image data (but this may not necessarily
  51853. be position 0)
  51854. @returns the image that was decoded, or an invalid image if it fails.
  51855. @see loadFrom
  51856. */
  51857. virtual Image decodeImage (InputStream& input) = 0;
  51858. /** Attempts to write an image to a stream.
  51859. To specify extra information like encoding quality, there will be appropriate parameters
  51860. in the subclasses of the specific file types.
  51861. @returns true if it nothing went wrong.
  51862. */
  51863. virtual bool writeImageToStream (const Image& sourceImage,
  51864. OutputStream& destStream) = 0;
  51865. /** Tries the built-in decoders to see if it can find one to read this stream.
  51866. There are currently built-in decoders for PNG, JPEG and GIF formats.
  51867. The object that is returned should not be deleted by the caller.
  51868. @see canUnderstand, decodeImage, loadFrom
  51869. */
  51870. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  51871. /** Tries to load an image from a stream.
  51872. This will use the findImageFormatForStream() method to locate a suitable
  51873. codec, and use that to load the image.
  51874. @returns the image that was decoded, or an invalid image if it fails.
  51875. */
  51876. static Image loadFrom (InputStream& input);
  51877. /** Tries to load an image from a file.
  51878. This will use the findImageFormatForStream() method to locate a suitable
  51879. codec, and use that to load the image.
  51880. @returns the image that was decoded, or an invalid image if it fails.
  51881. */
  51882. static Image loadFrom (const File& file);
  51883. /** Tries to load an image from a block of raw image data.
  51884. This will use the findImageFormatForStream() method to locate a suitable
  51885. codec, and use that to load the image.
  51886. @returns the image that was decoded, or an invalid image if it fails.
  51887. */
  51888. static Image loadFrom (const void* rawData,
  51889. const int numBytesOfData);
  51890. };
  51891. /**
  51892. A subclass of ImageFileFormat for reading and writing PNG files.
  51893. @see ImageFileFormat, JPEGImageFormat
  51894. */
  51895. class JUCE_API PNGImageFormat : public ImageFileFormat
  51896. {
  51897. public:
  51898. PNGImageFormat();
  51899. ~PNGImageFormat();
  51900. String getFormatName();
  51901. bool canUnderstand (InputStream& input);
  51902. Image decodeImage (InputStream& input);
  51903. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51904. };
  51905. /**
  51906. A subclass of ImageFileFormat for reading and writing JPEG files.
  51907. @see ImageFileFormat, PNGImageFormat
  51908. */
  51909. class JUCE_API JPEGImageFormat : public ImageFileFormat
  51910. {
  51911. public:
  51912. JPEGImageFormat();
  51913. ~JPEGImageFormat();
  51914. /** Specifies the quality to be used when writing a JPEG file.
  51915. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  51916. any negative value is "default" quality
  51917. */
  51918. void setQuality (float newQuality);
  51919. String getFormatName();
  51920. bool canUnderstand (InputStream& input);
  51921. Image decodeImage (InputStream& input);
  51922. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51923. private:
  51924. float quality;
  51925. };
  51926. /**
  51927. A subclass of ImageFileFormat for reading GIF files.
  51928. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  51929. */
  51930. class JUCE_API GIFImageFormat : public ImageFileFormat
  51931. {
  51932. public:
  51933. GIFImageFormat();
  51934. ~GIFImageFormat();
  51935. String getFormatName();
  51936. bool canUnderstand (InputStream& input);
  51937. Image decodeImage (InputStream& input);
  51938. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51939. };
  51940. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51941. /*** End of inlined file: juce_ImageFileFormat.h ***/
  51942. #endif
  51943. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  51944. #endif
  51945. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51946. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  51947. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51948. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51949. /**
  51950. A class to take care of the logic involved with the loading/saving of some kind
  51951. of document.
  51952. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  51953. functions you need for documents that get saved to a file, so this class attempts
  51954. to abstract most of the boring stuff.
  51955. Your subclass should just implement all the pure virtual methods, and you can
  51956. then use the higher-level public methods to do the load/save dialogs, to warn the user
  51957. about overwriting files, etc.
  51958. The document object keeps track of whether it has changed since it was last saved or
  51959. loaded, so when you change something, call its changed() method. This will set a
  51960. flag so it knows it needs saving, and will also broadcast a change message using the
  51961. ChangeBroadcaster base class.
  51962. @see ChangeBroadcaster
  51963. */
  51964. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  51965. {
  51966. public:
  51967. /** Creates a FileBasedDocument.
  51968. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  51969. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  51970. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  51971. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  51972. */
  51973. FileBasedDocument (const String& fileExtension,
  51974. const String& fileWildCard,
  51975. const String& openFileDialogTitle,
  51976. const String& saveFileDialogTitle);
  51977. /** Destructor. */
  51978. virtual ~FileBasedDocument();
  51979. /** Returns true if the changed() method has been called since the file was
  51980. last saved or loaded.
  51981. @see resetChangedFlag, changed
  51982. */
  51983. bool hasChangedSinceSaved() const { return changedSinceSave; }
  51984. /** Called to indicate that the document has changed and needs saving.
  51985. This method will also trigger a change message to be sent out using the
  51986. ChangeBroadcaster base class.
  51987. After calling the method, the hasChangedSinceSaved() method will return true, until
  51988. it is reset either by saving to a file or using the resetChangedFlag() method.
  51989. @see hasChangedSinceSaved, resetChangedFlag
  51990. */
  51991. virtual void changed();
  51992. /** Sets the state of the 'changed' flag.
  51993. The 'changed' flag is set to true when the changed() method is called - use this method
  51994. to reset it or to set it without also broadcasting a change message.
  51995. @see changed, hasChangedSinceSaved
  51996. */
  51997. void setChangedFlag (bool hasChanged);
  51998. /** Tries to open a file.
  51999. If the file opens correctly, the document's file (see the getFile() method) is set
  52000. to this new one; if it fails, the document's file is left unchanged, and optionally
  52001. a message box is shown telling the user there was an error.
  52002. @returns true if the new file loaded successfully
  52003. @see loadDocument, loadFromUserSpecifiedFile
  52004. */
  52005. bool loadFrom (const File& fileToLoadFrom,
  52006. bool showMessageOnFailure);
  52007. /** Asks the user for a file and tries to load it.
  52008. This will pop up a dialog box using the title, file extension and
  52009. wildcard specified in the document's constructor, and asks the user
  52010. for a file. If they pick one, the loadFrom() method is used to
  52011. try to load it, optionally showing a message if it fails.
  52012. @returns true if a file was loaded; false if the user cancelled or if they
  52013. picked a file which failed to load correctly
  52014. @see loadFrom
  52015. */
  52016. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  52017. /** A set of possible outcomes of one of the save() methods
  52018. */
  52019. enum SaveResult
  52020. {
  52021. savedOk = 0, /**< indicates that a file was saved successfully. */
  52022. userCancelledSave, /**< indicates that the user aborted the save operation. */
  52023. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  52024. };
  52025. /** Tries to save the document to the last file it was saved or loaded from.
  52026. This will always try to write to the file, even if the document isn't flagged as
  52027. having changed.
  52028. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  52029. true, it will prompt the user to pick a file, as if
  52030. saveAsInteractive() was called.
  52031. @param showMessageOnFailure if true it will show a warning message when if the
  52032. save operation fails
  52033. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  52034. */
  52035. SaveResult save (bool askUserForFileIfNotSpecified,
  52036. bool showMessageOnFailure);
  52037. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  52038. it if they say yes.
  52039. If you've got a document open and want to close it (e.g. to quit the app), this is the
  52040. method to call.
  52041. If the document doesn't need saving it'll return the value savedOk so
  52042. you can go ahead and delete the document.
  52043. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  52044. return savedOk, so again, you can safely delete the document.
  52045. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  52046. close-document operation.
  52047. And if they click "save changes", it'll try to save and either return savedOk, or
  52048. failedToWriteToFile if there was a problem.
  52049. @see save, saveAs, saveAsInteractive
  52050. */
  52051. SaveResult saveIfNeededAndUserAgrees();
  52052. /** Tries to save the document to a specified file.
  52053. If this succeeds, it'll also change the document's internal file (as returned by
  52054. the getFile() method). If it fails, the file will be left unchanged.
  52055. @param newFile the file to try to write to
  52056. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  52057. the user first if they want to overwrite it
  52058. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  52059. use the saveAsInteractive() method to ask the user for a
  52060. filename
  52061. @param showMessageOnFailure if true and the write operation fails, it'll show
  52062. a message box to warn the user
  52063. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  52064. */
  52065. SaveResult saveAs (const File& newFile,
  52066. bool warnAboutOverwritingExistingFiles,
  52067. bool askUserForFileIfNotSpecified,
  52068. bool showMessageOnFailure);
  52069. /** Prompts the user for a filename and tries to save to it.
  52070. This will pop up a dialog box using the title, file extension and
  52071. wildcard specified in the document's constructor, and asks the user
  52072. for a file. If they pick one, the saveAs() method is used to try to save
  52073. to this file.
  52074. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  52075. the user first if they want to overwrite it
  52076. @see saveIfNeededAndUserAgrees, save, saveAs
  52077. */
  52078. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  52079. /** Returns the file that this document was last successfully saved or loaded from.
  52080. When the document object is created, this will be set to File::nonexistent.
  52081. It is changed when one of the load or save methods is used, or when setFile()
  52082. is used to explicitly set it.
  52083. */
  52084. const File& getFile() const { return documentFile; }
  52085. /** Sets the file that this document thinks it was loaded from.
  52086. This won't actually load anything - it just changes the file stored internally.
  52087. @see getFile
  52088. */
  52089. void setFile (const File& newFile);
  52090. protected:
  52091. /** Overload this to return the title of the document.
  52092. This is used in message boxes, filenames and file choosers, so it should be
  52093. something sensible.
  52094. */
  52095. virtual const String getDocumentTitle() = 0;
  52096. /** This method should try to load your document from the given file.
  52097. If it fails, it should return an error message. If it succeeds, it should return
  52098. an empty string.
  52099. */
  52100. virtual const String loadDocument (const File& file) = 0;
  52101. /** This method should try to write your document to the given file.
  52102. If it fails, it should return an error message. If it succeeds, it should return
  52103. an empty string.
  52104. */
  52105. virtual const String saveDocument (const File& file) = 0;
  52106. /** This is used for dialog boxes to make them open at the last folder you
  52107. were using.
  52108. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  52109. the last document that was used - you might want to store this value
  52110. in a static variable, or even in your application's properties. It should
  52111. be a global setting rather than a property of this object.
  52112. This method works very well in conjunction with a RecentlyOpenedFilesList
  52113. object to manage your recent-files list.
  52114. As a default value, it's ok to return File::nonexistent, and the document
  52115. object will use a sensible one instead.
  52116. @see RecentlyOpenedFilesList
  52117. */
  52118. virtual const File getLastDocumentOpened() = 0;
  52119. /** This is used for dialog boxes to make them open at the last folder you
  52120. were using.
  52121. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  52122. the last document that was used - you might want to store this value
  52123. in a static variable, or even in your application's properties. It should
  52124. be a global setting rather than a property of this object.
  52125. This method works very well in conjunction with a RecentlyOpenedFilesList
  52126. object to manage your recent-files list.
  52127. @see RecentlyOpenedFilesList
  52128. */
  52129. virtual void setLastDocumentOpened (const File& file) = 0;
  52130. private:
  52131. File documentFile;
  52132. bool changedSinceSave;
  52133. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  52134. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  52135. };
  52136. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52137. /*** End of inlined file: juce_FileBasedDocument.h ***/
  52138. #endif
  52139. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  52140. #endif
  52141. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52142. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  52143. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52144. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52145. /**
  52146. Manages a set of files for use as a list of recently-opened documents.
  52147. This is a handy class for holding your list of recently-opened documents, with
  52148. helpful methods for things like purging any non-existent files, automatically
  52149. adding them to a menu, and making persistence easy.
  52150. @see File, FileBasedDocument
  52151. */
  52152. class JUCE_API RecentlyOpenedFilesList
  52153. {
  52154. public:
  52155. /** Creates an empty list.
  52156. */
  52157. RecentlyOpenedFilesList();
  52158. /** Destructor. */
  52159. ~RecentlyOpenedFilesList();
  52160. /** Sets a limit for the number of files that will be stored in the list.
  52161. When addFile() is called, then if there is no more space in the list, the
  52162. least-recently added file will be dropped.
  52163. @see getMaxNumberOfItems
  52164. */
  52165. void setMaxNumberOfItems (int newMaxNumber);
  52166. /** Returns the number of items that this list will store.
  52167. @see setMaxNumberOfItems
  52168. */
  52169. int getMaxNumberOfItems() const noexcept { return maxNumberOfItems; }
  52170. /** Returns the number of files in the list.
  52171. The most recently added file is always at index 0.
  52172. */
  52173. int getNumFiles() const;
  52174. /** Returns one of the files in the list.
  52175. The most recently added file is always at index 0.
  52176. */
  52177. File getFile (int index) const;
  52178. /** Returns an array of all the absolute pathnames in the list.
  52179. */
  52180. const StringArray& getAllFilenames() const noexcept { return files; }
  52181. /** Clears all the files from the list. */
  52182. void clear();
  52183. /** Adds a file to the list.
  52184. The file will be added at index 0. If this file is already in the list, it will
  52185. be moved up to index 0, but a file can only appear once in the list.
  52186. If the list already contains the maximum number of items that is permitted, the
  52187. least-recently added file will be dropped from the end.
  52188. */
  52189. void addFile (const File& file);
  52190. /** Removes a file from the list. */
  52191. void removeFile (const File& file);
  52192. /** Checks each of the files in the list, removing any that don't exist.
  52193. You might want to call this after reloading a list of files, or before putting them
  52194. on a menu.
  52195. */
  52196. void removeNonExistentFiles();
  52197. /** Adds entries to a menu, representing each of the files in the list.
  52198. This is handy for creating an "open recent file..." menu in your app. The
  52199. menu items are numbered consecutively starting with the baseItemId value,
  52200. and can either be added as complete pathnames, or just the last part of the
  52201. filename.
  52202. If dontAddNonExistentFiles is true, then each file will be checked and only those
  52203. that exist will be added.
  52204. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  52205. pointers to file objects. Any files that appear in this list will not be added to the
  52206. menu - the reason for this is that you might have a number of files already open, so
  52207. might not want these to be shown in the menu.
  52208. It returns the number of items that were added.
  52209. */
  52210. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  52211. int baseItemId,
  52212. bool showFullPaths,
  52213. bool dontAddNonExistentFiles,
  52214. const File** filesToAvoid = nullptr);
  52215. /** Returns a string that encapsulates all the files in the list.
  52216. The string that is returned can later be passed into restoreFromString() in
  52217. order to recreate the list. This is handy for persisting your list, e.g. in
  52218. a PropertiesFile object.
  52219. @see restoreFromString
  52220. */
  52221. String toString() const;
  52222. /** Restores the list from a previously stringified version of the list.
  52223. Pass in a stringified version created with toString() in order to persist/restore
  52224. your list.
  52225. @see toString
  52226. */
  52227. void restoreFromString (const String& stringifiedVersion);
  52228. private:
  52229. StringArray files;
  52230. int maxNumberOfItems;
  52231. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  52232. };
  52233. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52234. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  52235. #endif
  52236. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  52237. #endif
  52238. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52239. /*** Start of inlined file: juce_SystemClipboard.h ***/
  52240. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52241. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52242. /**
  52243. Handles reading/writing to the system's clipboard.
  52244. */
  52245. class JUCE_API SystemClipboard
  52246. {
  52247. public:
  52248. /** Copies a string of text onto the clipboard */
  52249. static void copyTextToClipboard (const String& text);
  52250. /** Gets the current clipboard's contents.
  52251. Obviously this might have come from another app, so could contain
  52252. anything..
  52253. */
  52254. static String getTextFromClipboard();
  52255. };
  52256. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52257. /*** End of inlined file: juce_SystemClipboard.h ***/
  52258. #endif
  52259. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  52260. #endif
  52261. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  52262. #endif
  52263. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  52264. /*** Start of inlined file: juce_UnitTest.h ***/
  52265. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  52266. #define __JUCE_UNITTEST_JUCEHEADER__
  52267. class UnitTestRunner;
  52268. /**
  52269. This is a base class for classes that perform a unit test.
  52270. To write a test using this class, your code should look something like this:
  52271. @code
  52272. class MyTest : public UnitTest
  52273. {
  52274. public:
  52275. MyTest() : UnitTest ("Foobar testing") {}
  52276. void runTest()
  52277. {
  52278. beginTest ("Part 1");
  52279. expect (myFoobar.doesSomething());
  52280. expect (myFoobar.doesSomethingElse());
  52281. beginTest ("Part 2");
  52282. expect (myOtherFoobar.doesSomething());
  52283. expect (myOtherFoobar.doesSomethingElse());
  52284. ...etc..
  52285. }
  52286. };
  52287. // Creating a static instance will automatically add the instance to the array
  52288. // returned by UnitTest::getAllTests(), so the test will be included when you call
  52289. // UnitTestRunner::runAllTests()
  52290. static MyTest test;
  52291. @endcode
  52292. To run a test, use the UnitTestRunner class.
  52293. @see UnitTestRunner
  52294. */
  52295. class JUCE_API UnitTest
  52296. {
  52297. public:
  52298. /** Creates a test with the given name. */
  52299. explicit UnitTest (const String& name);
  52300. /** Destructor. */
  52301. virtual ~UnitTest();
  52302. /** Returns the name of the test. */
  52303. const String& getName() const noexcept { return name; }
  52304. /** Runs the test, using the specified UnitTestRunner.
  52305. You shouldn't need to call this method directly - use
  52306. UnitTestRunner::runTests() instead.
  52307. */
  52308. void performTest (UnitTestRunner* runner);
  52309. /** Returns the set of all UnitTest objects that currently exist. */
  52310. static Array<UnitTest*>& getAllTests();
  52311. /** You can optionally implement this method to set up your test.
  52312. This method will be called before runTest().
  52313. */
  52314. virtual void initialise();
  52315. /** You can optionally implement this method to clear up after your test has been run.
  52316. This method will be called after runTest() has returned.
  52317. */
  52318. virtual void shutdown();
  52319. /** Implement this method in your subclass to actually run your tests.
  52320. The content of your implementation should call beginTest() and expect()
  52321. to perform the tests.
  52322. */
  52323. virtual void runTest() = 0;
  52324. /** Tells the system that a new subsection of tests is beginning.
  52325. This should be called from your runTest() method, and may be called
  52326. as many times as you like, to demarcate different sets of tests.
  52327. */
  52328. void beginTest (const String& testName);
  52329. /** Checks that the result of a test is true, and logs this result.
  52330. In your runTest() method, you should call this method for each condition that
  52331. you want to check, e.g.
  52332. @code
  52333. void runTest()
  52334. {
  52335. beginTest ("basic tests");
  52336. expect (x + y == 2);
  52337. expect (getThing() == someThing);
  52338. ...etc...
  52339. }
  52340. @endcode
  52341. If testResult is true, a pass is logged; if it's false, a failure is logged.
  52342. If the failure message is specified, it will be written to the log if the test fails.
  52343. */
  52344. void expect (bool testResult, const String& failureMessage = String::empty);
  52345. /** Compares two values, and if they don't match, prints out a message containing the
  52346. expected and actual result values.
  52347. */
  52348. template <class ValueType>
  52349. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  52350. {
  52351. const bool result = (actual == expected);
  52352. if (! result)
  52353. {
  52354. if (failureMessage.isNotEmpty())
  52355. failureMessage << " -- ";
  52356. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  52357. }
  52358. expect (result, failureMessage);
  52359. }
  52360. /** Writes a message to the test log.
  52361. This can only be called from within your runTest() method.
  52362. */
  52363. void logMessage (const String& message);
  52364. private:
  52365. const String name;
  52366. UnitTestRunner* runner;
  52367. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  52368. };
  52369. /**
  52370. Runs a set of unit tests.
  52371. You can instantiate one of these objects and use it to invoke tests on a set of
  52372. UnitTest objects.
  52373. By using a subclass of UnitTestRunner, you can intercept logging messages and
  52374. perform custom behaviour when each test completes.
  52375. @see UnitTest
  52376. */
  52377. class JUCE_API UnitTestRunner
  52378. {
  52379. public:
  52380. /** */
  52381. UnitTestRunner();
  52382. /** Destructor. */
  52383. virtual ~UnitTestRunner();
  52384. /** Runs a set of tests.
  52385. The tests are performed in order, and the results are logged. To run all the
  52386. registered UnitTest objects that exist, use runAllTests().
  52387. */
  52388. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  52389. /** Runs all the UnitTest objects that currently exist.
  52390. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  52391. */
  52392. void runAllTests (bool assertOnFailure);
  52393. /** Contains the results of a test.
  52394. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  52395. it contains details of the number of subsequent UnitTest::expect() calls that are
  52396. made.
  52397. */
  52398. struct TestResult
  52399. {
  52400. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  52401. String unitTestName;
  52402. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  52403. String subcategoryName;
  52404. /** The number of UnitTest::expect() calls that succeeded. */
  52405. int passes;
  52406. /** The number of UnitTest::expect() calls that failed. */
  52407. int failures;
  52408. /** A list of messages describing the failed tests. */
  52409. StringArray messages;
  52410. };
  52411. /** Returns the number of TestResult objects that have been performed.
  52412. @see getResult
  52413. */
  52414. int getNumResults() const noexcept;
  52415. /** Returns one of the TestResult objects that describes a test that has been run.
  52416. @see getNumResults
  52417. */
  52418. const TestResult* getResult (int index) const noexcept;
  52419. protected:
  52420. /** Called when the list of results changes.
  52421. You can override this to perform some sort of behaviour when results are added.
  52422. */
  52423. virtual void resultsUpdated();
  52424. /** Logs a message about the current test progress.
  52425. By default this just writes the message to the Logger class, but you could override
  52426. this to do something else with the data.
  52427. */
  52428. virtual void logMessage (const String& message);
  52429. private:
  52430. friend class UnitTest;
  52431. UnitTest* currentTest;
  52432. String currentSubCategory;
  52433. OwnedArray <TestResult, CriticalSection> results;
  52434. bool assertOnFailure;
  52435. void beginNewTest (UnitTest* test, const String& subCategory);
  52436. void endTest();
  52437. void addPass();
  52438. void addFail (const String& failureMessage);
  52439. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  52440. };
  52441. #endif // __JUCE_UNITTEST_JUCEHEADER__
  52442. /*** End of inlined file: juce_UnitTest.h ***/
  52443. #endif
  52444. #endif
  52445. /*** End of inlined file: juce_app_includes.h ***/
  52446. #endif
  52447. #if JUCE_MSVC
  52448. #pragma warning (pop)
  52449. #pragma pack (pop)
  52450. #endif
  52451. END_JUCE_NAMESPACE
  52452. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  52453. #ifdef JUCE_NAMESPACE
  52454. // this will obviously save a lot of typing, but can be disabled by
  52455. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  52456. using namespace JUCE_NAMESPACE;
  52457. /* On the Mac, these symbols are defined in the Mac libraries, so
  52458. these macros make it easier to reference them without writing out
  52459. the namespace every time.
  52460. If you run into difficulties where these macros interfere with the contents
  52461. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  52462. the comments in that file for more information.
  52463. */
  52464. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  52465. #define Component JUCE_NAMESPACE::Component
  52466. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  52467. #define Point JUCE_NAMESPACE::Point
  52468. #define Button JUCE_NAMESPACE::Button
  52469. #endif
  52470. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  52471. it easier to use the juce version explicitly.
  52472. If you run into difficulties where this macro interferes with other 3rd party header
  52473. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  52474. file for more information.
  52475. */
  52476. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  52477. #define Rectangle JUCE_NAMESPACE::Rectangle
  52478. #endif
  52479. #endif
  52480. #endif
  52481. /* Easy autolinking to the right JUCE libraries under win32.
  52482. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  52483. including this header file.
  52484. */
  52485. #if JUCE_MSVC
  52486. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  52487. /** If you want your application to link to Juce as a DLL instead of
  52488. a static library (on win32), just define the JUCE_DLL macro before
  52489. including juce.h
  52490. */
  52491. #ifdef JUCE_DLL
  52492. #if JUCE_DEBUG
  52493. #define AUTOLINKEDLIB "JUCE_debug.lib"
  52494. #else
  52495. #define AUTOLINKEDLIB "JUCE.lib"
  52496. #endif
  52497. #else
  52498. #if JUCE_DEBUG
  52499. #ifdef _WIN64
  52500. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  52501. #else
  52502. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  52503. #endif
  52504. #else
  52505. #ifdef _WIN64
  52506. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  52507. #else
  52508. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  52509. #endif
  52510. #endif
  52511. #endif
  52512. #pragma comment(lib, AUTOLINKEDLIB)
  52513. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  52514. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  52515. #endif
  52516. // Auto-link the other win32 libs that are needed by library calls..
  52517. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  52518. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  52519. // Auto-links to various win32 libs that are needed by library calls..
  52520. #pragma comment(lib, "kernel32.lib")
  52521. #pragma comment(lib, "user32.lib")
  52522. #pragma comment(lib, "shell32.lib")
  52523. #pragma comment(lib, "gdi32.lib")
  52524. #pragma comment(lib, "vfw32.lib")
  52525. #pragma comment(lib, "comdlg32.lib")
  52526. #pragma comment(lib, "winmm.lib")
  52527. #pragma comment(lib, "wininet.lib")
  52528. #pragma comment(lib, "ole32.lib")
  52529. #pragma comment(lib, "oleaut32.lib")
  52530. #pragma comment(lib, "advapi32.lib")
  52531. #pragma comment(lib, "ws2_32.lib")
  52532. #pragma comment(lib, "version.lib")
  52533. #pragma comment(lib, "shlwapi.lib")
  52534. #pragma comment(lib, "imm32.lib")
  52535. #ifdef _NATIVE_WCHAR_T_DEFINED
  52536. #ifdef _DEBUG
  52537. #pragma comment(lib, "comsuppwd.lib")
  52538. #else
  52539. #pragma comment(lib, "comsuppw.lib")
  52540. #endif
  52541. #else
  52542. #ifdef _DEBUG
  52543. #pragma comment(lib, "comsuppd.lib")
  52544. #else
  52545. #pragma comment(lib, "comsupp.lib")
  52546. #endif
  52547. #endif
  52548. #if JUCE_OPENGL
  52549. #pragma comment(lib, "OpenGL32.Lib")
  52550. #pragma comment(lib, "GlU32.Lib")
  52551. #endif
  52552. #if JUCE_QUICKTIME
  52553. #pragma comment (lib, "QTMLClient.lib")
  52554. #endif
  52555. #if JUCE_USE_CAMERA
  52556. #pragma comment (lib, "Strmiids.lib")
  52557. #pragma comment (lib, "wmvcore.lib")
  52558. #endif
  52559. #if JUCE_DIRECT2D
  52560. #pragma comment (lib, "Dwrite.lib")
  52561. #pragma comment (lib, "D2d1.lib")
  52562. #endif
  52563. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  52564. #endif
  52565. #endif
  52566. #endif
  52567. #endif // __JUCE_JUCEHEADER__
  52568. /*** End of inlined file: juce.h ***/
  52569. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__