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.

68160 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 70
  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 ! (DOXYGEN || JUCE_COMPILER_SUPPORTS_CXX2011)
  613. #define noexcept throw() // for c++98 compilers, we can fake these newer language features.
  614. #define nullptr (0)
  615. #endif
  616. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  617. /*** End of inlined file: juce_PlatformDefs.h ***/
  618. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  619. #if JUCE_MSVC
  620. #if JUCE_VC6
  621. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  622. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  623. {
  624. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  625. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  626. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  627. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  628. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  629. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  630. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  631. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  632. }
  633. #endif
  634. #pragma warning (push)
  635. #pragma warning (disable: 4514 4245 4100)
  636. #endif
  637. #include <cstdlib>
  638. #include <cstdarg>
  639. #include <climits>
  640. #include <limits>
  641. #include <cmath>
  642. #include <cwchar>
  643. #include <stdexcept>
  644. #include <typeinfo>
  645. #include <cstring>
  646. #include <cstdio>
  647. #include <iostream>
  648. #include <vector>
  649. #if JUCE_USE_INTRINSICS
  650. #include <intrin.h>
  651. #endif
  652. #if JUCE_MAC || JUCE_IOS
  653. #include <libkern/OSAtomic.h>
  654. #endif
  655. #if JUCE_LINUX
  656. #include <signal.h>
  657. #if __INTEL_COMPILER
  658. #if __ia64__
  659. #include <ia64intrin.h>
  660. #else
  661. #include <ia32intrin.h>
  662. #endif
  663. #endif
  664. #endif
  665. #if JUCE_MSVC && JUCE_DEBUG
  666. #include <crtdbg.h>
  667. #endif
  668. #if JUCE_MSVC
  669. #include <malloc.h>
  670. #pragma warning (pop)
  671. #if ! JUCE_PUBLIC_INCLUDES
  672. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  673. #endif
  674. #endif
  675. #if JUCE_ANDROID
  676. #include <sys/atomics.h>
  677. #include <byteswap.h>
  678. #endif
  679. // DLL building settings on Win32
  680. #if JUCE_MSVC
  681. #ifdef JUCE_DLL_BUILD
  682. #define JUCE_API __declspec (dllexport)
  683. #pragma warning (disable: 4251)
  684. #elif defined (JUCE_DLL)
  685. #define JUCE_API __declspec (dllimport)
  686. #pragma warning (disable: 4251)
  687. #endif
  688. #ifdef __INTEL_COMPILER
  689. #pragma warning (disable: 1125) // (virtual override warning)
  690. #endif
  691. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  692. #ifdef JUCE_DLL_BUILD
  693. #define JUCE_API __attribute__ ((visibility("default")))
  694. #endif
  695. #endif
  696. #ifndef JUCE_API
  697. /** This macro is added to all juce public class declarations. */
  698. #define JUCE_API
  699. #endif
  700. /** This macro is added to all juce public function declarations. */
  701. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  702. /** This turns on some non-essential bits of code that should prevent old code from compiling
  703. in cases where method signatures have changed, etc.
  704. */
  705. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  706. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  707. #endif
  708. // Now include some basics that are needed by most of the Juce classes...
  709. BEGIN_JUCE_NAMESPACE
  710. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  711. #if JUCE_LOG_ASSERTIONS
  712. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) noexcept;
  713. #endif
  714. /*** Start of inlined file: juce_Memory.h ***/
  715. #ifndef __JUCE_MEMORY_JUCEHEADER__
  716. #define __JUCE_MEMORY_JUCEHEADER__
  717. /*
  718. This file defines the various juce_malloc(), juce_free() macros that can be used in
  719. preference to the standard calls.
  720. None of this stuff is actually used in the library itself, and will probably be
  721. deprecated at some point in the future, to force everyone to use HeapBlock and other
  722. safer allocation methods.
  723. */
  724. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS && ! DOXYGEN
  725. #ifndef JUCE_DLL
  726. // Win32 debug non-DLL versions..
  727. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  728. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  729. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  730. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  731. #else
  732. // Win32 debug DLL versions..
  733. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  734. // way all juce calls in the DLL and in the host API will all use the same allocator.
  735. extern JUCE_API void* juce_DebugMalloc (int size, const char* file, int line);
  736. extern JUCE_API void* juce_DebugCalloc (int size, const char* file, int line);
  737. extern JUCE_API void* juce_DebugRealloc (void* block, int size, const char* file, int line);
  738. extern JUCE_API void juce_DebugFree (void* block);
  739. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  740. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  741. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  742. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  743. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  744. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  745. static void* operator new (size_t, void* p) { return p; } \
  746. static void operator delete (void* p) { juce_free (p); } \
  747. static void operator delete (void*, void*) {}
  748. #endif
  749. #elif defined (JUCE_DLL) && ! DOXYGEN
  750. // Win32 DLL (release) versions..
  751. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  752. // way all juce calls in the DLL and in the host API will all use the same allocator.
  753. extern JUCE_API void* juce_Malloc (int size);
  754. extern JUCE_API void* juce_Calloc (int size);
  755. extern JUCE_API void* juce_Realloc (void* block, int size);
  756. extern JUCE_API void juce_Free (void* block);
  757. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  758. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  759. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  760. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  761. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  762. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  763. static void* operator new (size_t, void* p) { return p; } \
  764. static void operator delete (void* p) { juce_free (p); } \
  765. static void operator delete (void*, void*) {}
  766. #else
  767. // Mac, Linux and Win32 (release) versions..
  768. /** This can be used instead of calling malloc directly.
  769. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  770. */
  771. #define juce_malloc(numBytes) malloc (numBytes)
  772. /** This can be used instead of calling calloc directly.
  773. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  774. */
  775. #define juce_calloc(numBytes) calloc (1, numBytes)
  776. /** This can be used instead of calling realloc directly.
  777. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  778. */
  779. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  780. /** This can be used instead of calling free directly.
  781. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  782. */
  783. #define juce_free(location) free (location)
  784. #endif
  785. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  786. use the JUCE_LEAK_DETECTOR instead.
  787. */
  788. #ifndef juce_UseDebuggingNewOperator
  789. #define juce_UseDebuggingNewOperator
  790. #endif
  791. #if JUCE_MSVC || DOXYGEN
  792. /** This is a compiler-independent way of declaring a variable as being thread-local.
  793. E.g.
  794. @code
  795. juce_ThreadLocal int myVariable;
  796. @endcode
  797. */
  798. #define juce_ThreadLocal __declspec(thread)
  799. #else
  800. #define juce_ThreadLocal __thread
  801. #endif
  802. #if JUCE_MINGW
  803. /** This allocator is not defined in mingw gcc. */
  804. #define alloca __builtin_alloca
  805. #endif
  806. /** Fills a block of memory with zeros. */
  807. inline void zeromem (void* memory, size_t numBytes) noexcept { memset (memory, 0, numBytes); }
  808. /** Overwrites a structure or object with zeros. */
  809. template <typename Type>
  810. inline void zerostruct (Type& structure) noexcept { memset (&structure, 0, sizeof (structure)); }
  811. /** Delete an object pointer, and sets the pointer to null.
  812. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  813. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  814. */
  815. template <typename Type>
  816. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = nullptr; }
  817. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  818. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  819. a specific number of bytes,
  820. */
  821. template <typename Type>
  822. inline Type* addBytesToPointer (Type* pointer, int bytes) noexcept { return (Type*) (((char*) pointer) + bytes); }
  823. #endif // __JUCE_MEMORY_JUCEHEADER__
  824. /*** End of inlined file: juce_Memory.h ***/
  825. /*** Start of inlined file: juce_MathsFunctions.h ***/
  826. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  827. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  828. /*
  829. This file sets up some handy mathematical typdefs and functions.
  830. */
  831. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  832. /** A platform-independent 8-bit signed integer type. */
  833. typedef signed char int8;
  834. /** A platform-independent 8-bit unsigned integer type. */
  835. typedef unsigned char uint8;
  836. /** A platform-independent 16-bit signed integer type. */
  837. typedef signed short int16;
  838. /** A platform-independent 16-bit unsigned integer type. */
  839. typedef unsigned short uint16;
  840. /** A platform-independent 32-bit signed integer type. */
  841. typedef signed int int32;
  842. /** A platform-independent 32-bit unsigned integer type. */
  843. typedef unsigned int uint32;
  844. #if JUCE_MSVC
  845. /** A platform-independent 64-bit integer type. */
  846. typedef __int64 int64;
  847. /** A platform-independent 64-bit unsigned integer type. */
  848. typedef unsigned __int64 uint64;
  849. /** A platform-independent macro for writing 64-bit literals, needed because
  850. different compilers have different syntaxes for this.
  851. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  852. GCC, or 0x1000000000 for MSVC.
  853. */
  854. #define literal64bit(longLiteral) ((__int64) longLiteral)
  855. #else
  856. /** A platform-independent 64-bit integer type. */
  857. typedef long long int64;
  858. /** A platform-independent 64-bit unsigned integer type. */
  859. typedef unsigned long long uint64;
  860. /** A platform-independent macro for writing 64-bit literals, needed because
  861. different compilers have different syntaxes for this.
  862. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  863. GCC, or 0x1000000000 for MSVC.
  864. */
  865. #define literal64bit(longLiteral) (longLiteral##LL)
  866. #endif
  867. #if JUCE_64BIT
  868. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  869. typedef int64 pointer_sized_int;
  870. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  871. typedef uint64 pointer_sized_uint;
  872. #elif JUCE_MSVC && ! JUCE_VC6
  873. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  874. typedef _W64 int pointer_sized_int;
  875. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  876. typedef _W64 unsigned int pointer_sized_uint;
  877. #else
  878. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  879. typedef int pointer_sized_int;
  880. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  881. typedef unsigned int pointer_sized_uint;
  882. #endif
  883. // Some indispensible min/max functions
  884. /** Returns the larger of two values. */
  885. template <typename Type>
  886. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  887. /** Returns the larger of three values. */
  888. template <typename Type>
  889. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  890. /** Returns the larger of four values. */
  891. template <typename Type>
  892. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  893. /** Returns the smaller of two values. */
  894. template <typename Type>
  895. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  896. /** Returns the smaller of three values. */
  897. template <typename Type>
  898. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  899. /** Returns the smaller of four values. */
  900. template <typename Type>
  901. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  902. /** Scans an array of values, returning the minimum value that it contains. */
  903. template <typename Type>
  904. const Type findMinimum (const Type* data, int numValues)
  905. {
  906. if (numValues <= 0)
  907. return Type();
  908. Type result (*data++);
  909. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  910. {
  911. const Type& v = *data++;
  912. if (v < result) result = v;
  913. }
  914. return result;
  915. }
  916. /** Scans an array of values, returning the minimum value that it contains. */
  917. template <typename Type>
  918. const Type findMaximum (const Type* values, int numValues)
  919. {
  920. if (numValues <= 0)
  921. return Type();
  922. Type result (*values++);
  923. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  924. {
  925. const Type& v = *values++;
  926. if (result > v) result = v;
  927. }
  928. return result;
  929. }
  930. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  931. template <typename Type>
  932. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  933. {
  934. if (numValues <= 0)
  935. {
  936. lowest = Type();
  937. highest = Type();
  938. }
  939. else
  940. {
  941. Type mn (*values++);
  942. Type mx (mn);
  943. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  944. {
  945. const Type& v = *values++;
  946. if (mx < v) mx = v;
  947. if (v < mn) mn = v;
  948. }
  949. lowest = mn;
  950. highest = mx;
  951. }
  952. }
  953. /** Constrains a value to keep it within a given range.
  954. This will check that the specified value lies between the lower and upper bounds
  955. specified, and if not, will return the nearest value that would be in-range. Effectively,
  956. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  957. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  958. the results will be unpredictable.
  959. @param lowerLimit the minimum value to return
  960. @param upperLimit the maximum value to return
  961. @param valueToConstrain the value to try to return
  962. @returns the closest value to valueToConstrain which lies between lowerLimit
  963. and upperLimit (inclusive)
  964. @see jlimit0To, jmin, jmax
  965. */
  966. template <typename Type>
  967. inline Type jlimit (const Type lowerLimit,
  968. const Type upperLimit,
  969. const Type valueToConstrain) noexcept
  970. {
  971. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  972. return (valueToConstrain < lowerLimit) ? lowerLimit
  973. : ((upperLimit < valueToConstrain) ? upperLimit
  974. : valueToConstrain);
  975. }
  976. /** Returns true if a value is at least zero, and also below a specified upper limit.
  977. This is basically a quicker way to write:
  978. @code valueToTest >= 0 && valueToTest < upperLimit
  979. @endcode
  980. */
  981. template <typename Type>
  982. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  983. {
  984. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  985. return Type() <= valueToTest && valueToTest < upperLimit;
  986. }
  987. #if ! JUCE_VC6
  988. template <>
  989. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  990. {
  991. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  992. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  993. }
  994. #endif
  995. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  996. This is basically a quicker way to write:
  997. @code valueToTest >= 0 && valueToTest <= upperLimit
  998. @endcode
  999. */
  1000. template <typename Type>
  1001. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  1002. {
  1003. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  1004. return Type() <= valueToTest && valueToTest <= upperLimit;
  1005. }
  1006. #if ! JUCE_VC6
  1007. template <>
  1008. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  1009. {
  1010. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  1011. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  1012. }
  1013. #endif
  1014. /** Handy function to swap two values. */
  1015. template <typename Type>
  1016. inline void swapVariables (Type& variable1, Type& variable2)
  1017. {
  1018. std::swap (variable1, variable2);
  1019. }
  1020. #if JUCE_VC6
  1021. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  1022. #else
  1023. /** Handy function for getting the number of elements in a simple const C array.
  1024. E.g.
  1025. @code
  1026. static int myArray[] = { 1, 2, 3 };
  1027. int numElements = numElementsInArray (myArray) // returns 3
  1028. @endcode
  1029. */
  1030. template <typename Type, int N>
  1031. inline int numElementsInArray (Type (&array)[N])
  1032. {
  1033. (void) array; // (required to avoid a spurious warning in MS compilers)
  1034. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  1035. return N;
  1036. }
  1037. #endif
  1038. // Some useful maths functions that aren't always present with all compilers and build settings.
  1039. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1040. that are provided by the various platforms and compilers. */
  1041. template <typename Type>
  1042. inline Type juce_hypot (Type a, Type b) noexcept
  1043. {
  1044. #if JUCE_WINDOWS
  1045. return static_cast <Type> (_hypot (a, b));
  1046. #else
  1047. return static_cast <Type> (hypot (a, b));
  1048. #endif
  1049. }
  1050. /** 64-bit abs function. */
  1051. inline int64 abs64 (const int64 n) noexcept
  1052. {
  1053. return (n >= 0) ? n : -n;
  1054. }
  1055. /** This templated negate function will negate pointers as well as integers */
  1056. template <typename Type>
  1057. inline Type juce_negate (Type n) noexcept
  1058. {
  1059. return sizeof (Type) == 1 ? (Type) -(signed char) n
  1060. : (sizeof (Type) == 2 ? (Type) -(short) n
  1061. : (sizeof (Type) == 4 ? (Type) -(int) n
  1062. : ((Type) -(int64) n)));
  1063. }
  1064. /** This templated negate function will negate pointers as well as integers */
  1065. template <typename Type>
  1066. inline Type* juce_negate (Type* n) noexcept
  1067. {
  1068. return (Type*) -(pointer_sized_int) n;
  1069. }
  1070. /** A predefined value for Pi, at double-precision.
  1071. @see float_Pi
  1072. */
  1073. const double double_Pi = 3.1415926535897932384626433832795;
  1074. /** A predefined value for Pi, at sngle-precision.
  1075. @see double_Pi
  1076. */
  1077. const float float_Pi = 3.14159265358979323846f;
  1078. /** The isfinite() method seems to vary between platforms, so this is a
  1079. platform-independent function for it.
  1080. */
  1081. template <typename FloatingPointType>
  1082. inline bool juce_isfinite (FloatingPointType value)
  1083. {
  1084. #if JUCE_WINDOWS
  1085. return _finite (value);
  1086. #elif JUCE_ANDROID
  1087. return isfinite (value);
  1088. #else
  1089. return std::isfinite (value);
  1090. #endif
  1091. }
  1092. /** Fast floating-point-to-integer conversion.
  1093. This is faster than using the normal c++ cast to convert a float to an int, and
  1094. it will round the value to the nearest integer, rather than rounding it down
  1095. like the normal cast does.
  1096. Note that this routine gets its speed at the expense of some accuracy, and when
  1097. rounding values whose floating point component is exactly 0.5, odd numbers and
  1098. even numbers will be rounded up or down differently.
  1099. */
  1100. template <typename FloatType>
  1101. inline int roundToInt (const FloatType value) noexcept
  1102. {
  1103. union { int asInt[2]; double asDouble; } n;
  1104. n.asDouble = ((double) value) + 6755399441055744.0;
  1105. #if JUCE_BIG_ENDIAN
  1106. return n.asInt [1];
  1107. #else
  1108. return n.asInt [0];
  1109. #endif
  1110. }
  1111. /** Fast floating-point-to-integer conversion.
  1112. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1113. fine for values above zero, but negative numbers are rounded the wrong way.
  1114. */
  1115. inline int roundToIntAccurate (const double value) noexcept
  1116. {
  1117. return roundToInt (value + 1.5e-8);
  1118. }
  1119. /** Fast floating-point-to-integer conversion.
  1120. This is faster than using the normal c++ cast to convert a double to an int, and
  1121. it will round the value to the nearest integer, rather than rounding it down
  1122. like the normal cast does.
  1123. Note that this routine gets its speed at the expense of some accuracy, and when
  1124. rounding values whose floating point component is exactly 0.5, odd numbers and
  1125. even numbers will be rounded up or down differently. For a more accurate conversion,
  1126. see roundDoubleToIntAccurate().
  1127. */
  1128. inline int roundDoubleToInt (const double value) noexcept
  1129. {
  1130. return roundToInt (value);
  1131. }
  1132. /** Fast floating-point-to-integer conversion.
  1133. This is faster than using the normal c++ cast to convert a float to an int, and
  1134. it will round the value to the nearest integer, rather than rounding it down
  1135. like the normal cast does.
  1136. Note that this routine gets its speed at the expense of some accuracy, and when
  1137. rounding values whose floating point component is exactly 0.5, odd numbers and
  1138. even numbers will be rounded up or down differently.
  1139. */
  1140. inline int roundFloatToInt (const float value) noexcept
  1141. {
  1142. return roundToInt (value);
  1143. }
  1144. /** This namespace contains a few template classes for helping work out class type variations.
  1145. */
  1146. namespace TypeHelpers
  1147. {
  1148. #if JUCE_VC8_OR_EARLIER
  1149. #define PARAMETER_TYPE(type) const type&
  1150. #else
  1151. /** The ParameterType struct is used to find the best type to use when passing some kind
  1152. of object as a parameter.
  1153. Of course, this is only likely to be useful in certain esoteric template situations.
  1154. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1155. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1156. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1157. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1158. pass-by-value, but passing objects as a const reference, to avoid copying.
  1159. */
  1160. template <typename Type> struct ParameterType { typedef const Type& type; };
  1161. #if ! DOXYGEN
  1162. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1163. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1164. template <> struct ParameterType <char> { typedef char type; };
  1165. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1166. template <> struct ParameterType <short> { typedef short type; };
  1167. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1168. template <> struct ParameterType <int> { typedef int type; };
  1169. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1170. template <> struct ParameterType <long> { typedef long type; };
  1171. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1172. template <> struct ParameterType <int64> { typedef int64 type; };
  1173. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1174. template <> struct ParameterType <bool> { typedef bool type; };
  1175. template <> struct ParameterType <float> { typedef float type; };
  1176. template <> struct ParameterType <double> { typedef double type; };
  1177. #endif
  1178. /** A helpful macro to simplify the use of the ParameterType template.
  1179. @see ParameterType
  1180. */
  1181. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1182. #endif
  1183. }
  1184. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1185. /*** End of inlined file: juce_MathsFunctions.h ***/
  1186. /*** Start of inlined file: juce_ByteOrder.h ***/
  1187. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1188. #define __JUCE_BYTEORDER_JUCEHEADER__
  1189. /** Contains static methods for converting the byte order between different
  1190. endiannesses.
  1191. */
  1192. class JUCE_API ByteOrder
  1193. {
  1194. public:
  1195. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1196. static uint16 swap (uint16 value);
  1197. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1198. static uint32 swap (uint32 value);
  1199. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1200. static uint64 swap (uint64 value);
  1201. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1202. static uint16 swapIfBigEndian (uint16 value);
  1203. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1204. static uint32 swapIfBigEndian (uint32 value);
  1205. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1206. static uint64 swapIfBigEndian (uint64 value);
  1207. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1208. static uint16 swapIfLittleEndian (uint16 value);
  1209. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1210. static uint32 swapIfLittleEndian (uint32 value);
  1211. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1212. static uint64 swapIfLittleEndian (uint64 value);
  1213. /** Turns 4 bytes into a little-endian integer. */
  1214. static uint32 littleEndianInt (const void* bytes);
  1215. /** Turns 2 bytes into a little-endian integer. */
  1216. static uint16 littleEndianShort (const void* bytes);
  1217. /** Turns 4 bytes into a big-endian integer. */
  1218. static uint32 bigEndianInt (const void* bytes);
  1219. /** Turns 2 bytes into a big-endian integer. */
  1220. static uint16 bigEndianShort (const void* bytes);
  1221. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1222. static int littleEndian24Bit (const char* bytes);
  1223. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1224. static int bigEndian24Bit (const char* bytes);
  1225. /** Copies a 24-bit number to 3 little-endian bytes. */
  1226. static void littleEndian24BitToChars (int value, char* destBytes);
  1227. /** Copies a 24-bit number to 3 big-endian bytes. */
  1228. static void bigEndian24BitToChars (int value, char* destBytes);
  1229. /** Returns true if the current CPU is big-endian. */
  1230. static bool isBigEndian();
  1231. private:
  1232. ByteOrder();
  1233. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1234. };
  1235. #if JUCE_USE_INTRINSICS
  1236. #pragma intrinsic (_byteswap_ulong)
  1237. #endif
  1238. inline uint16 ByteOrder::swap (uint16 n)
  1239. {
  1240. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1241. return static_cast <uint16> (_byteswap_ushort (n));
  1242. #else
  1243. return static_cast <uint16> ((n << 8) | (n >> 8));
  1244. #endif
  1245. }
  1246. inline uint32 ByteOrder::swap (uint32 n)
  1247. {
  1248. #if JUCE_MAC || JUCE_IOS
  1249. return OSSwapInt32 (n);
  1250. #elif JUCE_GCC && JUCE_INTEL
  1251. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1252. return n;
  1253. #elif JUCE_USE_INTRINSICS
  1254. return _byteswap_ulong (n);
  1255. #elif JUCE_MSVC
  1256. __asm {
  1257. mov eax, n
  1258. bswap eax
  1259. mov n, eax
  1260. }
  1261. return n;
  1262. #elif JUCE_ANDROID
  1263. return bswap_32 (n);
  1264. #else
  1265. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1266. #endif
  1267. }
  1268. inline uint64 ByteOrder::swap (uint64 value)
  1269. {
  1270. #if JUCE_MAC || JUCE_IOS
  1271. return OSSwapInt64 (value);
  1272. #elif JUCE_USE_INTRINSICS
  1273. return _byteswap_uint64 (value);
  1274. #else
  1275. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1276. #endif
  1277. }
  1278. #if JUCE_LITTLE_ENDIAN
  1279. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1280. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1281. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1282. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1283. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1284. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1285. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1286. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1287. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1288. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1289. inline bool ByteOrder::isBigEndian() { return false; }
  1290. #else
  1291. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1292. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1293. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1294. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1295. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1296. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1297. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1298. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1299. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1300. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1301. inline bool ByteOrder::isBigEndian() { return true; }
  1302. #endif
  1303. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1304. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1305. 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); }
  1306. 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); }
  1307. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1308. /*** End of inlined file: juce_ByteOrder.h ***/
  1309. /*** Start of inlined file: juce_Logger.h ***/
  1310. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1311. #define __JUCE_LOGGER_JUCEHEADER__
  1312. /*** Start of inlined file: juce_String.h ***/
  1313. #ifndef __JUCE_STRING_JUCEHEADER__
  1314. #define __JUCE_STRING_JUCEHEADER__
  1315. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1316. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1317. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1318. #if JUCE_WINDOWS && ! DOXYGEN
  1319. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1320. #define JUCE_NATIVE_WCHAR_IS_UTF16 1
  1321. #define JUCE_NATIVE_WCHAR_IS_UTF32 0
  1322. #else
  1323. /** This macro will be set to 1 if the compiler's native wchar_t is an 8-bit type. */
  1324. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1325. /** This macro will be set to 1 if the compiler's native wchar_t is a 16-bit type. */
  1326. #define JUCE_NATIVE_WCHAR_IS_UTF16 0
  1327. /** This macro will be set to 1 if the compiler's native wchar_t is a 32-bit type. */
  1328. #define JUCE_NATIVE_WCHAR_IS_UTF32 1
  1329. #endif
  1330. #if JUCE_NATIVE_WCHAR_IS_UTF32 || DOXYGEN
  1331. /** A platform-independent 32-bit unicode character type. */
  1332. typedef wchar_t juce_wchar;
  1333. #else
  1334. typedef uint32 juce_wchar;
  1335. #endif
  1336. /** This macro is deprecated, but preserved for compatibility with old code.*/
  1337. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1338. #if ! JUCE_DONT_DEFINE_MACROS
  1339. /** The 'T' macro is an alternative for using the "L" prefix in front of a string literal.
  1340. This macro is deprectated, but kept here for compatibility with old code. The best (i.e.
  1341. most portable) way to encode your string literals is just as standard 8-bit strings, but
  1342. using escaped utf-8 character codes for extended characters.
  1343. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1344. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1345. the juce/src directory) to avoid defining this macro. See the comments in
  1346. juce_withoutMacros.h for more info.
  1347. */
  1348. #define T(stringLiteral) JUCE_T(stringLiteral)
  1349. #endif
  1350. #undef max
  1351. #undef min
  1352. /**
  1353. A set of methods for manipulating characters and character strings.
  1354. These are defined as wrappers around the basic C string handlers, to provide
  1355. a clean, cross-platform layer, (because various platforms differ in the
  1356. range of C library calls that they provide).
  1357. @see String
  1358. */
  1359. class JUCE_API CharacterFunctions
  1360. {
  1361. public:
  1362. static juce_wchar toUpperCase (juce_wchar character) noexcept;
  1363. static juce_wchar toLowerCase (juce_wchar character) noexcept;
  1364. static bool isUpperCase (juce_wchar character) noexcept;
  1365. static bool isLowerCase (juce_wchar character) noexcept;
  1366. static bool isWhitespace (char character) noexcept;
  1367. static bool isWhitespace (juce_wchar character) noexcept;
  1368. static bool isDigit (char character) noexcept;
  1369. static bool isDigit (juce_wchar character) noexcept;
  1370. static bool isLetter (char character) noexcept;
  1371. static bool isLetter (juce_wchar character) noexcept;
  1372. static bool isLetterOrDigit (char character) noexcept;
  1373. static bool isLetterOrDigit (juce_wchar character) noexcept;
  1374. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1375. static int getHexDigitValue (juce_wchar digit) noexcept;
  1376. template <typename CharPointerType>
  1377. static double readDoubleValue (CharPointerType& text) noexcept
  1378. {
  1379. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  1380. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  1381. int exponent = 0, decPointIndex = 0, digit = 0;
  1382. int lastDigit = 0, numSignificantDigits = 0;
  1383. bool isNegative = false, digitsFound = false;
  1384. const int maxSignificantDigits = 15 + 2;
  1385. text = text.findEndOfWhitespace();
  1386. juce_wchar c = *text;
  1387. switch (c)
  1388. {
  1389. case '-': isNegative = true; // fall-through..
  1390. case '+': c = *++text;
  1391. }
  1392. switch (c)
  1393. {
  1394. case 'n':
  1395. case 'N':
  1396. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1397. return std::numeric_limits<double>::quiet_NaN();
  1398. break;
  1399. case 'i':
  1400. case 'I':
  1401. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1402. return std::numeric_limits<double>::infinity();
  1403. break;
  1404. }
  1405. for (;;)
  1406. {
  1407. if (text.isDigit())
  1408. {
  1409. lastDigit = digit;
  1410. digit = text.getAndAdvance() - '0';
  1411. digitsFound = true;
  1412. if (decPointIndex != 0)
  1413. exponentAdjustment[1]++;
  1414. if (numSignificantDigits == 0 && digit == 0)
  1415. continue;
  1416. if (++numSignificantDigits > maxSignificantDigits)
  1417. {
  1418. if (digit > 5)
  1419. ++accumulator [decPointIndex];
  1420. else if (digit == 5 && (lastDigit & 1) != 0)
  1421. ++accumulator [decPointIndex];
  1422. if (decPointIndex > 0)
  1423. exponentAdjustment[1]--;
  1424. else
  1425. exponentAdjustment[0]++;
  1426. while (text.isDigit())
  1427. {
  1428. ++text;
  1429. if (decPointIndex == 0)
  1430. exponentAdjustment[0]++;
  1431. }
  1432. }
  1433. else
  1434. {
  1435. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1436. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1437. {
  1438. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1439. + accumulator [decPointIndex];
  1440. accumulator [decPointIndex] = 0;
  1441. exponentAccumulator [decPointIndex] = 0;
  1442. }
  1443. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1444. exponentAccumulator [decPointIndex]++;
  1445. }
  1446. }
  1447. else if (decPointIndex == 0 && *text == '.')
  1448. {
  1449. ++text;
  1450. decPointIndex = 1;
  1451. if (numSignificantDigits > maxSignificantDigits)
  1452. {
  1453. while (text.isDigit())
  1454. ++text;
  1455. break;
  1456. }
  1457. }
  1458. else
  1459. {
  1460. break;
  1461. }
  1462. }
  1463. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1464. if (decPointIndex != 0)
  1465. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1466. c = *text;
  1467. if ((c == 'e' || c == 'E') && digitsFound)
  1468. {
  1469. bool negativeExponent = false;
  1470. switch (*++text)
  1471. {
  1472. case '-': negativeExponent = true; // fall-through..
  1473. case '+': ++text;
  1474. }
  1475. while (text.isDigit())
  1476. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1477. if (negativeExponent)
  1478. exponent = -exponent;
  1479. }
  1480. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1481. if (decPointIndex != 0)
  1482. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1483. return isNegative ? -r : r;
  1484. }
  1485. template <typename CharPointerType>
  1486. static double getDoubleValue (const CharPointerType& text) noexcept
  1487. {
  1488. CharPointerType t (text);
  1489. return readDoubleValue (t);
  1490. }
  1491. template <typename IntType, typename CharPointerType>
  1492. static IntType getIntValue (const CharPointerType& text) noexcept
  1493. {
  1494. IntType v = 0;
  1495. CharPointerType s (text.findEndOfWhitespace());
  1496. const bool isNeg = *s == '-';
  1497. if (isNeg)
  1498. ++s;
  1499. for (;;)
  1500. {
  1501. const juce_wchar c = s.getAndAdvance();
  1502. if (c >= '0' && c <= '9')
  1503. v = v * 10 + (IntType) (c - '0');
  1504. else
  1505. break;
  1506. }
  1507. return isNeg ? -v : v;
  1508. }
  1509. template <typename CharPointerType>
  1510. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) noexcept
  1511. {
  1512. size_t len = 0;
  1513. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  1514. ++len;
  1515. return len;
  1516. }
  1517. template <typename CharPointerType>
  1518. static size_t lengthUpTo (CharPointerType start, const CharPointerType& end) noexcept
  1519. {
  1520. size_t len = 0;
  1521. while (start < end && start.getAndAdvance() != 0)
  1522. ++len;
  1523. return len;
  1524. }
  1525. template <typename DestCharPointerType, typename SrcCharPointerType>
  1526. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) noexcept
  1527. {
  1528. for (;;)
  1529. {
  1530. const juce_wchar c = src.getAndAdvance();
  1531. if (c == 0)
  1532. break;
  1533. dest.write (c);
  1534. }
  1535. dest.writeNull();
  1536. }
  1537. template <typename DestCharPointerType, typename SrcCharPointerType>
  1538. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) noexcept
  1539. {
  1540. int numBytesDone = 0;
  1541. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1542. for (;;)
  1543. {
  1544. const juce_wchar c = src.getAndAdvance();
  1545. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1546. maxBytes -= bytesNeeded;
  1547. if (c == 0 || maxBytes < 0)
  1548. break;
  1549. numBytesDone += bytesNeeded;
  1550. dest.write (c);
  1551. }
  1552. dest.writeNull();
  1553. return numBytesDone;
  1554. }
  1555. template <typename DestCharPointerType, typename SrcCharPointerType>
  1556. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) noexcept
  1557. {
  1558. while (--maxChars > 0)
  1559. {
  1560. const juce_wchar c = src.getAndAdvance();
  1561. if (c == 0)
  1562. break;
  1563. dest.write (c);
  1564. }
  1565. dest.writeNull();
  1566. }
  1567. template <typename CharPointerType1, typename CharPointerType2>
  1568. static int compare (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1569. {
  1570. for (;;)
  1571. {
  1572. const int c1 = (int) s1.getAndAdvance();
  1573. const int c2 = (int) s2.getAndAdvance();
  1574. const int diff = c1 - c2;
  1575. if (diff != 0)
  1576. return diff < 0 ? -1 : 1;
  1577. else if (c1 == 0)
  1578. break;
  1579. }
  1580. return 0;
  1581. }
  1582. template <typename CharPointerType1, typename CharPointerType2>
  1583. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1584. {
  1585. while (--maxChars >= 0)
  1586. {
  1587. const int c1 = (int) s1.getAndAdvance();
  1588. const int c2 = (int) s2.getAndAdvance();
  1589. const int diff = c1 - c2;
  1590. if (diff != 0)
  1591. return diff < 0 ? -1 : 1;
  1592. else if (c1 == 0)
  1593. break;
  1594. }
  1595. return 0;
  1596. }
  1597. template <typename CharPointerType1, typename CharPointerType2>
  1598. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1599. {
  1600. for (;;)
  1601. {
  1602. int c1 = s1.toUpperCase();
  1603. int c2 = s2.toUpperCase();
  1604. ++s1;
  1605. ++s2;
  1606. const int diff = c1 - c2;
  1607. if (diff != 0)
  1608. return diff < 0 ? -1 : 1;
  1609. else if (c1 == 0)
  1610. break;
  1611. }
  1612. return 0;
  1613. }
  1614. template <typename CharPointerType1, typename CharPointerType2>
  1615. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1616. {
  1617. while (--maxChars >= 0)
  1618. {
  1619. int c1 = s1.toUpperCase();
  1620. int c2 = s2.toUpperCase();
  1621. ++s1;
  1622. ++s2;
  1623. const int diff = c1 - c2;
  1624. if (diff != 0)
  1625. return diff < 0 ? -1 : 1;
  1626. else if (c1 == 0)
  1627. break;
  1628. }
  1629. return 0;
  1630. }
  1631. template <typename CharPointerType1, typename CharPointerType2>
  1632. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1633. {
  1634. int index = 0;
  1635. const int needleLength = (int) needle.length();
  1636. for (;;)
  1637. {
  1638. if (haystack.compareUpTo (needle, needleLength) == 0)
  1639. return index;
  1640. if (haystack.getAndAdvance() == 0)
  1641. return -1;
  1642. ++index;
  1643. }
  1644. }
  1645. template <typename CharPointerType1, typename CharPointerType2>
  1646. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1647. {
  1648. int index = 0;
  1649. const int needleLength = (int) needle.length();
  1650. for (;;)
  1651. {
  1652. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  1653. return index;
  1654. if (haystack.getAndAdvance() == 0)
  1655. return -1;
  1656. ++index;
  1657. }
  1658. }
  1659. template <typename Type>
  1660. static int indexOfChar (Type text, const juce_wchar charToFind) noexcept
  1661. {
  1662. int i = 0;
  1663. while (! text.isEmpty())
  1664. {
  1665. if (text.getAndAdvance() == charToFind)
  1666. return i;
  1667. ++i;
  1668. }
  1669. return -1;
  1670. }
  1671. template <typename Type>
  1672. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) noexcept
  1673. {
  1674. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1675. int i = 0;
  1676. while (! text.isEmpty())
  1677. {
  1678. if (text.toLowerCase() == charToFind)
  1679. return i;
  1680. ++text;
  1681. ++i;
  1682. }
  1683. return -1;
  1684. }
  1685. template <typename Type>
  1686. static Type findEndOfWhitespace (const Type& text) noexcept
  1687. {
  1688. Type p (text);
  1689. while (p.isWhitespace())
  1690. ++p;
  1691. return p;
  1692. }
  1693. template <typename Type>
  1694. static Type findEndOfToken (const Type& text, const Type& breakCharacters, const Type& quoteCharacters)
  1695. {
  1696. Type t (text);
  1697. juce_wchar currentQuoteChar = 0;
  1698. while (! t.isEmpty())
  1699. {
  1700. const juce_wchar c = t.getAndAdvance();
  1701. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  1702. {
  1703. --t;
  1704. break;
  1705. }
  1706. if (quoteCharacters.indexOf (c) >= 0)
  1707. {
  1708. if (currentQuoteChar == 0)
  1709. currentQuoteChar = c;
  1710. else if (currentQuoteChar == c)
  1711. currentQuoteChar = 0;
  1712. }
  1713. }
  1714. return t;
  1715. }
  1716. private:
  1717. static double mulexp10 (const double value, int exponent) noexcept;
  1718. };
  1719. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1720. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1721. #ifndef JUCE_STRING_UTF_TYPE
  1722. #define JUCE_STRING_UTF_TYPE 8
  1723. #endif
  1724. #if JUCE_MSVC
  1725. #pragma warning (push)
  1726. #pragma warning (disable: 4514 4996)
  1727. #endif
  1728. /*** Start of inlined file: juce_Atomic.h ***/
  1729. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1730. #define __JUCE_ATOMIC_JUCEHEADER__
  1731. /**
  1732. Simple class to hold a primitive value and perform atomic operations on it.
  1733. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1734. There are methods to perform most of the basic atomic operations.
  1735. */
  1736. template <typename Type>
  1737. class Atomic
  1738. {
  1739. public:
  1740. /** Creates a new value, initialised to zero. */
  1741. inline Atomic() noexcept
  1742. : value (0)
  1743. {
  1744. }
  1745. /** Creates a new value, with a given initial value. */
  1746. inline Atomic (const Type initialValue) noexcept
  1747. : value (initialValue)
  1748. {
  1749. }
  1750. /** Copies another value (atomically). */
  1751. inline Atomic (const Atomic& other) noexcept
  1752. : value (other.get())
  1753. {
  1754. }
  1755. /** Destructor. */
  1756. inline ~Atomic() noexcept
  1757. {
  1758. // This class can only be used for types which are 32 or 64 bits in size.
  1759. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1760. }
  1761. /** Atomically reads and returns the current value. */
  1762. Type get() const noexcept;
  1763. /** Copies another value onto this one (atomically). */
  1764. inline Atomic& operator= (const Atomic& other) noexcept { exchange (other.get()); return *this; }
  1765. /** Copies another value onto this one (atomically). */
  1766. inline Atomic& operator= (const Type newValue) noexcept { exchange (newValue); return *this; }
  1767. /** Atomically sets the current value. */
  1768. void set (Type newValue) noexcept { exchange (newValue); }
  1769. /** Atomically sets the current value, returning the value that was replaced. */
  1770. Type exchange (Type value) noexcept;
  1771. /** Atomically adds a number to this value, returning the new value. */
  1772. Type operator+= (Type amountToAdd) noexcept;
  1773. /** Atomically subtracts a number from this value, returning the new value. */
  1774. Type operator-= (Type amountToSubtract) noexcept;
  1775. /** Atomically increments this value, returning the new value. */
  1776. Type operator++() noexcept;
  1777. /** Atomically decrements this value, returning the new value. */
  1778. Type operator--() noexcept;
  1779. /** Atomically compares this value with a target value, and if it is equal, sets
  1780. this to be equal to a new value.
  1781. This operation is the atomic equivalent of doing this:
  1782. @code
  1783. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1784. {
  1785. if (get() == valueToCompare)
  1786. {
  1787. set (newValue);
  1788. return true;
  1789. }
  1790. return false;
  1791. }
  1792. @endcode
  1793. @returns true if the comparison was true and the value was replaced; false if
  1794. the comparison failed and the value was left unchanged.
  1795. @see compareAndSetValue
  1796. */
  1797. bool compareAndSetBool (Type newValue, Type valueToCompare) noexcept;
  1798. /** Atomically compares this value with a target value, and if it is equal, sets
  1799. this to be equal to a new value.
  1800. This operation is the atomic equivalent of doing this:
  1801. @code
  1802. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1803. {
  1804. Type oldValue = get();
  1805. if (oldValue == valueToCompare)
  1806. set (newValue);
  1807. return oldValue;
  1808. }
  1809. @endcode
  1810. @returns the old value before it was changed.
  1811. @see compareAndSetBool
  1812. */
  1813. Type compareAndSetValue (Type newValue, Type valueToCompare) noexcept;
  1814. /** Implements a memory read/write barrier. */
  1815. static void memoryBarrier() noexcept;
  1816. #if JUCE_64BIT
  1817. JUCE_ALIGN (8)
  1818. #else
  1819. JUCE_ALIGN (4)
  1820. #endif
  1821. /** The raw value that this class operates on.
  1822. This is exposed publically in case you need to manipulate it directly
  1823. for performance reasons.
  1824. */
  1825. volatile Type value;
  1826. private:
  1827. static inline Type castFrom32Bit (int32 value) noexcept { return *(Type*) &value; }
  1828. static inline Type castFrom64Bit (int64 value) noexcept { return *(Type*) &value; }
  1829. static inline int32 castTo32Bit (Type value) noexcept { return *(int32*) &value; }
  1830. static inline int64 castTo64Bit (Type value) noexcept { return *(int64*) &value; }
  1831. Type operator++ (int); // better to just use pre-increment with atomics..
  1832. Type operator-- (int);
  1833. };
  1834. /*
  1835. The following code is in the header so that the atomics can be inlined where possible...
  1836. */
  1837. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1838. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1839. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1840. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1841. #define JUCE_MAC_ATOMICS_VOLATILE
  1842. #else
  1843. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1844. #endif
  1845. #if JUCE_PPC || JUCE_IOS
  1846. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1847. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return *a += b; }
  1848. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return ++*a; }
  1849. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return --*a; }
  1850. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) noexcept
  1851. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1852. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1853. #endif
  1854. #elif JUCE_ANDROID
  1855. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1856. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1857. #elif JUCE_GCC
  1858. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1859. #if JUCE_IOS
  1860. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1861. #endif
  1862. #else
  1863. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1864. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1865. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1866. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1867. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1868. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1869. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1870. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1871. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1872. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1873. #define juce_MemoryBarrier _ReadWriteBarrier
  1874. #else
  1875. // (these are defined in juce_win32_Threads.cpp)
  1876. long juce_InterlockedExchange (volatile long* a, long b) noexcept;
  1877. long juce_InterlockedIncrement (volatile long* a) noexcept;
  1878. long juce_InterlockedDecrement (volatile long* a) noexcept;
  1879. long juce_InterlockedExchangeAdd (volatile long* a, long b) noexcept;
  1880. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) noexcept;
  1881. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) noexcept;
  1882. inline void juce_MemoryBarrier() noexcept { long x = 0; juce_InterlockedIncrement (&x); }
  1883. #endif
  1884. #if JUCE_64BIT
  1885. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1886. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1887. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1888. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1889. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1890. #else
  1891. // None of these atomics are available in a 32-bit Windows build!!
  1892. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a += b; return old; }
  1893. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a = b; return old; }
  1894. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) noexcept { jassertfalse; return ++*a; }
  1895. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) noexcept { jassertfalse; return --*a; }
  1896. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1897. #endif
  1898. #endif
  1899. #if JUCE_MSVC
  1900. #pragma warning (push)
  1901. #pragma warning (disable: 4311) // (truncation warning)
  1902. #endif
  1903. template <typename Type>
  1904. inline Type Atomic<Type>::get() const noexcept
  1905. {
  1906. #if JUCE_ATOMICS_MAC
  1907. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1908. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1909. #elif JUCE_ATOMICS_WINDOWS
  1910. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1911. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1912. #elif JUCE_ATOMICS_ANDROID
  1913. return value;
  1914. #elif JUCE_ATOMICS_GCC
  1915. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1916. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1917. #endif
  1918. }
  1919. template <typename Type>
  1920. inline Type Atomic<Type>::exchange (const Type newValue) noexcept
  1921. {
  1922. #if JUCE_ATOMICS_ANDROID
  1923. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1924. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1925. Type currentVal = value;
  1926. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1927. return currentVal;
  1928. #elif JUCE_ATOMICS_WINDOWS
  1929. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1930. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1931. #endif
  1932. }
  1933. template <typename Type>
  1934. inline Type Atomic<Type>::operator+= (const Type amountToAdd) noexcept
  1935. {
  1936. #if JUCE_ATOMICS_MAC
  1937. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1938. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1939. #elif JUCE_ATOMICS_WINDOWS
  1940. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1941. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1942. #elif JUCE_ATOMICS_ANDROID
  1943. for (;;)
  1944. {
  1945. const Type oldValue (value);
  1946. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1947. if (compareAndSetBool (newValue, oldValue))
  1948. return newValue;
  1949. }
  1950. #elif JUCE_ATOMICS_GCC
  1951. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1952. #endif
  1953. }
  1954. template <typename Type>
  1955. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) noexcept
  1956. {
  1957. return operator+= (juce_negate (amountToSubtract));
  1958. }
  1959. template <typename Type>
  1960. inline Type Atomic<Type>::operator++() noexcept
  1961. {
  1962. #if JUCE_ATOMICS_MAC
  1963. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1964. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1965. #elif JUCE_ATOMICS_WINDOWS
  1966. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1967. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1968. #elif JUCE_ATOMICS_ANDROID
  1969. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1970. #elif JUCE_ATOMICS_GCC
  1971. return (Type) __sync_add_and_fetch (&value, 1);
  1972. #endif
  1973. }
  1974. template <typename Type>
  1975. inline Type Atomic<Type>::operator--() noexcept
  1976. {
  1977. #if JUCE_ATOMICS_MAC
  1978. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1979. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1980. #elif JUCE_ATOMICS_WINDOWS
  1981. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1982. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1983. #elif JUCE_ATOMICS_ANDROID
  1984. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1985. #elif JUCE_ATOMICS_GCC
  1986. return (Type) __sync_add_and_fetch (&value, -1);
  1987. #endif
  1988. }
  1989. template <typename Type>
  1990. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) noexcept
  1991. {
  1992. #if JUCE_ATOMICS_MAC
  1993. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1994. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1995. #elif JUCE_ATOMICS_WINDOWS
  1996. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1997. #elif JUCE_ATOMICS_ANDROID
  1998. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1999. #elif JUCE_ATOMICS_GCC
  2000. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  2001. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  2002. #endif
  2003. }
  2004. template <typename Type>
  2005. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) noexcept
  2006. {
  2007. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  2008. for (;;) // Annoying workaround for only having a bool CAS operation..
  2009. {
  2010. if (compareAndSetBool (newValue, valueToCompare))
  2011. return valueToCompare;
  2012. const Type result = value;
  2013. if (result != valueToCompare)
  2014. return result;
  2015. }
  2016. #elif JUCE_ATOMICS_WINDOWS
  2017. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  2018. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  2019. #elif JUCE_ATOMICS_GCC
  2020. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  2021. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  2022. #endif
  2023. }
  2024. template <typename Type>
  2025. inline void Atomic<Type>::memoryBarrier() noexcept
  2026. {
  2027. #if JUCE_ATOMICS_MAC
  2028. OSMemoryBarrier();
  2029. #elif JUCE_ATOMICS_GCC
  2030. __sync_synchronize();
  2031. #elif JUCE_ATOMICS_WINDOWS
  2032. juce_MemoryBarrier();
  2033. #endif
  2034. }
  2035. #if JUCE_MSVC
  2036. #pragma warning (pop)
  2037. #endif
  2038. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2039. /*** End of inlined file: juce_Atomic.h ***/
  2040. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2041. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2042. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2043. /**
  2044. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2045. various methods to operate on the data.
  2046. @see CharPointer_UTF16, CharPointer_UTF32
  2047. */
  2048. class CharPointer_UTF8
  2049. {
  2050. public:
  2051. typedef char CharType;
  2052. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) noexcept
  2053. : data (const_cast <CharType*> (rawPointer))
  2054. {
  2055. }
  2056. inline CharPointer_UTF8 (const CharPointer_UTF8& other) noexcept
  2057. : data (other.data)
  2058. {
  2059. }
  2060. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) noexcept
  2061. {
  2062. data = other.data;
  2063. return *this;
  2064. }
  2065. inline CharPointer_UTF8& operator= (const CharType* text) noexcept
  2066. {
  2067. data = const_cast <CharType*> (text);
  2068. return *this;
  2069. }
  2070. /** This is a pointer comparison, it doesn't compare the actual text. */
  2071. inline bool operator== (const CharPointer_UTF8& other) const noexcept { return data == other.data; }
  2072. inline bool operator!= (const CharPointer_UTF8& other) const noexcept { return data != other.data; }
  2073. inline bool operator<= (const CharPointer_UTF8& other) const noexcept { return data <= other.data; }
  2074. inline bool operator< (const CharPointer_UTF8& other) const noexcept { return data < other.data; }
  2075. inline bool operator>= (const CharPointer_UTF8& other) const noexcept { return data >= other.data; }
  2076. inline bool operator> (const CharPointer_UTF8& other) const noexcept { return data > other.data; }
  2077. /** Returns the address that this pointer is pointing to. */
  2078. inline CharType* getAddress() const noexcept { return data; }
  2079. /** Returns the address that this pointer is pointing to. */
  2080. inline operator const CharType*() const noexcept { return data; }
  2081. /** Returns true if this pointer is pointing to a null character. */
  2082. inline bool isEmpty() const noexcept { return *data == 0; }
  2083. /** Returns the unicode character that this pointer is pointing to. */
  2084. juce_wchar operator*() const noexcept
  2085. {
  2086. const signed char byte = (signed char) *data;
  2087. if (byte >= 0)
  2088. return byte;
  2089. uint32 n = (uint32) (uint8) byte;
  2090. uint32 mask = 0x7f;
  2091. uint32 bit = 0x40;
  2092. size_t numExtraValues = 0;
  2093. while ((n & bit) != 0 && bit > 0x10)
  2094. {
  2095. mask >>= 1;
  2096. ++numExtraValues;
  2097. bit >>= 1;
  2098. }
  2099. n &= mask;
  2100. for (size_t i = 1; i <= numExtraValues; ++i)
  2101. {
  2102. const juce_wchar nextByte = data [i];
  2103. if ((nextByte & 0xc0) != 0x80)
  2104. break;
  2105. n <<= 6;
  2106. n |= (nextByte & 0x3f);
  2107. }
  2108. return (juce_wchar) n;
  2109. }
  2110. /** Moves this pointer along to the next character in the string. */
  2111. CharPointer_UTF8& operator++() noexcept
  2112. {
  2113. const signed char n = (signed char) *data++;
  2114. if (n < 0)
  2115. {
  2116. juce_wchar bit = 0x40;
  2117. while ((n & bit) != 0 && bit > 0x8)
  2118. {
  2119. ++data;
  2120. bit >>= 1;
  2121. }
  2122. }
  2123. return *this;
  2124. }
  2125. /** Moves this pointer back to the previous character in the string. */
  2126. CharPointer_UTF8& operator--() noexcept
  2127. {
  2128. const char n = *--data;
  2129. if ((n & 0xc0) == 0xc0)
  2130. {
  2131. int count = 3;
  2132. do
  2133. {
  2134. --data;
  2135. }
  2136. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2137. }
  2138. return *this;
  2139. }
  2140. /** Returns the character that this pointer is currently pointing to, and then
  2141. advances the pointer to point to the next character. */
  2142. juce_wchar getAndAdvance() noexcept
  2143. {
  2144. const signed char byte = (signed char) *data++;
  2145. if (byte >= 0)
  2146. return byte;
  2147. uint32 n = (uint32) (uint8) byte;
  2148. uint32 mask = 0x7f;
  2149. uint32 bit = 0x40;
  2150. int numExtraValues = 0;
  2151. while ((n & bit) != 0 && bit > 0x8)
  2152. {
  2153. mask >>= 1;
  2154. ++numExtraValues;
  2155. bit >>= 1;
  2156. }
  2157. n &= mask;
  2158. while (--numExtraValues >= 0)
  2159. {
  2160. const uint32 nextByte = (uint32) (uint8) *data++;
  2161. if ((nextByte & 0xc0) != 0x80)
  2162. break;
  2163. n <<= 6;
  2164. n |= (nextByte & 0x3f);
  2165. }
  2166. return (juce_wchar) n;
  2167. }
  2168. /** Moves this pointer along to the next character in the string. */
  2169. CharPointer_UTF8 operator++ (int) noexcept
  2170. {
  2171. CharPointer_UTF8 temp (*this);
  2172. ++*this;
  2173. return temp;
  2174. }
  2175. /** Moves this pointer forwards by the specified number of characters. */
  2176. void operator+= (int numToSkip) noexcept
  2177. {
  2178. if (numToSkip < 0)
  2179. {
  2180. while (++numToSkip <= 0)
  2181. --*this;
  2182. }
  2183. else
  2184. {
  2185. while (--numToSkip >= 0)
  2186. ++*this;
  2187. }
  2188. }
  2189. /** Moves this pointer backwards by the specified number of characters. */
  2190. void operator-= (int numToSkip) noexcept
  2191. {
  2192. operator+= (-numToSkip);
  2193. }
  2194. /** Returns the character at a given character index from the start of the string. */
  2195. juce_wchar operator[] (int characterIndex) const noexcept
  2196. {
  2197. CharPointer_UTF8 p (*this);
  2198. p += characterIndex;
  2199. return *p;
  2200. }
  2201. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2202. CharPointer_UTF8 operator+ (int numToSkip) const noexcept
  2203. {
  2204. CharPointer_UTF8 p (*this);
  2205. p += numToSkip;
  2206. return p;
  2207. }
  2208. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2209. CharPointer_UTF8 operator- (int numToSkip) const noexcept
  2210. {
  2211. CharPointer_UTF8 p (*this);
  2212. p += -numToSkip;
  2213. return p;
  2214. }
  2215. /** Returns the number of characters in this string. */
  2216. size_t length() const noexcept
  2217. {
  2218. const CharType* d = data;
  2219. size_t count = 0;
  2220. for (;;)
  2221. {
  2222. const uint32 n = (uint32) (uint8) *d++;
  2223. if ((n & 0x80) != 0)
  2224. {
  2225. uint32 bit = 0x40;
  2226. while ((n & bit) != 0)
  2227. {
  2228. ++d;
  2229. bit >>= 1;
  2230. if (bit == 0)
  2231. break; // illegal utf-8 sequence
  2232. }
  2233. }
  2234. else if (n == 0)
  2235. break;
  2236. ++count;
  2237. }
  2238. return count;
  2239. }
  2240. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2241. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2242. {
  2243. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2244. }
  2245. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2246. size_t lengthUpTo (const CharPointer_UTF8& end) const noexcept
  2247. {
  2248. return CharacterFunctions::lengthUpTo (*this, end);
  2249. }
  2250. /** Returns the number of bytes that are used to represent this string.
  2251. This includes the terminating null character.
  2252. */
  2253. size_t sizeInBytes() const noexcept
  2254. {
  2255. return strlen (data) + 1;
  2256. }
  2257. /** Returns the number of bytes that would be needed to represent the given
  2258. unicode character in this encoding format.
  2259. */
  2260. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2261. {
  2262. size_t num = 1;
  2263. const uint32 c = (uint32) charToWrite;
  2264. if (c >= 0x80)
  2265. {
  2266. ++num;
  2267. if (c >= 0x800)
  2268. {
  2269. ++num;
  2270. if (c >= 0x10000)
  2271. ++num;
  2272. }
  2273. }
  2274. return num;
  2275. }
  2276. /** Returns the number of bytes that would be needed to represent the given
  2277. string in this encoding format.
  2278. The value returned does NOT include the terminating null character.
  2279. */
  2280. template <class CharPointer>
  2281. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2282. {
  2283. size_t count = 0;
  2284. juce_wchar n;
  2285. while ((n = text.getAndAdvance()) != 0)
  2286. count += getBytesRequiredFor (n);
  2287. return count;
  2288. }
  2289. /** Returns a pointer to the null character that terminates this string. */
  2290. CharPointer_UTF8 findTerminatingNull() const noexcept
  2291. {
  2292. return CharPointer_UTF8 (data + strlen (data));
  2293. }
  2294. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2295. void write (const juce_wchar charToWrite) noexcept
  2296. {
  2297. const uint32 c = (uint32) charToWrite;
  2298. if (c >= 0x80)
  2299. {
  2300. int numExtraBytes = 1;
  2301. if (c >= 0x800)
  2302. {
  2303. ++numExtraBytes;
  2304. if (c >= 0x10000)
  2305. ++numExtraBytes;
  2306. }
  2307. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2308. while (--numExtraBytes >= 0)
  2309. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2310. }
  2311. else
  2312. {
  2313. *data++ = (CharType) c;
  2314. }
  2315. }
  2316. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2317. inline void writeNull() const noexcept
  2318. {
  2319. *data = 0;
  2320. }
  2321. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2322. template <typename CharPointer>
  2323. void writeAll (const CharPointer& src) noexcept
  2324. {
  2325. CharacterFunctions::copyAll (*this, src);
  2326. }
  2327. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2328. void writeAll (const CharPointer_UTF8& src) noexcept
  2329. {
  2330. const CharType* s = src.data;
  2331. while ((*data = *s) != 0)
  2332. {
  2333. ++data;
  2334. ++s;
  2335. }
  2336. }
  2337. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2338. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2339. to the destination buffer before stopping.
  2340. */
  2341. template <typename CharPointer>
  2342. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2343. {
  2344. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2345. }
  2346. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2347. The maxChars parameter specifies the maximum number of characters that can be
  2348. written to the destination buffer before stopping (including the terminating null).
  2349. */
  2350. template <typename CharPointer>
  2351. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2352. {
  2353. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2354. }
  2355. /** Compares this string with another one. */
  2356. template <typename CharPointer>
  2357. int compare (const CharPointer& other) const noexcept
  2358. {
  2359. return CharacterFunctions::compare (*this, other);
  2360. }
  2361. /** Compares this string with another one, up to a specified number of characters. */
  2362. template <typename CharPointer>
  2363. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2364. {
  2365. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2366. }
  2367. /** Compares this string with another one. */
  2368. template <typename CharPointer>
  2369. int compareIgnoreCase (const CharPointer& other) const noexcept
  2370. {
  2371. return CharacterFunctions::compareIgnoreCase (*this, other);
  2372. }
  2373. /** Compares this string with another one. */
  2374. int compareIgnoreCase (const CharPointer_UTF8& other) const noexcept
  2375. {
  2376. #if JUCE_WINDOWS
  2377. return stricmp (data, other.data);
  2378. #else
  2379. return strcasecmp (data, other.data);
  2380. #endif
  2381. }
  2382. /** Compares this string with another one, up to a specified number of characters. */
  2383. template <typename CharPointer>
  2384. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2385. {
  2386. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2387. }
  2388. /** Compares this string with another one, up to a specified number of characters. */
  2389. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const noexcept
  2390. {
  2391. #if JUCE_WINDOWS
  2392. return strnicmp (data, other.data, maxChars);
  2393. #else
  2394. return strncasecmp (data, other.data, maxChars);
  2395. #endif
  2396. }
  2397. /** Returns the character index of a substring, or -1 if it isn't found. */
  2398. template <typename CharPointer>
  2399. int indexOf (const CharPointer& stringToFind) const noexcept
  2400. {
  2401. return CharacterFunctions::indexOf (*this, stringToFind);
  2402. }
  2403. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2404. int indexOf (const juce_wchar charToFind) const noexcept
  2405. {
  2406. return CharacterFunctions::indexOfChar (*this, charToFind);
  2407. }
  2408. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2409. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2410. {
  2411. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2412. : CharacterFunctions::indexOfChar (*this, charToFind);
  2413. }
  2414. /** Returns true if the first character of this string is whitespace. */
  2415. bool isWhitespace() const noexcept { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2416. /** Returns true if the first character of this string is a digit. */
  2417. bool isDigit() const noexcept { return *data >= '0' && *data <= '9'; }
  2418. /** Returns true if the first character of this string is a letter. */
  2419. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2420. /** Returns true if the first character of this string is a letter or digit. */
  2421. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2422. /** Returns true if the first character of this string is upper-case. */
  2423. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2424. /** Returns true if the first character of this string is lower-case. */
  2425. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2426. /** Returns an upper-case version of the first character of this string. */
  2427. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2428. /** Returns a lower-case version of the first character of this string. */
  2429. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2430. /** Parses this string as a 32-bit integer. */
  2431. int getIntValue32() const noexcept { return atoi (data); }
  2432. /** Parses this string as a 64-bit integer. */
  2433. int64 getIntValue64() const noexcept
  2434. {
  2435. #if JUCE_LINUX || JUCE_ANDROID
  2436. return atoll (data);
  2437. #elif JUCE_WINDOWS
  2438. return _atoi64 (data);
  2439. #else
  2440. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2441. #endif
  2442. }
  2443. /** Parses this string as a floating point double. */
  2444. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2445. /** Returns the first non-whitespace character in the string. */
  2446. CharPointer_UTF8 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2447. /** Returns true if the given unicode character can be represented in this encoding. */
  2448. static bool canRepresent (juce_wchar character) noexcept
  2449. {
  2450. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2451. }
  2452. /** Returns true if this data contains a valid string in this encoding. */
  2453. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2454. {
  2455. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2456. {
  2457. const signed char byte = (signed char) *dataToTest;
  2458. if (byte < 0)
  2459. {
  2460. uint32 n = (uint32) (uint8) byte;
  2461. uint32 mask = 0x7f;
  2462. uint32 bit = 0x40;
  2463. int numExtraValues = 0;
  2464. while ((n & bit) != 0)
  2465. {
  2466. if (bit <= 0x10)
  2467. return false;
  2468. mask >>= 1;
  2469. ++numExtraValues;
  2470. bit >>= 1;
  2471. }
  2472. n &= mask;
  2473. while (--numExtraValues >= 0)
  2474. {
  2475. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2476. if ((nextByte & 0xc0) != 0x80)
  2477. return false;
  2478. }
  2479. }
  2480. }
  2481. return true;
  2482. }
  2483. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2484. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2485. {
  2486. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2487. }
  2488. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2489. enum
  2490. {
  2491. byteOrderMark1 = 0xef,
  2492. byteOrderMark2 = 0xbb,
  2493. byteOrderMark3 = 0xbf
  2494. };
  2495. private:
  2496. CharType* data;
  2497. };
  2498. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2499. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2500. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2501. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2502. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2503. /**
  2504. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2505. various methods to operate on the data.
  2506. @see CharPointer_UTF8, CharPointer_UTF32
  2507. */
  2508. class CharPointer_UTF16
  2509. {
  2510. public:
  2511. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2512. typedef wchar_t CharType;
  2513. #else
  2514. typedef int16 CharType;
  2515. #endif
  2516. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) noexcept
  2517. : data (const_cast <CharType*> (rawPointer))
  2518. {
  2519. }
  2520. inline CharPointer_UTF16 (const CharPointer_UTF16& other) noexcept
  2521. : data (other.data)
  2522. {
  2523. }
  2524. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) noexcept
  2525. {
  2526. data = other.data;
  2527. return *this;
  2528. }
  2529. inline CharPointer_UTF16& operator= (const CharType* text) noexcept
  2530. {
  2531. data = const_cast <CharType*> (text);
  2532. return *this;
  2533. }
  2534. /** This is a pointer comparison, it doesn't compare the actual text. */
  2535. inline bool operator== (const CharPointer_UTF16& other) const noexcept { return data == other.data; }
  2536. inline bool operator!= (const CharPointer_UTF16& other) const noexcept { return data != other.data; }
  2537. inline bool operator<= (const CharPointer_UTF16& other) const noexcept { return data <= other.data; }
  2538. inline bool operator< (const CharPointer_UTF16& other) const noexcept { return data < other.data; }
  2539. inline bool operator>= (const CharPointer_UTF16& other) const noexcept { return data >= other.data; }
  2540. inline bool operator> (const CharPointer_UTF16& other) const noexcept { return data > other.data; }
  2541. /** Returns the address that this pointer is pointing to. */
  2542. inline CharType* getAddress() const noexcept { return data; }
  2543. /** Returns the address that this pointer is pointing to. */
  2544. inline operator const CharType*() const noexcept { return data; }
  2545. /** Returns true if this pointer is pointing to a null character. */
  2546. inline bool isEmpty() const noexcept { return *data == 0; }
  2547. /** Returns the unicode character that this pointer is pointing to. */
  2548. juce_wchar operator*() const noexcept
  2549. {
  2550. uint32 n = (uint32) (uint16) *data;
  2551. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2552. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2553. return (juce_wchar) n;
  2554. }
  2555. /** Moves this pointer along to the next character in the string. */
  2556. CharPointer_UTF16& operator++() noexcept
  2557. {
  2558. const juce_wchar n = *data++;
  2559. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2560. ++data;
  2561. return *this;
  2562. }
  2563. /** Moves this pointer back to the previous character in the string. */
  2564. CharPointer_UTF16& operator--() noexcept
  2565. {
  2566. const juce_wchar n = *--data;
  2567. if (n >= 0xdc00 && n <= 0xdfff)
  2568. --data;
  2569. return *this;
  2570. }
  2571. /** Returns the character that this pointer is currently pointing to, and then
  2572. advances the pointer to point to the next character. */
  2573. juce_wchar getAndAdvance() noexcept
  2574. {
  2575. uint32 n = (uint32) (uint16) *data++;
  2576. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2577. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2578. return (juce_wchar) n;
  2579. }
  2580. /** Moves this pointer along to the next character in the string. */
  2581. CharPointer_UTF16 operator++ (int) noexcept
  2582. {
  2583. CharPointer_UTF16 temp (*this);
  2584. ++*this;
  2585. return temp;
  2586. }
  2587. /** Moves this pointer forwards by the specified number of characters. */
  2588. void operator+= (int numToSkip) noexcept
  2589. {
  2590. if (numToSkip < 0)
  2591. {
  2592. while (++numToSkip <= 0)
  2593. --*this;
  2594. }
  2595. else
  2596. {
  2597. while (--numToSkip >= 0)
  2598. ++*this;
  2599. }
  2600. }
  2601. /** Moves this pointer backwards by the specified number of characters. */
  2602. void operator-= (int numToSkip) noexcept
  2603. {
  2604. operator+= (-numToSkip);
  2605. }
  2606. /** Returns the character at a given character index from the start of the string. */
  2607. juce_wchar operator[] (const int characterIndex) const noexcept
  2608. {
  2609. CharPointer_UTF16 p (*this);
  2610. p += characterIndex;
  2611. return *p;
  2612. }
  2613. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2614. CharPointer_UTF16 operator+ (const int numToSkip) const noexcept
  2615. {
  2616. CharPointer_UTF16 p (*this);
  2617. p += numToSkip;
  2618. return p;
  2619. }
  2620. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2621. CharPointer_UTF16 operator- (const int numToSkip) const noexcept
  2622. {
  2623. CharPointer_UTF16 p (*this);
  2624. p += -numToSkip;
  2625. return p;
  2626. }
  2627. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2628. void write (juce_wchar charToWrite) noexcept
  2629. {
  2630. if (charToWrite >= 0x10000)
  2631. {
  2632. charToWrite -= 0x10000;
  2633. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2634. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2635. }
  2636. else
  2637. {
  2638. *data++ = (CharType) charToWrite;
  2639. }
  2640. }
  2641. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2642. inline void writeNull() const noexcept
  2643. {
  2644. *data = 0;
  2645. }
  2646. /** Returns the number of characters in this string. */
  2647. size_t length() const noexcept
  2648. {
  2649. const CharType* d = data;
  2650. size_t count = 0;
  2651. for (;;)
  2652. {
  2653. const int n = *d++;
  2654. if (n >= 0xd800 && n <= 0xdfff)
  2655. {
  2656. if (*d++ == 0)
  2657. break;
  2658. }
  2659. else if (n == 0)
  2660. break;
  2661. ++count;
  2662. }
  2663. return count;
  2664. }
  2665. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2666. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2667. {
  2668. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2669. }
  2670. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2671. size_t lengthUpTo (const CharPointer_UTF16& end) const noexcept
  2672. {
  2673. return CharacterFunctions::lengthUpTo (*this, end);
  2674. }
  2675. /** Returns the number of bytes that are used to represent this string.
  2676. This includes the terminating null character.
  2677. */
  2678. size_t sizeInBytes() const noexcept
  2679. {
  2680. return sizeof (CharType) * (findNullIndex (data) + 1);
  2681. }
  2682. /** Returns the number of bytes that would be needed to represent the given
  2683. unicode character in this encoding format.
  2684. */
  2685. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2686. {
  2687. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2688. }
  2689. /** Returns the number of bytes that would be needed to represent the given
  2690. string in this encoding format.
  2691. The value returned does NOT include the terminating null character.
  2692. */
  2693. template <class CharPointer>
  2694. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2695. {
  2696. size_t count = 0;
  2697. juce_wchar n;
  2698. while ((n = text.getAndAdvance()) != 0)
  2699. count += getBytesRequiredFor (n);
  2700. return count;
  2701. }
  2702. /** Returns a pointer to the null character that terminates this string. */
  2703. CharPointer_UTF16 findTerminatingNull() const noexcept
  2704. {
  2705. const CharType* t = data;
  2706. while (*t != 0)
  2707. ++t;
  2708. return CharPointer_UTF16 (t);
  2709. }
  2710. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2711. template <typename CharPointer>
  2712. void writeAll (const CharPointer& src) noexcept
  2713. {
  2714. CharacterFunctions::copyAll (*this, src);
  2715. }
  2716. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2717. void writeAll (const CharPointer_UTF16& src) noexcept
  2718. {
  2719. const CharType* s = src.data;
  2720. while ((*data = *s) != 0)
  2721. {
  2722. ++data;
  2723. ++s;
  2724. }
  2725. }
  2726. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2727. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2728. to the destination buffer before stopping.
  2729. */
  2730. template <typename CharPointer>
  2731. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2732. {
  2733. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2734. }
  2735. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2736. The maxChars parameter specifies the maximum number of characters that can be
  2737. written to the destination buffer before stopping (including the terminating null).
  2738. */
  2739. template <typename CharPointer>
  2740. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2741. {
  2742. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2743. }
  2744. /** Compares this string with another one. */
  2745. template <typename CharPointer>
  2746. int compare (const CharPointer& other) const noexcept
  2747. {
  2748. return CharacterFunctions::compare (*this, other);
  2749. }
  2750. /** Compares this string with another one, up to a specified number of characters. */
  2751. template <typename CharPointer>
  2752. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2753. {
  2754. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2755. }
  2756. /** Compares this string with another one. */
  2757. template <typename CharPointer>
  2758. int compareIgnoreCase (const CharPointer& other) const noexcept
  2759. {
  2760. return CharacterFunctions::compareIgnoreCase (*this, other);
  2761. }
  2762. /** Compares this string with another one, up to a specified number of characters. */
  2763. template <typename CharPointer>
  2764. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2765. {
  2766. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2767. }
  2768. #if JUCE_WINDOWS && ! DOXYGEN
  2769. int compareIgnoreCase (const CharPointer_UTF16& other) const noexcept
  2770. {
  2771. return _wcsicmp (data, other.data);
  2772. }
  2773. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const noexcept
  2774. {
  2775. return _wcsnicmp (data, other.data, maxChars);
  2776. }
  2777. int indexOf (const CharPointer_UTF16& stringToFind) const noexcept
  2778. {
  2779. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2780. return t == nullptr ? -1 : (int) (t - data);
  2781. }
  2782. #endif
  2783. /** Returns the character index of a substring, or -1 if it isn't found. */
  2784. template <typename CharPointer>
  2785. int indexOf (const CharPointer& stringToFind) const noexcept
  2786. {
  2787. return CharacterFunctions::indexOf (*this, stringToFind);
  2788. }
  2789. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2790. int indexOf (const juce_wchar charToFind) const noexcept
  2791. {
  2792. return CharacterFunctions::indexOfChar (*this, charToFind);
  2793. }
  2794. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2795. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2796. {
  2797. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2798. : CharacterFunctions::indexOfChar (*this, charToFind);
  2799. }
  2800. /** Returns true if the first character of this string is whitespace. */
  2801. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2802. /** Returns true if the first character of this string is a digit. */
  2803. bool isDigit() const noexcept { return CharacterFunctions::isDigit (operator*()) != 0; }
  2804. /** Returns true if the first character of this string is a letter. */
  2805. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2806. /** Returns true if the first character of this string is a letter or digit. */
  2807. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2808. /** Returns true if the first character of this string is upper-case. */
  2809. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2810. /** Returns true if the first character of this string is lower-case. */
  2811. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2812. /** Returns an upper-case version of the first character of this string. */
  2813. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2814. /** Returns a lower-case version of the first character of this string. */
  2815. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2816. /** Parses this string as a 32-bit integer. */
  2817. int getIntValue32() const noexcept
  2818. {
  2819. #if JUCE_WINDOWS
  2820. return _wtoi (data);
  2821. #else
  2822. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2823. #endif
  2824. }
  2825. /** Parses this string as a 64-bit integer. */
  2826. int64 getIntValue64() const noexcept
  2827. {
  2828. #if JUCE_WINDOWS
  2829. return _wtoi64 (data);
  2830. #else
  2831. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2832. #endif
  2833. }
  2834. /** Parses this string as a floating point double. */
  2835. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2836. /** Returns the first non-whitespace character in the string. */
  2837. CharPointer_UTF16 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2838. /** Returns true if the given unicode character can be represented in this encoding. */
  2839. static bool canRepresent (juce_wchar character) noexcept
  2840. {
  2841. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2842. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2843. }
  2844. /** Returns true if this data contains a valid string in this encoding. */
  2845. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2846. {
  2847. maxBytesToRead /= sizeof (CharType);
  2848. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2849. {
  2850. const uint32 n = (uint32) (uint16) *dataToTest++;
  2851. if (n >= 0xd800)
  2852. {
  2853. if (n > 0x10ffff)
  2854. return false;
  2855. if (n <= 0xdfff)
  2856. {
  2857. if (n > 0xdc00)
  2858. return false;
  2859. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2860. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2861. return false;
  2862. }
  2863. }
  2864. }
  2865. return true;
  2866. }
  2867. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2868. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2869. {
  2870. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2871. }
  2872. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2873. enum
  2874. {
  2875. byteOrderMarkBE1 = 0xfe,
  2876. byteOrderMarkBE2 = 0xff,
  2877. byteOrderMarkLE1 = 0xff,
  2878. byteOrderMarkLE2 = 0xfe
  2879. };
  2880. private:
  2881. CharType* data;
  2882. static int findNullIndex (const CharType* const t) noexcept
  2883. {
  2884. int n = 0;
  2885. while (t[n] != 0)
  2886. ++n;
  2887. return n;
  2888. }
  2889. };
  2890. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2891. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2892. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2893. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2894. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2895. /**
  2896. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2897. various methods to operate on the data.
  2898. @see CharPointer_UTF8, CharPointer_UTF16
  2899. */
  2900. class CharPointer_UTF32
  2901. {
  2902. public:
  2903. typedef juce_wchar CharType;
  2904. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) noexcept
  2905. : data (const_cast <CharType*> (rawPointer))
  2906. {
  2907. }
  2908. inline CharPointer_UTF32 (const CharPointer_UTF32& other) noexcept
  2909. : data (other.data)
  2910. {
  2911. }
  2912. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) noexcept
  2913. {
  2914. data = other.data;
  2915. return *this;
  2916. }
  2917. inline CharPointer_UTF32& operator= (const CharType* text) noexcept
  2918. {
  2919. data = const_cast <CharType*> (text);
  2920. return *this;
  2921. }
  2922. /** This is a pointer comparison, it doesn't compare the actual text. */
  2923. inline bool operator== (const CharPointer_UTF32& other) const noexcept { return data == other.data; }
  2924. inline bool operator!= (const CharPointer_UTF32& other) const noexcept { return data != other.data; }
  2925. inline bool operator<= (const CharPointer_UTF32& other) const noexcept { return data <= other.data; }
  2926. inline bool operator< (const CharPointer_UTF32& other) const noexcept { return data < other.data; }
  2927. inline bool operator>= (const CharPointer_UTF32& other) const noexcept { return data >= other.data; }
  2928. inline bool operator> (const CharPointer_UTF32& other) const noexcept { return data > other.data; }
  2929. /** Returns the address that this pointer is pointing to. */
  2930. inline CharType* getAddress() const noexcept { return data; }
  2931. /** Returns the address that this pointer is pointing to. */
  2932. inline operator const CharType*() const noexcept { return data; }
  2933. /** Returns true if this pointer is pointing to a null character. */
  2934. inline bool isEmpty() const noexcept { return *data == 0; }
  2935. /** Returns the unicode character that this pointer is pointing to. */
  2936. inline juce_wchar operator*() const noexcept { return *data; }
  2937. /** Moves this pointer along to the next character in the string. */
  2938. inline CharPointer_UTF32& operator++() noexcept
  2939. {
  2940. ++data;
  2941. return *this;
  2942. }
  2943. /** Moves this pointer to the previous character in the string. */
  2944. inline CharPointer_UTF32& operator--() noexcept
  2945. {
  2946. --data;
  2947. return *this;
  2948. }
  2949. /** Returns the character that this pointer is currently pointing to, and then
  2950. advances the pointer to point to the next character. */
  2951. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  2952. /** Moves this pointer along to the next character in the string. */
  2953. CharPointer_UTF32 operator++ (int) noexcept
  2954. {
  2955. CharPointer_UTF32 temp (*this);
  2956. ++data;
  2957. return temp;
  2958. }
  2959. /** Moves this pointer forwards by the specified number of characters. */
  2960. inline void operator+= (const int numToSkip) noexcept
  2961. {
  2962. data += numToSkip;
  2963. }
  2964. inline void operator-= (const int numToSkip) noexcept
  2965. {
  2966. data -= numToSkip;
  2967. }
  2968. /** Returns the character at a given character index from the start of the string. */
  2969. inline juce_wchar& operator[] (const int characterIndex) const noexcept
  2970. {
  2971. return data [characterIndex];
  2972. }
  2973. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2974. CharPointer_UTF32 operator+ (const int numToSkip) const noexcept
  2975. {
  2976. return CharPointer_UTF32 (data + numToSkip);
  2977. }
  2978. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2979. CharPointer_UTF32 operator- (const int numToSkip) const noexcept
  2980. {
  2981. return CharPointer_UTF32 (data - numToSkip);
  2982. }
  2983. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2984. inline void write (const juce_wchar charToWrite) noexcept
  2985. {
  2986. *data++ = charToWrite;
  2987. }
  2988. inline void replaceChar (const juce_wchar newChar) noexcept
  2989. {
  2990. *data = newChar;
  2991. }
  2992. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2993. inline void writeNull() const noexcept
  2994. {
  2995. *data = 0;
  2996. }
  2997. /** Returns the number of characters in this string. */
  2998. size_t length() const noexcept
  2999. {
  3000. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3001. return wcslen (data);
  3002. #else
  3003. size_t n = 0;
  3004. while (data[n] != 0)
  3005. ++n;
  3006. return n;
  3007. #endif
  3008. }
  3009. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3010. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3011. {
  3012. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3013. }
  3014. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3015. size_t lengthUpTo (const CharPointer_UTF32& end) const noexcept
  3016. {
  3017. return CharacterFunctions::lengthUpTo (*this, end);
  3018. }
  3019. /** Returns the number of bytes that are used to represent this string.
  3020. This includes the terminating null character.
  3021. */
  3022. size_t sizeInBytes() const noexcept
  3023. {
  3024. return sizeof (CharType) * (length() + 1);
  3025. }
  3026. /** Returns the number of bytes that would be needed to represent the given
  3027. unicode character in this encoding format.
  3028. */
  3029. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3030. {
  3031. return sizeof (CharType);
  3032. }
  3033. /** Returns the number of bytes that would be needed to represent the given
  3034. string in this encoding format.
  3035. The value returned does NOT include the terminating null character.
  3036. */
  3037. template <class CharPointer>
  3038. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3039. {
  3040. return sizeof (CharType) * text.length();
  3041. }
  3042. /** Returns a pointer to the null character that terminates this string. */
  3043. CharPointer_UTF32 findTerminatingNull() const noexcept
  3044. {
  3045. return CharPointer_UTF32 (data + length());
  3046. }
  3047. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3048. template <typename CharPointer>
  3049. void writeAll (const CharPointer& src) noexcept
  3050. {
  3051. CharacterFunctions::copyAll (*this, src);
  3052. }
  3053. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3054. void writeAll (const CharPointer_UTF32& src) noexcept
  3055. {
  3056. const CharType* s = src.data;
  3057. while ((*data = *s) != 0)
  3058. {
  3059. ++data;
  3060. ++s;
  3061. }
  3062. }
  3063. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3064. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3065. to the destination buffer before stopping.
  3066. */
  3067. template <typename CharPointer>
  3068. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3069. {
  3070. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3071. }
  3072. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3073. The maxChars parameter specifies the maximum number of characters that can be
  3074. written to the destination buffer before stopping (including the terminating null).
  3075. */
  3076. template <typename CharPointer>
  3077. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3078. {
  3079. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3080. }
  3081. /** Compares this string with another one. */
  3082. template <typename CharPointer>
  3083. int compare (const CharPointer& other) const noexcept
  3084. {
  3085. return CharacterFunctions::compare (*this, other);
  3086. }
  3087. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3088. /** Compares this string with another one. */
  3089. int compare (const CharPointer_UTF32& other) const noexcept
  3090. {
  3091. return wcscmp (data, other.data);
  3092. }
  3093. #endif
  3094. /** Compares this string with another one, up to a specified number of characters. */
  3095. template <typename CharPointer>
  3096. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3097. {
  3098. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3099. }
  3100. /** Compares this string with another one. */
  3101. template <typename CharPointer>
  3102. int compareIgnoreCase (const CharPointer& other) const
  3103. {
  3104. return CharacterFunctions::compareIgnoreCase (*this, other);
  3105. }
  3106. /** Compares this string with another one, up to a specified number of characters. */
  3107. template <typename CharPointer>
  3108. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3109. {
  3110. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3111. }
  3112. /** Returns the character index of a substring, or -1 if it isn't found. */
  3113. template <typename CharPointer>
  3114. int indexOf (const CharPointer& stringToFind) const noexcept
  3115. {
  3116. return CharacterFunctions::indexOf (*this, stringToFind);
  3117. }
  3118. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3119. int indexOf (const juce_wchar charToFind) const noexcept
  3120. {
  3121. int i = 0;
  3122. while (data[i] != 0)
  3123. {
  3124. if (data[i] == charToFind)
  3125. return i;
  3126. ++i;
  3127. }
  3128. return -1;
  3129. }
  3130. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3131. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3132. {
  3133. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3134. : CharacterFunctions::indexOfChar (*this, charToFind);
  3135. }
  3136. /** Returns true if the first character of this string is whitespace. */
  3137. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3138. /** Returns true if the first character of this string is a digit. */
  3139. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3140. /** Returns true if the first character of this string is a letter. */
  3141. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3142. /** Returns true if the first character of this string is a letter or digit. */
  3143. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3144. /** Returns true if the first character of this string is upper-case. */
  3145. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3146. /** Returns true if the first character of this string is lower-case. */
  3147. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3148. /** Returns an upper-case version of the first character of this string. */
  3149. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3150. /** Returns a lower-case version of the first character of this string. */
  3151. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3152. /** Parses this string as a 32-bit integer. */
  3153. int getIntValue32() const noexcept { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3154. /** Parses this string as a 64-bit integer. */
  3155. int64 getIntValue64() const noexcept { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3156. /** Parses this string as a floating point double. */
  3157. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3158. /** Returns the first non-whitespace character in the string. */
  3159. CharPointer_UTF32 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3160. /** Returns true if the given unicode character can be represented in this encoding. */
  3161. static bool canRepresent (juce_wchar character) noexcept
  3162. {
  3163. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3164. }
  3165. /** Returns true if this data contains a valid string in this encoding. */
  3166. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3167. {
  3168. maxBytesToRead /= sizeof (CharType);
  3169. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3170. if (! canRepresent (*dataToTest++))
  3171. return false;
  3172. return true;
  3173. }
  3174. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3175. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3176. {
  3177. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3178. }
  3179. private:
  3180. CharType* data;
  3181. };
  3182. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3183. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3184. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3185. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3186. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3187. /**
  3188. Wraps a pointer to a null-terminated ASCII character string, and provides
  3189. various methods to operate on the data.
  3190. A valid ASCII string is assumed to not contain any characters above 127.
  3191. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3192. */
  3193. class CharPointer_ASCII
  3194. {
  3195. public:
  3196. typedef char CharType;
  3197. inline explicit CharPointer_ASCII (const CharType* const rawPointer) noexcept
  3198. : data (const_cast <CharType*> (rawPointer))
  3199. {
  3200. }
  3201. inline CharPointer_ASCII (const CharPointer_ASCII& other) noexcept
  3202. : data (other.data)
  3203. {
  3204. }
  3205. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) noexcept
  3206. {
  3207. data = other.data;
  3208. return *this;
  3209. }
  3210. inline CharPointer_ASCII& operator= (const CharType* text) noexcept
  3211. {
  3212. data = const_cast <CharType*> (text);
  3213. return *this;
  3214. }
  3215. /** This is a pointer comparison, it doesn't compare the actual text. */
  3216. inline bool operator== (const CharPointer_ASCII& other) const noexcept { return data == other.data; }
  3217. inline bool operator!= (const CharPointer_ASCII& other) const noexcept { return data != other.data; }
  3218. inline bool operator<= (const CharPointer_ASCII& other) const noexcept { return data <= other.data; }
  3219. inline bool operator< (const CharPointer_ASCII& other) const noexcept { return data < other.data; }
  3220. inline bool operator>= (const CharPointer_ASCII& other) const noexcept { return data >= other.data; }
  3221. inline bool operator> (const CharPointer_ASCII& other) const noexcept { return data > other.data; }
  3222. /** Returns the address that this pointer is pointing to. */
  3223. inline CharType* getAddress() const noexcept { return data; }
  3224. /** Returns the address that this pointer is pointing to. */
  3225. inline operator const CharType*() const noexcept { return data; }
  3226. /** Returns true if this pointer is pointing to a null character. */
  3227. inline bool isEmpty() const noexcept { return *data == 0; }
  3228. /** Returns the unicode character that this pointer is pointing to. */
  3229. inline juce_wchar operator*() const noexcept { return *data; }
  3230. /** Moves this pointer along to the next character in the string. */
  3231. inline CharPointer_ASCII& operator++() noexcept
  3232. {
  3233. ++data;
  3234. return *this;
  3235. }
  3236. /** Moves this pointer to the previous character in the string. */
  3237. inline CharPointer_ASCII& operator--() noexcept
  3238. {
  3239. --data;
  3240. return *this;
  3241. }
  3242. /** Returns the character that this pointer is currently pointing to, and then
  3243. advances the pointer to point to the next character. */
  3244. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  3245. /** Moves this pointer along to the next character in the string. */
  3246. CharPointer_ASCII operator++ (int) noexcept
  3247. {
  3248. CharPointer_ASCII temp (*this);
  3249. ++data;
  3250. return temp;
  3251. }
  3252. /** Moves this pointer forwards by the specified number of characters. */
  3253. inline void operator+= (const int numToSkip) noexcept
  3254. {
  3255. data += numToSkip;
  3256. }
  3257. inline void operator-= (const int numToSkip) noexcept
  3258. {
  3259. data -= numToSkip;
  3260. }
  3261. /** Returns the character at a given character index from the start of the string. */
  3262. inline juce_wchar operator[] (const int characterIndex) const noexcept
  3263. {
  3264. return (juce_wchar) (unsigned char) data [characterIndex];
  3265. }
  3266. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3267. CharPointer_ASCII operator+ (const int numToSkip) const noexcept
  3268. {
  3269. return CharPointer_ASCII (data + numToSkip);
  3270. }
  3271. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3272. CharPointer_ASCII operator- (const int numToSkip) const noexcept
  3273. {
  3274. return CharPointer_ASCII (data - numToSkip);
  3275. }
  3276. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3277. inline void write (const juce_wchar charToWrite) noexcept
  3278. {
  3279. *data++ = (char) charToWrite;
  3280. }
  3281. inline void replaceChar (const juce_wchar newChar) noexcept
  3282. {
  3283. *data = (char) newChar;
  3284. }
  3285. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3286. inline void writeNull() const noexcept
  3287. {
  3288. *data = 0;
  3289. }
  3290. /** Returns the number of characters in this string. */
  3291. size_t length() const noexcept
  3292. {
  3293. return (size_t) strlen (data);
  3294. }
  3295. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3296. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3297. {
  3298. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3299. }
  3300. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3301. size_t lengthUpTo (const CharPointer_ASCII& end) const noexcept
  3302. {
  3303. return CharacterFunctions::lengthUpTo (*this, end);
  3304. }
  3305. /** Returns the number of bytes that are used to represent this string.
  3306. This includes the terminating null character.
  3307. */
  3308. size_t sizeInBytes() const noexcept
  3309. {
  3310. return length() + 1;
  3311. }
  3312. /** Returns the number of bytes that would be needed to represent the given
  3313. unicode character in this encoding format.
  3314. */
  3315. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3316. {
  3317. return 1;
  3318. }
  3319. /** Returns the number of bytes that would be needed to represent the given
  3320. string in this encoding format.
  3321. The value returned does NOT include the terminating null character.
  3322. */
  3323. template <class CharPointer>
  3324. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3325. {
  3326. return text.length();
  3327. }
  3328. /** Returns a pointer to the null character that terminates this string. */
  3329. CharPointer_ASCII findTerminatingNull() const noexcept
  3330. {
  3331. return CharPointer_ASCII (data + length());
  3332. }
  3333. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3334. template <typename CharPointer>
  3335. void writeAll (const CharPointer& src) noexcept
  3336. {
  3337. CharacterFunctions::copyAll (*this, src);
  3338. }
  3339. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3340. void writeAll (const CharPointer_ASCII& src) noexcept
  3341. {
  3342. strcpy (data, src.data);
  3343. }
  3344. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3345. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3346. to the destination buffer before stopping.
  3347. */
  3348. template <typename CharPointer>
  3349. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3350. {
  3351. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3352. }
  3353. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3354. The maxChars parameter specifies the maximum number of characters that can be
  3355. written to the destination buffer before stopping (including the terminating null).
  3356. */
  3357. template <typename CharPointer>
  3358. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3359. {
  3360. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3361. }
  3362. /** Compares this string with another one. */
  3363. template <typename CharPointer>
  3364. int compare (const CharPointer& other) const noexcept
  3365. {
  3366. return CharacterFunctions::compare (*this, other);
  3367. }
  3368. /** Compares this string with another one. */
  3369. int compare (const CharPointer_ASCII& other) const noexcept
  3370. {
  3371. return strcmp (data, other.data);
  3372. }
  3373. /** Compares this string with another one, up to a specified number of characters. */
  3374. template <typename CharPointer>
  3375. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3376. {
  3377. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3378. }
  3379. /** Compares this string with another one, up to a specified number of characters. */
  3380. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const noexcept
  3381. {
  3382. return strncmp (data, other.data, (size_t) maxChars);
  3383. }
  3384. /** Compares this string with another one. */
  3385. template <typename CharPointer>
  3386. int compareIgnoreCase (const CharPointer& other) const
  3387. {
  3388. return CharacterFunctions::compareIgnoreCase (*this, other);
  3389. }
  3390. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3391. {
  3392. #if JUCE_WINDOWS
  3393. return stricmp (data, other.data);
  3394. #else
  3395. return strcasecmp (data, other.data);
  3396. #endif
  3397. }
  3398. /** Compares this string with another one, up to a specified number of characters. */
  3399. template <typename CharPointer>
  3400. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3401. {
  3402. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3403. }
  3404. /** Returns the character index of a substring, or -1 if it isn't found. */
  3405. template <typename CharPointer>
  3406. int indexOf (const CharPointer& stringToFind) const noexcept
  3407. {
  3408. return CharacterFunctions::indexOf (*this, stringToFind);
  3409. }
  3410. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3411. int indexOf (const juce_wchar charToFind) const noexcept
  3412. {
  3413. int i = 0;
  3414. while (data[i] != 0)
  3415. {
  3416. if (data[i] == (char) charToFind)
  3417. return i;
  3418. ++i;
  3419. }
  3420. return -1;
  3421. }
  3422. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3423. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3424. {
  3425. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3426. : CharacterFunctions::indexOfChar (*this, charToFind);
  3427. }
  3428. /** Returns true if the first character of this string is whitespace. */
  3429. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3430. /** Returns true if the first character of this string is a digit. */
  3431. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3432. /** Returns true if the first character of this string is a letter. */
  3433. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3434. /** Returns true if the first character of this string is a letter or digit. */
  3435. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3436. /** Returns true if the first character of this string is upper-case. */
  3437. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3438. /** Returns true if the first character of this string is lower-case. */
  3439. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3440. /** Returns an upper-case version of the first character of this string. */
  3441. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3442. /** Returns a lower-case version of the first character of this string. */
  3443. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3444. /** Parses this string as a 32-bit integer. */
  3445. int getIntValue32() const noexcept { return atoi (data); }
  3446. /** Parses this string as a 64-bit integer. */
  3447. int64 getIntValue64() const noexcept
  3448. {
  3449. #if JUCE_LINUX || JUCE_ANDROID
  3450. return atoll (data);
  3451. #elif JUCE_WINDOWS
  3452. return _atoi64 (data);
  3453. #else
  3454. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3455. #endif
  3456. }
  3457. /** Parses this string as a floating point double. */
  3458. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3459. /** Returns the first non-whitespace character in the string. */
  3460. CharPointer_ASCII findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3461. /** Returns true if the given unicode character can be represented in this encoding. */
  3462. static bool canRepresent (juce_wchar character) noexcept
  3463. {
  3464. return ((unsigned int) character) < (unsigned int) 128;
  3465. }
  3466. /** Returns true if this data contains a valid string in this encoding. */
  3467. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3468. {
  3469. while (--maxBytesToRead >= 0)
  3470. {
  3471. if (((signed char) *dataToTest) <= 0)
  3472. return *dataToTest == 0;
  3473. ++dataToTest;
  3474. }
  3475. return true;
  3476. }
  3477. private:
  3478. CharType* data;
  3479. };
  3480. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3481. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3482. #if JUCE_MSVC
  3483. #pragma warning (pop)
  3484. #endif
  3485. class OutputStream;
  3486. /**
  3487. The JUCE String class!
  3488. Using a reference-counted internal representation, these strings are fast
  3489. and efficient, and there are methods to do just about any operation you'll ever
  3490. dream of.
  3491. @see StringArray, StringPairArray
  3492. */
  3493. class JUCE_API String
  3494. {
  3495. public:
  3496. /** Creates an empty string.
  3497. @see empty
  3498. */
  3499. String() noexcept;
  3500. /** Creates a copy of another string. */
  3501. String (const String& other) noexcept;
  3502. /** Creates a string from a zero-terminated ascii text string.
  3503. The string passed-in must not contain any characters with a value above 127, because
  3504. these can't be converted to unicode without knowing the original encoding that was
  3505. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3506. assertion.
  3507. To create strings with extended characters from UTF-8, you should explicitly call
  3508. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3509. use UTF-8 with escape characters in your source code to represent extended characters,
  3510. because there's no other way to represent unicode strings in a way that isn't dependent
  3511. on the compiler, source code editor and platform.
  3512. */
  3513. String (const char* text);
  3514. /** Creates a string from a string of 8-bit ascii characters.
  3515. The string passed-in must not contain any characters with a value above 127, because
  3516. these can't be converted to unicode without knowing the original encoding that was
  3517. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3518. assertion.
  3519. To create strings with extended characters from UTF-8, you should explicitly call
  3520. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3521. use UTF-8 with escape characters in your source code to represent extended characters,
  3522. because there's no other way to represent unicode strings in a way that isn't dependent
  3523. on the compiler, source code editor and platform.
  3524. This will use up the the first maxChars characters of the string (or less if the string
  3525. is actually shorter).
  3526. */
  3527. String (const char* text, size_t maxChars);
  3528. /** Creates a string from a whcar_t character string.
  3529. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3530. */
  3531. String (const wchar_t* text);
  3532. /** Creates a string from a whcar_t character string.
  3533. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3534. */
  3535. String (const wchar_t* text, size_t maxChars);
  3536. /** Creates a string from a UTF-8 character string */
  3537. String (const CharPointer_UTF8& text);
  3538. /** Creates a string from a UTF-8 character string */
  3539. String (const CharPointer_UTF8& text, size_t maxChars);
  3540. /** Creates a string from a UTF-8 character string */
  3541. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3542. /** Creates a string from a UTF-16 character string */
  3543. String (const CharPointer_UTF16& text);
  3544. /** Creates a string from a UTF-16 character string */
  3545. String (const CharPointer_UTF16& text, size_t maxChars);
  3546. /** Creates a string from a UTF-16 character string */
  3547. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3548. /** Creates a string from a UTF-32 character string */
  3549. String (const CharPointer_UTF32& text);
  3550. /** Creates a string from a UTF-32 character string */
  3551. String (const CharPointer_UTF32& text, size_t maxChars);
  3552. /** Creates a string from a UTF-32 character string */
  3553. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3554. /** Creates a string from an ASCII character string */
  3555. String (const CharPointer_ASCII& text);
  3556. /** Creates a string from a single character. */
  3557. static const String charToString (juce_wchar character);
  3558. /** Destructor. */
  3559. ~String() noexcept;
  3560. /** This is an empty string that can be used whenever one is needed.
  3561. It's better to use this than String() because it explains what's going on
  3562. and is more efficient.
  3563. */
  3564. static const String empty;
  3565. /** This is the character encoding type used internally to store the string.
  3566. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3567. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3568. contain few extended characters), but call operator[] involves iterating the string to find
  3569. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3570. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3571. but is the native wchar_t format used in Windows.
  3572. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3573. toUTF32() methods let you access the string's content in any of the other formats.
  3574. */
  3575. #if (JUCE_STRING_UTF_TYPE == 32)
  3576. typedef CharPointer_UTF32 CharPointerType;
  3577. #elif (JUCE_STRING_UTF_TYPE == 16)
  3578. typedef CharPointer_UTF16 CharPointerType;
  3579. #elif (JUCE_STRING_UTF_TYPE == 8)
  3580. typedef CharPointer_UTF8 CharPointerType;
  3581. #else
  3582. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3583. #endif
  3584. /** Generates a probably-unique 32-bit hashcode from this string. */
  3585. int hashCode() const noexcept;
  3586. /** Generates a probably-unique 64-bit hashcode from this string. */
  3587. int64 hashCode64() const noexcept;
  3588. /** Returns the number of characters in the string. */
  3589. int length() const noexcept;
  3590. // Assignment and concatenation operators..
  3591. /** Replaces this string's contents with another string. */
  3592. String& operator= (const String& other) noexcept;
  3593. /** Appends another string at the end of this one. */
  3594. String& operator+= (const String& stringToAppend);
  3595. /** Appends another string at the end of this one. */
  3596. String& operator+= (const char* textToAppend);
  3597. /** Appends another string at the end of this one. */
  3598. String& operator+= (const wchar_t* textToAppend);
  3599. /** Appends a decimal number at the end of this string. */
  3600. String& operator+= (int numberToAppend);
  3601. /** Appends a character at the end of this string. */
  3602. String& operator+= (char characterToAppend);
  3603. /** Appends a character at the end of this string. */
  3604. String& operator+= (wchar_t characterToAppend);
  3605. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3606. /** Appends a character at the end of this string. */
  3607. String& operator+= (juce_wchar characterToAppend);
  3608. #endif
  3609. /** Appends a string to the end of this one.
  3610. @param textToAppend the string to add
  3611. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3612. */
  3613. void append (const String& textToAppend, size_t maxCharsToTake);
  3614. /** Appends a string to the end of this one.
  3615. @param textToAppend the string to add
  3616. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3617. */
  3618. template <class CharPointer>
  3619. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3620. {
  3621. if (textToAppend.getAddress() != nullptr)
  3622. {
  3623. size_t extraBytesNeeded = 0;
  3624. size_t numChars = 0;
  3625. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3626. {
  3627. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3628. ++numChars;
  3629. }
  3630. if (numChars > 0)
  3631. {
  3632. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3633. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3634. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3635. }
  3636. }
  3637. }
  3638. /** Appends a string to the end of this one. */
  3639. template <class CharPointer>
  3640. void appendCharPointer (const CharPointer& textToAppend)
  3641. {
  3642. if (textToAppend.getAddress() != nullptr)
  3643. {
  3644. size_t extraBytesNeeded = 0;
  3645. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3646. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3647. if (extraBytesNeeded > 0)
  3648. {
  3649. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3650. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3651. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3652. }
  3653. }
  3654. }
  3655. // Comparison methods..
  3656. /** Returns true if the string contains no characters.
  3657. Note that there's also an isNotEmpty() method to help write readable code.
  3658. @see containsNonWhitespaceChars()
  3659. */
  3660. inline bool isEmpty() const noexcept { return text[0] == 0; }
  3661. /** Returns true if the string contains at least one character.
  3662. Note that there's also an isEmpty() method to help write readable code.
  3663. @see containsNonWhitespaceChars()
  3664. */
  3665. inline bool isNotEmpty() const noexcept { return text[0] != 0; }
  3666. /** Case-insensitive comparison with another string. */
  3667. bool equalsIgnoreCase (const String& other) const noexcept;
  3668. /** Case-insensitive comparison with another string. */
  3669. bool equalsIgnoreCase (const wchar_t* other) const noexcept;
  3670. /** Case-insensitive comparison with another string. */
  3671. bool equalsIgnoreCase (const char* other) const noexcept;
  3672. /** Case-sensitive comparison with another string.
  3673. @returns 0 if the two strings are identical; negative if this string comes before
  3674. the other one alphabetically, or positive if it comes after it.
  3675. */
  3676. int compare (const String& other) const noexcept;
  3677. /** Case-sensitive comparison with another string.
  3678. @returns 0 if the two strings are identical; negative if this string comes before
  3679. the other one alphabetically, or positive if it comes after it.
  3680. */
  3681. int compare (const char* other) const noexcept;
  3682. /** Case-sensitive comparison with another string.
  3683. @returns 0 if the two strings are identical; negative if this string comes before
  3684. the other one alphabetically, or positive if it comes after it.
  3685. */
  3686. int compare (const wchar_t* other) const noexcept;
  3687. /** Case-insensitive comparison with another string.
  3688. @returns 0 if the two strings are identical; negative if this string comes before
  3689. the other one alphabetically, or positive if it comes after it.
  3690. */
  3691. int compareIgnoreCase (const String& other) const noexcept;
  3692. /** Lexicographic comparison with another string.
  3693. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3694. characters, making it good for sorting human-readable strings.
  3695. @returns 0 if the two strings are identical; negative if this string comes before
  3696. the other one alphabetically, or positive if it comes after it.
  3697. */
  3698. int compareLexicographically (const String& other) const noexcept;
  3699. /** Tests whether the string begins with another string.
  3700. If the parameter is an empty string, this will always return true.
  3701. Uses a case-sensitive comparison.
  3702. */
  3703. bool startsWith (const String& text) const noexcept;
  3704. /** Tests whether the string begins with a particular character.
  3705. If the character is 0, this will always return false.
  3706. Uses a case-sensitive comparison.
  3707. */
  3708. bool startsWithChar (juce_wchar character) const noexcept;
  3709. /** Tests whether the string begins with another string.
  3710. If the parameter is an empty string, this will always return true.
  3711. Uses a case-insensitive comparison.
  3712. */
  3713. bool startsWithIgnoreCase (const String& text) const noexcept;
  3714. /** Tests whether the string ends with another string.
  3715. If the parameter is an empty string, this will always return true.
  3716. Uses a case-sensitive comparison.
  3717. */
  3718. bool endsWith (const String& text) const noexcept;
  3719. /** Tests whether the string ends with a particular character.
  3720. If the character is 0, this will always return false.
  3721. Uses a case-sensitive comparison.
  3722. */
  3723. bool endsWithChar (juce_wchar character) const noexcept;
  3724. /** Tests whether the string ends with another string.
  3725. If the parameter is an empty string, this will always return true.
  3726. Uses a case-insensitive comparison.
  3727. */
  3728. bool endsWithIgnoreCase (const String& text) const noexcept;
  3729. /** Tests whether the string contains another substring.
  3730. If the parameter is an empty string, this will always return true.
  3731. Uses a case-sensitive comparison.
  3732. */
  3733. bool contains (const String& text) const noexcept;
  3734. /** Tests whether the string contains a particular character.
  3735. Uses a case-sensitive comparison.
  3736. */
  3737. bool containsChar (juce_wchar character) const noexcept;
  3738. /** Tests whether the string contains another substring.
  3739. Uses a case-insensitive comparison.
  3740. */
  3741. bool containsIgnoreCase (const String& text) const noexcept;
  3742. /** Tests whether the string contains another substring as a distict word.
  3743. @returns true if the string contains this word, surrounded by
  3744. non-alphanumeric characters
  3745. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3746. */
  3747. bool containsWholeWord (const String& wordToLookFor) const noexcept;
  3748. /** Tests whether the string contains another substring as a distict word.
  3749. @returns true if the string contains this word, surrounded by
  3750. non-alphanumeric characters
  3751. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3752. */
  3753. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3754. /** Finds an instance of another substring if it exists as a distict word.
  3755. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3756. then this will return the index of the start of the substring. If it isn't
  3757. found, then it will return -1
  3758. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3759. */
  3760. int indexOfWholeWord (const String& wordToLookFor) const noexcept;
  3761. /** Finds an instance of another substring if it exists as a distict word.
  3762. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3763. then this will return the index of the start of the substring. If it isn't
  3764. found, then it will return -1
  3765. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3766. */
  3767. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3768. /** Looks for any of a set of characters in the string.
  3769. Uses a case-sensitive comparison.
  3770. @returns true if the string contains any of the characters from
  3771. the string that is passed in.
  3772. */
  3773. bool containsAnyOf (const String& charactersItMightContain) const noexcept;
  3774. /** Looks for a set of characters in the string.
  3775. Uses a case-sensitive comparison.
  3776. @returns Returns false if any of the characters in this string do not occur in
  3777. the parameter string. If this string is empty, the return value will
  3778. always be true.
  3779. */
  3780. bool containsOnly (const String& charactersItMightContain) const noexcept;
  3781. /** Returns true if this string contains any non-whitespace characters.
  3782. This will return false if the string contains only whitespace characters, or
  3783. if it's empty.
  3784. It is equivalent to calling "myString.trim().isNotEmpty()".
  3785. */
  3786. bool containsNonWhitespaceChars() const noexcept;
  3787. /** Returns true if the string matches this simple wildcard expression.
  3788. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3789. This isn't a full-blown regex though! The only wildcard characters supported
  3790. are "*" and "?". It's mainly intended for filename pattern matching.
  3791. */
  3792. bool matchesWildcard (const String& wildcard, bool ignoreCase) const noexcept;
  3793. // Substring location methods..
  3794. /** Searches for a character inside this string.
  3795. Uses a case-sensitive comparison.
  3796. @returns the index of the first occurrence of the character in this
  3797. string, or -1 if it's not found.
  3798. */
  3799. int indexOfChar (juce_wchar characterToLookFor) const noexcept;
  3800. /** Searches for a character inside this string.
  3801. Uses a case-sensitive comparison.
  3802. @param startIndex the index from which the search should proceed
  3803. @param characterToLookFor the character to look for
  3804. @returns the index of the first occurrence of the character in this
  3805. string, or -1 if it's not found.
  3806. */
  3807. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const noexcept;
  3808. /** Returns the index of the first character that matches one of the characters
  3809. passed-in to this method.
  3810. This scans the string, beginning from the startIndex supplied, and if it finds
  3811. a character that appears in the string charactersToLookFor, it returns its index.
  3812. If none of these characters are found, it returns -1.
  3813. If ignoreCase is true, the comparison will be case-insensitive.
  3814. @see indexOfChar, lastIndexOfAnyOf
  3815. */
  3816. int indexOfAnyOf (const String& charactersToLookFor,
  3817. int startIndex = 0,
  3818. bool ignoreCase = false) const noexcept;
  3819. /** Searches for a substring within this string.
  3820. Uses a case-sensitive comparison.
  3821. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3822. If textToLookFor is an empty string, this will always return 0.
  3823. */
  3824. int indexOf (const String& textToLookFor) const noexcept;
  3825. /** Searches for a substring within this string.
  3826. Uses a case-sensitive comparison.
  3827. @param startIndex the index from which the search should proceed
  3828. @param textToLookFor the string to search for
  3829. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3830. If textToLookFor is an empty string, this will always return -1.
  3831. */
  3832. int indexOf (int startIndex, const String& textToLookFor) const noexcept;
  3833. /** Searches for a substring within this string.
  3834. Uses a case-insensitive comparison.
  3835. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3836. If textToLookFor is an empty string, this will always return 0.
  3837. */
  3838. int indexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3839. /** Searches for a substring within this string.
  3840. Uses a case-insensitive comparison.
  3841. @param startIndex the index from which the search should proceed
  3842. @param textToLookFor the string to search for
  3843. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3844. If textToLookFor is an empty string, this will always return -1.
  3845. */
  3846. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const noexcept;
  3847. /** Searches for a character inside this string (working backwards from the end of the string).
  3848. Uses a case-sensitive comparison.
  3849. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3850. */
  3851. int lastIndexOfChar (juce_wchar character) const noexcept;
  3852. /** Searches for a substring inside this string (working backwards from the end of the string).
  3853. Uses a case-sensitive comparison.
  3854. @returns the index of the start of the last occurrence of the substring within this string,
  3855. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3856. */
  3857. int lastIndexOf (const String& textToLookFor) const noexcept;
  3858. /** Searches for a substring inside this string (working backwards from the end of the string).
  3859. Uses a case-insensitive comparison.
  3860. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3861. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3862. */
  3863. int lastIndexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3864. /** Returns the index of the last character in this string that matches one of the
  3865. characters passed-in to this method.
  3866. This scans the string backwards, starting from its end, and if it finds
  3867. a character that appears in the string charactersToLookFor, it returns its index.
  3868. If none of these characters are found, it returns -1.
  3869. If ignoreCase is true, the comparison will be case-insensitive.
  3870. @see lastIndexOf, indexOfAnyOf
  3871. */
  3872. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3873. bool ignoreCase = false) const noexcept;
  3874. // Substring extraction and manipulation methods..
  3875. /** Returns the character at this index in the string.
  3876. In a release build, no checks are made to see if the index is within a valid range, so be
  3877. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3878. Also beware that depending on the encoding format that the string is using internally, this
  3879. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3880. If you're scanning through a string to inspect its characters, you should never use this operator
  3881. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3882. then to use that to iterate the string.
  3883. @see getCharPointer
  3884. */
  3885. const juce_wchar operator[] (int index) const noexcept;
  3886. /** Returns the final character of the string.
  3887. If the string is empty this will return 0.
  3888. */
  3889. juce_wchar getLastCharacter() const noexcept;
  3890. /** Returns a subsection of the string.
  3891. If the range specified is beyond the limits of the string, as much as
  3892. possible is returned.
  3893. @param startIndex the index of the start of the substring needed
  3894. @param endIndex all characters from startIndex up to (but not including)
  3895. this index are returned
  3896. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3897. */
  3898. const String substring (int startIndex, int endIndex) const;
  3899. /** Returns a section of the string, starting from a given position.
  3900. @param startIndex the first character to include. If this is beyond the end
  3901. of the string, an empty string is returned. If it is zero or
  3902. less, the whole string is returned.
  3903. @returns the substring from startIndex up to the end of the string
  3904. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3905. */
  3906. const String substring (int startIndex) const;
  3907. /** Returns a version of this string with a number of characters removed
  3908. from the end.
  3909. @param numberToDrop the number of characters to drop from the end of the
  3910. string. If this is greater than the length of the string,
  3911. an empty string will be returned. If zero or less, the
  3912. original string will be returned.
  3913. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3914. */
  3915. const String dropLastCharacters (int numberToDrop) const;
  3916. /** Returns a number of characters from the end of the string.
  3917. This returns the last numCharacters characters from the end of the string. If the
  3918. string is shorter than numCharacters, the whole string is returned.
  3919. @see substring, dropLastCharacters, getLastCharacter
  3920. */
  3921. const String getLastCharacters (int numCharacters) const;
  3922. /** Returns a section of the string starting from a given substring.
  3923. This will search for the first occurrence of the given substring, and
  3924. return the section of the string starting from the point where this is
  3925. found (optionally not including the substring itself).
  3926. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3927. fromFirstOccurrenceOf ("34", false) would return "56".
  3928. If the substring isn't found, the method will return an empty string.
  3929. If ignoreCase is true, the comparison will be case-insensitive.
  3930. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3931. */
  3932. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3933. bool includeSubStringInResult,
  3934. bool ignoreCase) const;
  3935. /** Returns a section of the string starting from the last occurrence of a given substring.
  3936. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3937. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3938. return the whole of the original string.
  3939. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3940. */
  3941. const String fromLastOccurrenceOf (const String& substringToFind,
  3942. bool includeSubStringInResult,
  3943. bool ignoreCase) const;
  3944. /** Returns the start of this string, up to the first occurrence of a substring.
  3945. This will search for the first occurrence of a given substring, and then
  3946. return a copy of the string, up to the position of this substring,
  3947. optionally including or excluding the substring itself in the result.
  3948. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3949. upTo ("34", true) would return "1234".
  3950. If the substring isn't found, this will return the whole of the original string.
  3951. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3952. */
  3953. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  3954. bool includeSubStringInResult,
  3955. bool ignoreCase) const;
  3956. /** Returns the start of this string, up to the last occurrence of a substring.
  3957. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3958. If the substring isn't found, this will return the whole of the original string.
  3959. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3960. */
  3961. const String upToLastOccurrenceOf (const String& substringToFind,
  3962. bool includeSubStringInResult,
  3963. bool ignoreCase) const;
  3964. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3965. const String trim() const;
  3966. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3967. const String trimStart() const;
  3968. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3969. const String trimEnd() const;
  3970. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3971. Characters are removed from the start of the string until it finds one that is not in the
  3972. specified set, and then it stops.
  3973. @param charactersToTrim the set of characters to remove.
  3974. @see trim, trimStart, trimCharactersAtEnd
  3975. */
  3976. const String trimCharactersAtStart (const String& charactersToTrim) const;
  3977. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3978. Characters are removed from the end of the string until it finds one that is not in the
  3979. specified set, and then it stops.
  3980. @param charactersToTrim the set of characters to remove.
  3981. @see trim, trimEnd, trimCharactersAtStart
  3982. */
  3983. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  3984. /** Returns an upper-case version of this string. */
  3985. const String toUpperCase() const;
  3986. /** Returns an lower-case version of this string. */
  3987. const String toLowerCase() const;
  3988. /** Replaces a sub-section of the string with another string.
  3989. This will return a copy of this string, with a set of characters
  3990. from startIndex to startIndex + numCharsToReplace removed, and with
  3991. a new string inserted in their place.
  3992. Note that this is a const method, and won't alter the string itself.
  3993. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3994. it will be constrained to a valid range.
  3995. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3996. characters will be taken out.
  3997. @param stringToInsert the new string to insert at startIndex after the characters have been
  3998. removed.
  3999. */
  4000. const String replaceSection (int startIndex,
  4001. int numCharactersToReplace,
  4002. const String& stringToInsert) const;
  4003. /** Replaces all occurrences of a substring with another string.
  4004. Returns a copy of this string, with any occurrences of stringToReplace
  4005. swapped for stringToInsertInstead.
  4006. Note that this is a const method, and won't alter the string itself.
  4007. */
  4008. const String replace (const String& stringToReplace,
  4009. const String& stringToInsertInstead,
  4010. bool ignoreCase = false) const;
  4011. /** Returns a string with all occurrences of a character replaced with a different one. */
  4012. const String replaceCharacter (juce_wchar characterToReplace,
  4013. juce_wchar characterToInsertInstead) const;
  4014. /** Replaces a set of characters with another set.
  4015. Returns a string in which each character from charactersToReplace has been replaced
  4016. by the character at the equivalent position in newCharacters (so the two strings
  4017. passed in must be the same length).
  4018. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  4019. Note that this is a const method, and won't affect the string itself.
  4020. */
  4021. const String replaceCharacters (const String& charactersToReplace,
  4022. const String& charactersToInsertInstead) const;
  4023. /** Returns a version of this string that only retains a fixed set of characters.
  4024. This will return a copy of this string, omitting any characters which are not
  4025. found in the string passed-in.
  4026. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  4027. Note that this is a const method, and won't alter the string itself.
  4028. */
  4029. const String retainCharacters (const String& charactersToRetain) const;
  4030. /** Returns a version of this string with a set of characters removed.
  4031. This will return a copy of this string, omitting any characters which are
  4032. found in the string passed-in.
  4033. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  4034. Note that this is a const method, and won't alter the string itself.
  4035. */
  4036. const String removeCharacters (const String& charactersToRemove) const;
  4037. /** Returns a section from the start of the string that only contains a certain set of characters.
  4038. This returns the leftmost section of the string, up to (and not including) the
  4039. first character that doesn't appear in the string passed in.
  4040. */
  4041. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  4042. /** Returns a section from the start of the string that only contains a certain set of characters.
  4043. This returns the leftmost section of the string, up to (and not including) the
  4044. first character that occurs in the string passed in. (If none of the specified
  4045. characters are found in the string, the return value will just be the original string).
  4046. */
  4047. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  4048. /** Checks whether the string might be in quotation marks.
  4049. @returns true if the string begins with a quote character (either a double or single quote).
  4050. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4051. @see unquoted, quoted
  4052. */
  4053. bool isQuotedString() const;
  4054. /** Removes quotation marks from around the string, (if there are any).
  4055. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4056. at the ends of the string are not affected. If there aren't any quotes, the original string
  4057. is returned.
  4058. Note that this is a const method, and won't alter the string itself.
  4059. @see isQuotedString, quoted
  4060. */
  4061. const String unquoted() const;
  4062. /** Adds quotation marks around a string.
  4063. This will return a copy of the string with a quote at the start and end, (but won't
  4064. add the quote if there's already one there, so it's safe to call this on strings that
  4065. may already have quotes around them).
  4066. Note that this is a const method, and won't alter the string itself.
  4067. @param quoteCharacter the character to add at the start and end
  4068. @see isQuotedString, unquoted
  4069. */
  4070. const String quoted (juce_wchar quoteCharacter = '"') const;
  4071. /** Creates a string which is a version of a string repeated and joined together.
  4072. @param stringToRepeat the string to repeat
  4073. @param numberOfTimesToRepeat how many times to repeat it
  4074. */
  4075. static const String repeatedString (const String& stringToRepeat,
  4076. int numberOfTimesToRepeat);
  4077. /** Returns a copy of this string with the specified character repeatedly added to its
  4078. beginning until the total length is at least the minimum length specified.
  4079. */
  4080. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4081. /** Returns a copy of this string with the specified character repeatedly added to its
  4082. end until the total length is at least the minimum length specified.
  4083. */
  4084. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4085. /** Creates a string from data in an unknown format.
  4086. This looks at some binary data and tries to guess whether it's Unicode
  4087. or 8-bit characters, then returns a string that represents it correctly.
  4088. Should be able to handle Unicode endianness correctly, by looking at
  4089. the first two bytes.
  4090. */
  4091. static const String createStringFromData (const void* data, int size);
  4092. /** Creates a String from a printf-style parameter list.
  4093. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4094. using the operator<< methods or pretty much anything else instead. It's only provided
  4095. here because of the popular unrest that was stirred-up when I tried to remove it...
  4096. If you're really determined to use it, at least make sure that you never, ever,
  4097. pass any String objects to it as parameters. And bear in mind that internally, depending
  4098. on the platform, it may be using wchar_t or char character types, so that even string
  4099. literals can't be safely used as parameters if you're writing portable code.
  4100. */
  4101. static const String formatted (const String formatString, ... );
  4102. // Numeric conversions..
  4103. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4104. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4105. */
  4106. explicit String (int decimalInteger);
  4107. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4108. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4109. */
  4110. explicit String (unsigned int decimalInteger);
  4111. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4112. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4113. */
  4114. explicit String (short decimalInteger);
  4115. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4116. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4117. */
  4118. explicit String (unsigned short decimalInteger);
  4119. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4120. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4121. */
  4122. explicit String (int64 largeIntegerValue);
  4123. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4124. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4125. */
  4126. explicit String (uint64 largeIntegerValue);
  4127. /** Creates a string representing this floating-point number.
  4128. @param floatValue the value to convert to a string
  4129. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4130. decimal places, and will not use exponent notation. If 0 or
  4131. less, it will use exponent notation if necessary.
  4132. @see getDoubleValue, getIntValue
  4133. */
  4134. explicit String (float floatValue,
  4135. int numberOfDecimalPlaces = 0);
  4136. /** Creates a string representing this floating-point number.
  4137. @param doubleValue the value to convert to a string
  4138. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4139. decimal places, and will not use exponent notation. If 0 or
  4140. less, it will use exponent notation if necessary.
  4141. @see getFloatValue, getIntValue
  4142. */
  4143. explicit String (double doubleValue,
  4144. int numberOfDecimalPlaces = 0);
  4145. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4146. @returns the value of the string as a 32 bit signed base-10 integer.
  4147. @see getTrailingIntValue, getHexValue32, getHexValue64
  4148. */
  4149. int getIntValue() const noexcept;
  4150. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4151. @returns the value of the string as a 64 bit signed base-10 integer.
  4152. */
  4153. int64 getLargeIntValue() const noexcept;
  4154. /** Parses a decimal number from the end of the string.
  4155. This will look for a value at the end of the string.
  4156. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4157. Negative numbers are not handled, so "xyz-5" returns 5.
  4158. @see getIntValue
  4159. */
  4160. int getTrailingIntValue() const noexcept;
  4161. /** Parses this string as a floating point number.
  4162. @returns the value of the string as a 32-bit floating point value.
  4163. @see getDoubleValue
  4164. */
  4165. float getFloatValue() const noexcept;
  4166. /** Parses this string as a floating point number.
  4167. @returns the value of the string as a 64-bit floating point value.
  4168. @see getFloatValue
  4169. */
  4170. double getDoubleValue() const noexcept;
  4171. /** Parses the string as a hexadecimal number.
  4172. Non-hexadecimal characters in the string are ignored.
  4173. If the string contains too many characters, then the lowest significant
  4174. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4175. @returns a 32-bit number which is the value of the string in hex.
  4176. */
  4177. int getHexValue32() const noexcept;
  4178. /** Parses the string as a hexadecimal number.
  4179. Non-hexadecimal characters in the string are ignored.
  4180. If the string contains too many characters, then the lowest significant
  4181. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4182. @returns a 64-bit number which is the value of the string in hex.
  4183. */
  4184. int64 getHexValue64() const noexcept;
  4185. /** Creates a string representing this 32-bit value in hexadecimal. */
  4186. static const String toHexString (int number);
  4187. /** Creates a string representing this 64-bit value in hexadecimal. */
  4188. static const String toHexString (int64 number);
  4189. /** Creates a string representing this 16-bit value in hexadecimal. */
  4190. static const String toHexString (short number);
  4191. /** Creates a string containing a hex dump of a block of binary data.
  4192. @param data the binary data to use as input
  4193. @param size how many bytes of data to use
  4194. @param groupSize how many bytes are grouped together before inserting a
  4195. space into the output. e.g. group size 0 has no spaces,
  4196. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4197. like "bea1 c2ff".
  4198. */
  4199. static const String toHexString (const unsigned char* data,
  4200. int size,
  4201. int groupSize = 1);
  4202. /** Returns the character pointer currently being used to store this string.
  4203. Because it returns a reference to the string's internal data, the pointer
  4204. that is returned must not be stored anywhere, as it can be deleted whenever the
  4205. string changes.
  4206. */
  4207. inline const CharPointerType& getCharPointer() const noexcept { return text; }
  4208. /** Returns a pointer to a UTF-8 version of this string.
  4209. Because it returns a reference to the string's internal data, the pointer
  4210. that is returned must not be stored anywhere, as it can be deleted whenever the
  4211. string changes.
  4212. To find out how many bytes you need to store this string as UTF-8, you can call
  4213. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4214. @see getCharPointer, toUTF16, toUTF32
  4215. */
  4216. const CharPointer_UTF8 toUTF8() const;
  4217. /** Returns a pointer to a UTF-32 version of this string.
  4218. Because it returns a reference to the string's internal data, the pointer
  4219. that is returned must not be stored anywhere, as it can be deleted whenever the
  4220. string changes.
  4221. To find out how many bytes you need to store this string as UTF-16, you can call
  4222. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4223. @see getCharPointer, toUTF8, toUTF32
  4224. */
  4225. CharPointer_UTF16 toUTF16() const;
  4226. /** Returns a pointer to a UTF-32 version of this string.
  4227. Because it returns a reference to the string's internal data, the pointer
  4228. that is returned must not be stored anywhere, as it can be deleted whenever the
  4229. string changes.
  4230. @see getCharPointer, toUTF8, toUTF16
  4231. */
  4232. CharPointer_UTF32 toUTF32() const;
  4233. /** Returns a pointer to a wchar_t version of this string.
  4234. Because it returns a reference to the string's internal data, the pointer
  4235. that is returned must not be stored anywhere, as it can be deleted whenever the
  4236. string changes.
  4237. Bear in mind that the wchar_t type is different on different platforms, so on
  4238. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4239. as calling toUTF32(), etc.
  4240. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4241. */
  4242. const wchar_t* toWideCharPointer() const;
  4243. /** Creates a String from a UTF-8 encoded buffer.
  4244. If the size is < 0, it'll keep reading until it hits a zero.
  4245. */
  4246. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4247. /** Returns the number of bytes required to represent this string as UTF8.
  4248. The number returned does NOT include the trailing zero.
  4249. @see toUTF8, copyToUTF8
  4250. */
  4251. int getNumBytesAsUTF8() const noexcept;
  4252. /** Copies the string to a buffer as UTF-8 characters.
  4253. Returns the number of bytes copied to the buffer, including the terminating null
  4254. character.
  4255. To find out how many bytes you need to store this string as UTF-8, you can call
  4256. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4257. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4258. returns the number of bytes required (including the terminating null character).
  4259. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4260. put in as many as it can while still allowing for a terminating null char at the
  4261. end, and will return the number of bytes that were actually used.
  4262. @see CharPointer_UTF8::writeWithDestByteLimit
  4263. */
  4264. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4265. /** Copies the string to a buffer as UTF-16 characters.
  4266. Returns the number of bytes copied to the buffer, including the terminating null
  4267. character.
  4268. To find out how many bytes you need to store this string as UTF-16, you can call
  4269. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4270. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4271. returns the number of bytes required (including the terminating null character).
  4272. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4273. put in as many as it can while still allowing for a terminating null char at the
  4274. end, and will return the number of bytes that were actually used.
  4275. @see CharPointer_UTF16::writeWithDestByteLimit
  4276. */
  4277. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4278. /** Copies the string to a buffer as UTF-16 characters.
  4279. Returns the number of bytes copied to the buffer, including the terminating null
  4280. character.
  4281. To find out how many bytes you need to store this string as UTF-32, you can call
  4282. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4283. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4284. returns the number of bytes required (including the terminating null character).
  4285. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4286. put in as many as it can while still allowing for a terminating null char at the
  4287. end, and will return the number of bytes that were actually used.
  4288. @see CharPointer_UTF32::writeWithDestByteLimit
  4289. */
  4290. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4291. /** Increases the string's internally allocated storage.
  4292. Although the string's contents won't be affected by this call, it will
  4293. increase the amount of memory allocated internally for the string to grow into.
  4294. If you're about to make a large number of calls to methods such
  4295. as += or <<, it's more efficient to preallocate enough extra space
  4296. beforehand, so that these methods won't have to keep resizing the string
  4297. to append the extra characters.
  4298. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4299. value is less than the currently allocated size, it will
  4300. have no effect.
  4301. */
  4302. void preallocateBytes (size_t numBytesNeeded);
  4303. /** Swaps the contents of this string with another one.
  4304. This is a very fast operation, as no allocation or copying needs to be done.
  4305. */
  4306. void swapWith (String& other) noexcept;
  4307. /** A helper class to improve performance when concatenating many large strings
  4308. together.
  4309. Because appending one string to another involves measuring the length of
  4310. both strings, repeatedly doing this for many long strings will become
  4311. an exponentially slow operation. This class uses some internal state to
  4312. avoid that, so that each append operation only needs to measure the length
  4313. of the appended string.
  4314. */
  4315. class JUCE_API Concatenator
  4316. {
  4317. public:
  4318. Concatenator (String& stringToAppendTo);
  4319. ~Concatenator();
  4320. void append (const String& s);
  4321. private:
  4322. String& result;
  4323. int nextIndex;
  4324. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4325. };
  4326. private:
  4327. CharPointerType text;
  4328. struct PreallocationBytes
  4329. {
  4330. explicit PreallocationBytes (size_t);
  4331. size_t numBytes;
  4332. };
  4333. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4334. void appendFixedLength (const char* text, int numExtraChars);
  4335. size_t getByteOffsetOfEnd() const noexcept;
  4336. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4337. // This private cast operator should prevent strings being accidentally cast
  4338. // to bools (this is possible because the compiler can add an implicit cast
  4339. // via a const char*)
  4340. operator bool() const noexcept { return false; }
  4341. };
  4342. /** Concatenates two strings. */
  4343. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4344. /** Concatenates two strings. */
  4345. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4346. /** Concatenates two strings. */
  4347. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4348. /** Concatenates two strings. */
  4349. JUCE_API const String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4350. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4351. /** Concatenates two strings. */
  4352. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4353. #endif
  4354. /** Concatenates two strings. */
  4355. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4356. /** Concatenates two strings. */
  4357. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4358. /** Concatenates two strings. */
  4359. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4360. /** Concatenates two strings. */
  4361. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4362. /** Concatenates two strings. */
  4363. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4364. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4365. /** Concatenates two strings. */
  4366. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4367. #endif
  4368. /** Appends a character at the end of a string. */
  4369. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4370. /** Appends a character at the end of a string. */
  4371. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4372. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4373. /** Appends a character at the end of a string. */
  4374. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4375. #endif
  4376. /** Appends a string to the end of the first one. */
  4377. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4378. /** Appends a string to the end of the first one. */
  4379. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4380. /** Appends a string to the end of the first one. */
  4381. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4382. /** Appends a decimal number at the end of a string. */
  4383. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4384. /** Appends a decimal number at the end of a string. */
  4385. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4386. /** Appends a decimal number at the end of a string. */
  4387. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4388. /** Appends a decimal number at the end of a string. */
  4389. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4390. /** Appends a decimal number at the end of a string. */
  4391. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4392. /** Case-sensitive comparison of two strings. */
  4393. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept;
  4394. /** Case-sensitive comparison of two strings. */
  4395. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept;
  4396. /** Case-sensitive comparison of two strings. */
  4397. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept;
  4398. /** Case-sensitive comparison of two strings. */
  4399. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4400. /** Case-sensitive comparison of two strings. */
  4401. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4402. /** Case-sensitive comparison of two strings. */
  4403. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4404. /** Case-sensitive comparison of two strings. */
  4405. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept;
  4406. /** Case-sensitive comparison of two strings. */
  4407. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept;
  4408. /** Case-sensitive comparison of two strings. */
  4409. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept;
  4410. /** Case-sensitive comparison of two strings. */
  4411. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4412. /** Case-sensitive comparison of two strings. */
  4413. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4414. /** Case-sensitive comparison of two strings. */
  4415. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4416. /** Case-sensitive comparison of two strings. */
  4417. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) noexcept;
  4418. /** Case-sensitive comparison of two strings. */
  4419. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) noexcept;
  4420. /** Case-sensitive comparison of two strings. */
  4421. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) noexcept;
  4422. /** Case-sensitive comparison of two strings. */
  4423. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) noexcept;
  4424. /** This operator allows you to write a juce String directly to std output streams.
  4425. This is handy for writing strings to std::cout, std::cerr, etc.
  4426. */
  4427. template <class traits>
  4428. std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  4429. {
  4430. return stream << stringToWrite.toUTF8().getAddress();
  4431. }
  4432. /** This operator allows you to write a juce String directly to std output streams.
  4433. This is handy for writing strings to std::wcout, std::wcerr, etc.
  4434. */
  4435. template <class traits>
  4436. std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
  4437. {
  4438. return stream << stringToWrite.toWideCharPointer();
  4439. }
  4440. /** Writes a string to an OutputStream as UTF8. */
  4441. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
  4442. #endif // __JUCE_STRING_JUCEHEADER__
  4443. /*** End of inlined file: juce_String.h ***/
  4444. /**
  4445. Acts as an application-wide logging class.
  4446. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4447. method and this will then be used by all calls to writeToLog.
  4448. The logger class also contains methods for writing messages to the debugger's
  4449. output stream.
  4450. @see FileLogger
  4451. */
  4452. class JUCE_API Logger
  4453. {
  4454. public:
  4455. /** Destructor. */
  4456. virtual ~Logger();
  4457. /** Sets the current logging class to use.
  4458. Note that the object passed in won't be deleted when no longer needed.
  4459. A null pointer can be passed-in to disable any logging.
  4460. If deleteOldLogger is set to true, the existing logger will be
  4461. deleted (if there is one).
  4462. */
  4463. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4464. bool deleteOldLogger = false);
  4465. /** Writes a string to the current logger.
  4466. This will pass the string to the logger's logMessage() method if a logger
  4467. has been set.
  4468. @see logMessage
  4469. */
  4470. static void JUCE_CALLTYPE writeToLog (const String& message);
  4471. /** Writes a message to the standard error stream.
  4472. This can be called directly, or by using the DBG() macro in
  4473. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4474. */
  4475. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4476. protected:
  4477. Logger();
  4478. /** This is overloaded by subclasses to implement custom logging behaviour.
  4479. @see setCurrentLogger
  4480. */
  4481. virtual void logMessage (const String& message) = 0;
  4482. private:
  4483. static Logger* currentLogger;
  4484. };
  4485. #endif // __JUCE_LOGGER_JUCEHEADER__
  4486. /*** End of inlined file: juce_Logger.h ***/
  4487. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4488. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4489. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4490. /**
  4491. Embedding an instance of this class inside another class can be used as a low-overhead
  4492. way of detecting leaked instances.
  4493. This class keeps an internal static count of the number of instances that are
  4494. active, so that when the app is shutdown and the static destructors are called,
  4495. it can check whether there are any left-over instances that may have been leaked.
  4496. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4497. class declaration. Have a look through the juce codebase for examples, it's used
  4498. in most of the classes.
  4499. */
  4500. template <class OwnerClass>
  4501. class LeakedObjectDetector
  4502. {
  4503. public:
  4504. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  4505. LeakedObjectDetector (const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  4506. ~LeakedObjectDetector()
  4507. {
  4508. if (--(getCounter().numObjects) < 0)
  4509. {
  4510. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4511. /** If you hit this, then you've managed to delete more instances of this class than you've
  4512. created.. That indicates that you're deleting some dangling pointers.
  4513. Note that although this assertion will have been triggered during a destructor, it might
  4514. not be this particular deletion that's at fault - the incorrect one may have happened
  4515. at an earlier point in the program, and simply not been detected until now.
  4516. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4517. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4518. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4519. */
  4520. jassertfalse;
  4521. }
  4522. }
  4523. private:
  4524. class LeakCounter
  4525. {
  4526. public:
  4527. LeakCounter() noexcept {}
  4528. ~LeakCounter()
  4529. {
  4530. if (numObjects.value > 0)
  4531. {
  4532. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4533. /** If you hit this, then you've leaked one or more objects of the type specified by
  4534. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4535. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4536. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4537. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4538. */
  4539. jassertfalse;
  4540. }
  4541. }
  4542. Atomic<int> numObjects;
  4543. };
  4544. static const char* getLeakedObjectClassName()
  4545. {
  4546. return OwnerClass::getLeakedObjectClassName();
  4547. }
  4548. static LeakCounter& getCounter() noexcept
  4549. {
  4550. static LeakCounter counter;
  4551. return counter;
  4552. }
  4553. };
  4554. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4555. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4556. /** This macro lets you embed a leak-detecting object inside a class.
  4557. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4558. of the class declaration. E.g.
  4559. @code
  4560. class MyClass
  4561. {
  4562. public:
  4563. MyClass();
  4564. void blahBlah();
  4565. private:
  4566. JUCE_LEAK_DETECTOR (MyClass);
  4567. };@endcode
  4568. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4569. */
  4570. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4571. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4572. static const char* getLeakedObjectClassName() noexcept { return #OwnerClass; } \
  4573. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4574. #else
  4575. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4576. #endif
  4577. #endif
  4578. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4579. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4580. END_JUCE_NAMESPACE
  4581. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4582. /*** End of inlined file: juce_StandardHeader.h ***/
  4583. BEGIN_JUCE_NAMESPACE
  4584. #if JUCE_MSVC
  4585. // this is set explicitly in case the app is using a different packing size.
  4586. #pragma pack (push, 8)
  4587. #pragma warning (push)
  4588. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4589. #ifdef __INTEL_COMPILER
  4590. #pragma warning (disable: 1125)
  4591. #endif
  4592. #endif
  4593. // this is where all the class header files get brought in..
  4594. /*** Start of inlined file: juce_core_includes.h ***/
  4595. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4596. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4597. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4598. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4599. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4600. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4601. /**
  4602. Encapsulates the logic required to implement a lock-free FIFO.
  4603. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4604. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4605. its position and status when reading or writing to it.
  4606. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4607. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4608. outgoing block should be read from.
  4609. e.g.
  4610. @code
  4611. class MyFifo
  4612. {
  4613. public:
  4614. MyFifo() : abstractFifo (1024)
  4615. {
  4616. }
  4617. void addToFifo (const int* someData, int numItems)
  4618. {
  4619. int start1, size1, start2, size2;
  4620. prepareToWrite (numItems, start1, size1, start2, size2);
  4621. if (size1 > 0)
  4622. copySomeData (myBuffer + start1, someData, size1);
  4623. if (size2 > 0)
  4624. copySomeData (myBuffer + start2, someData + size1, size2);
  4625. finishedWrite (size1 + size2);
  4626. }
  4627. void readFromFifo (int* someData, int numItems)
  4628. {
  4629. int start1, size1, start2, size2;
  4630. prepareToRead (numSamples, start1, size1, start2, size2);
  4631. if (size1 > 0)
  4632. copySomeData (someData, myBuffer + start1, size1);
  4633. if (size2 > 0)
  4634. copySomeData (someData + size1, myBuffer + start2, size2);
  4635. finishedRead (size1 + size2);
  4636. }
  4637. private:
  4638. AbstractFifo abstractFifo;
  4639. int myBuffer [1024];
  4640. };
  4641. @endcode
  4642. */
  4643. class JUCE_API AbstractFifo
  4644. {
  4645. public:
  4646. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4647. AbstractFifo (int capacity) noexcept;
  4648. /** Destructor */
  4649. ~AbstractFifo();
  4650. /** Returns the total size of the buffer being managed. */
  4651. int getTotalSize() const noexcept;
  4652. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4653. int getFreeSpace() const noexcept;
  4654. /** Returns the number of items that can currently be read from the buffer. */
  4655. int getNumReady() const noexcept;
  4656. /** Clears the buffer positions, so that it appears empty. */
  4657. void reset() noexcept;
  4658. /** Changes the buffer's total size.
  4659. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4660. might overlap with a call to any other method in this class!
  4661. */
  4662. void setTotalSize (int newSize) noexcept;
  4663. /** Returns the location within the buffer at which an incoming block of data should be written.
  4664. Because the section of data that you want to add to the buffer may overlap the end
  4665. and wrap around to the start, two blocks within your buffer are returned, and you
  4666. should copy your data into the first one, with any remaining data spilling over into
  4667. the second.
  4668. If the number of items you ask for is too large to fit within the buffer's free space, then
  4669. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4670. may decide to keep waiting and re-trying the method until there's enough space available.
  4671. After calling this method, if you choose to write your data into the blocks returned, you
  4672. must call finishedWrite() to tell the FIFO how much data you actually added.
  4673. e.g.
  4674. @code
  4675. void addToFifo (const int* someData, int numItems)
  4676. {
  4677. int start1, size1, start2, size2;
  4678. prepareToWrite (numItems, start1, size1, start2, size2);
  4679. if (size1 > 0)
  4680. copySomeData (myBuffer + start1, someData, size1);
  4681. if (size2 > 0)
  4682. copySomeData (myBuffer + start2, someData + size1, size2);
  4683. finishedWrite (size1 + size2);
  4684. }
  4685. @endcode
  4686. @param numToWrite indicates how many items you'd like to add to the buffer
  4687. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4688. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4689. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4690. the first block should be written
  4691. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4692. @see finishedWrite
  4693. */
  4694. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4695. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4696. @see prepareToWrite
  4697. */
  4698. void finishedWrite (int numWritten) noexcept;
  4699. /** Returns the location within the buffer from which the next block of data should be read.
  4700. Because the section of data that you want to read from the buffer may overlap the end
  4701. and wrap around to the start, two blocks within your buffer are returned, and you
  4702. should read from both of them.
  4703. If the number of items you ask for is greater than the amount of data available, then
  4704. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4705. may decide to keep waiting and re-trying the method until there's enough data available.
  4706. After calling this method, if you choose to read the data, you must call finishedRead() to
  4707. tell the FIFO how much data you have consumed.
  4708. e.g.
  4709. @code
  4710. void readFromFifo (int* someData, int numItems)
  4711. {
  4712. int start1, size1, start2, size2;
  4713. prepareToRead (numSamples, start1, size1, start2, size2);
  4714. if (size1 > 0)
  4715. copySomeData (someData, myBuffer + start1, size1);
  4716. if (size2 > 0)
  4717. copySomeData (someData + size1, myBuffer + start2, size2);
  4718. finishedRead (size1 + size2);
  4719. }
  4720. @endcode
  4721. @param numWanted indicates how many items you'd like to add to the buffer
  4722. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4723. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4724. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4725. the first block should be written
  4726. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4727. @see finishedRead
  4728. */
  4729. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4730. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4731. @see prepareToRead
  4732. */
  4733. void finishedRead (int numRead) noexcept;
  4734. private:
  4735. int bufferSize;
  4736. Atomic <int> validStart, validEnd;
  4737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4738. };
  4739. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4740. /*** End of inlined file: juce_AbstractFifo.h ***/
  4741. #endif
  4742. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4743. /*** Start of inlined file: juce_Array.h ***/
  4744. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4745. #define __JUCE_ARRAY_JUCEHEADER__
  4746. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4747. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4748. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4749. /*** Start of inlined file: juce_HeapBlock.h ***/
  4750. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4751. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4752. /**
  4753. Very simple container class to hold a pointer to some data on the heap.
  4754. When you need to allocate some heap storage for something, always try to use
  4755. this class instead of allocating the memory directly using malloc/free.
  4756. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4757. as an char*, but as long as you allocate it on the stack or as a class member,
  4758. it's almost impossible for it to leak memory.
  4759. It also makes your code much more concise and readable than doing the same thing
  4760. using direct allocations,
  4761. E.g. instead of this:
  4762. @code
  4763. int* temp = (int*) malloc (1024 * sizeof (int));
  4764. memcpy (temp, xyz, 1024 * sizeof (int));
  4765. free (temp);
  4766. temp = (int*) calloc (2048 * sizeof (int));
  4767. temp[0] = 1234;
  4768. memcpy (foobar, temp, 2048 * sizeof (int));
  4769. free (temp);
  4770. @endcode
  4771. ..you could just write this:
  4772. @code
  4773. HeapBlock <int> temp (1024);
  4774. memcpy (temp, xyz, 1024 * sizeof (int));
  4775. temp.calloc (2048);
  4776. temp[0] = 1234;
  4777. memcpy (foobar, temp, 2048 * sizeof (int));
  4778. @endcode
  4779. The class is extremely lightweight, containing only a pointer to the
  4780. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4781. as their less object-oriented counterparts. Despite adding safety, you probably
  4782. won't sacrifice any performance by using this in place of normal pointers.
  4783. @see Array, OwnedArray, MemoryBlock
  4784. */
  4785. template <class ElementType>
  4786. class HeapBlock
  4787. {
  4788. public:
  4789. /** Creates a HeapBlock which is initially just a null pointer.
  4790. After creation, you can resize the array using the malloc(), calloc(),
  4791. or realloc() methods.
  4792. */
  4793. HeapBlock() noexcept : data (nullptr)
  4794. {
  4795. }
  4796. /** Creates a HeapBlock containing a number of elements.
  4797. The contents of the block are undefined, as it will have been created by a
  4798. malloc call.
  4799. If you want an array of zero values, you can use the calloc() method instead.
  4800. */
  4801. explicit HeapBlock (const size_t numElements)
  4802. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4803. {
  4804. }
  4805. /** Destructor.
  4806. This will free the data, if any has been allocated.
  4807. */
  4808. ~HeapBlock()
  4809. {
  4810. ::free (data);
  4811. }
  4812. /** Returns a raw pointer to the allocated data.
  4813. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4814. freed by calling the free() method.
  4815. */
  4816. inline operator ElementType*() const noexcept { return data; }
  4817. /** Returns a raw pointer to the allocated data.
  4818. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4819. freed by calling the free() method.
  4820. */
  4821. inline ElementType* getData() const noexcept { return data; }
  4822. /** Returns a void pointer to the allocated data.
  4823. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4824. freed by calling the free() method.
  4825. */
  4826. inline operator void*() const noexcept { return static_cast <void*> (data); }
  4827. /** Returns a void pointer to the allocated data.
  4828. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4829. freed by calling the free() method.
  4830. */
  4831. inline operator const void*() const noexcept { return static_cast <const void*> (data); }
  4832. /** Lets you use indirect calls to the first element in the array.
  4833. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4834. be referencing a null pointer.
  4835. */
  4836. inline ElementType* operator->() const noexcept { return data; }
  4837. /** Returns a reference to one of the data elements.
  4838. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4839. has no idea of the size it currently has allocated.
  4840. */
  4841. template <typename IndexType>
  4842. inline ElementType& operator[] (IndexType index) const noexcept { return data [index]; }
  4843. /** Returns a pointer to a data element at an offset from the start of the array.
  4844. This is the same as doing pointer arithmetic on the raw pointer itself.
  4845. */
  4846. template <typename IndexType>
  4847. inline ElementType* operator+ (IndexType index) const noexcept { return data + index; }
  4848. /** Compares the pointer with another pointer.
  4849. This can be handy for checking whether this is a null pointer.
  4850. */
  4851. inline bool operator== (const ElementType* const otherPointer) const noexcept { return otherPointer == data; }
  4852. /** Compares the pointer with another pointer.
  4853. This can be handy for checking whether this is a null pointer.
  4854. */
  4855. inline bool operator!= (const ElementType* const otherPointer) const noexcept { return otherPointer != data; }
  4856. /** Allocates a specified amount of memory.
  4857. This uses the normal malloc to allocate an amount of memory for this object.
  4858. Any previously allocated memory will be freed by this method.
  4859. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4860. you wouldn't need to specify the second parameter, but it can be handy if you need
  4861. to allocate a size in bytes rather than in terms of the number of elements.
  4862. The data that is allocated will be freed when this object is deleted, or when you
  4863. call free() or any of the allocation methods.
  4864. */
  4865. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4866. {
  4867. ::free (data);
  4868. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4869. }
  4870. /** Allocates a specified amount of memory and clears it.
  4871. This does the same job as the malloc() method, but clears the memory that it allocates.
  4872. */
  4873. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4874. {
  4875. ::free (data);
  4876. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4877. }
  4878. /** Allocates a specified amount of memory and optionally clears it.
  4879. This does the same job as either malloc() or calloc(), depending on the
  4880. initialiseToZero parameter.
  4881. */
  4882. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4883. {
  4884. ::free (data);
  4885. if (initialiseToZero)
  4886. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4887. else
  4888. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4889. }
  4890. /** Re-allocates a specified amount of memory.
  4891. The semantics of this method are the same as malloc() and calloc(), but it
  4892. uses realloc() to keep as much of the existing data as possible.
  4893. */
  4894. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4895. {
  4896. if (data == nullptr)
  4897. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4898. else
  4899. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4900. }
  4901. /** Frees any currently-allocated data.
  4902. This will free the data and reset this object to be a null pointer.
  4903. */
  4904. void free()
  4905. {
  4906. ::free (data);
  4907. data = nullptr;
  4908. }
  4909. /** Swaps this object's data with the data of another HeapBlock.
  4910. The two objects simply exchange their data pointers.
  4911. */
  4912. void swapWith (HeapBlock <ElementType>& other) noexcept
  4913. {
  4914. std::swap (data, other.data);
  4915. }
  4916. /** This fills the block with zeros, up to the number of elements specified.
  4917. Since the block has no way of knowing its own size, you must make sure that the number of
  4918. elements you specify doesn't exceed the allocated size.
  4919. */
  4920. void clear (size_t numElements) noexcept
  4921. {
  4922. zeromem (data, sizeof (ElementType) * numElements);
  4923. }
  4924. private:
  4925. ElementType* data;
  4926. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4927. };
  4928. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4929. /*** End of inlined file: juce_HeapBlock.h ***/
  4930. /**
  4931. Implements some basic array storage allocation functions.
  4932. This class isn't really for public use - it's used by the other
  4933. array classes, but might come in handy for some purposes.
  4934. It inherits from a critical section class to allow the arrays to use
  4935. the "empty base class optimisation" pattern to reduce their footprint.
  4936. @see Array, OwnedArray, ReferenceCountedArray
  4937. */
  4938. template <class ElementType, class TypeOfCriticalSectionToUse>
  4939. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4940. {
  4941. public:
  4942. /** Creates an empty array. */
  4943. ArrayAllocationBase() noexcept
  4944. : numAllocated (0)
  4945. {
  4946. }
  4947. /** Destructor. */
  4948. ~ArrayAllocationBase()
  4949. {
  4950. }
  4951. /** Changes the amount of storage allocated.
  4952. This will retain any data currently held in the array, and either add or
  4953. remove extra space at the end.
  4954. @param numElements the number of elements that are needed
  4955. */
  4956. void setAllocatedSize (const int numElements)
  4957. {
  4958. if (numAllocated != numElements)
  4959. {
  4960. if (numElements > 0)
  4961. elements.realloc (numElements);
  4962. else
  4963. elements.free();
  4964. numAllocated = numElements;
  4965. }
  4966. }
  4967. /** Increases the amount of storage allocated if it is less than a given amount.
  4968. This will retain any data currently held in the array, but will add
  4969. extra space at the end to make sure there it's at least as big as the size
  4970. passed in. If it's already bigger, no action is taken.
  4971. @param minNumElements the minimum number of elements that are needed
  4972. */
  4973. void ensureAllocatedSize (const int minNumElements)
  4974. {
  4975. if (minNumElements > numAllocated)
  4976. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4977. }
  4978. /** Minimises the amount of storage allocated so that it's no more than
  4979. the given number of elements.
  4980. */
  4981. void shrinkToNoMoreThan (const int maxNumElements)
  4982. {
  4983. if (maxNumElements < numAllocated)
  4984. setAllocatedSize (maxNumElements);
  4985. }
  4986. /** Swap the contents of two objects. */
  4987. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) noexcept
  4988. {
  4989. elements.swapWith (other.elements);
  4990. std::swap (numAllocated, other.numAllocated);
  4991. }
  4992. HeapBlock <ElementType> elements;
  4993. int numAllocated;
  4994. private:
  4995. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4996. };
  4997. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4998. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4999. /*** Start of inlined file: juce_ElementComparator.h ***/
  5000. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5001. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5002. /**
  5003. Sorts a range of elements in an array.
  5004. The comparator object that is passed-in must define a public method with the following
  5005. signature:
  5006. @code
  5007. int compareElements (ElementType first, ElementType second);
  5008. @endcode
  5009. ..and this method must return:
  5010. - a value of < 0 if the first comes before the second
  5011. - a value of 0 if the two objects are equivalent
  5012. - a value of > 0 if the second comes before the first
  5013. To improve performance, the compareElements() method can be declared as static or const.
  5014. @param comparator an object which defines a compareElements() method
  5015. @param array the array to sort
  5016. @param firstElement the index of the first element of the range to be sorted
  5017. @param lastElement the index of the last element in the range that needs
  5018. sorting (this is inclusive)
  5019. @param retainOrderOfEquivalentItems if true, the order of items that the
  5020. comparator deems the same will be maintained - this will be
  5021. a slower algorithm than if they are allowed to be moved around.
  5022. @see sortArrayRetainingOrder
  5023. */
  5024. template <class ElementType, class ElementComparator>
  5025. static void sortArray (ElementComparator& comparator,
  5026. ElementType* const array,
  5027. int firstElement,
  5028. int lastElement,
  5029. const bool retainOrderOfEquivalentItems)
  5030. {
  5031. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5032. // avoids getting warning messages about the parameter being unused
  5033. if (lastElement > firstElement)
  5034. {
  5035. if (retainOrderOfEquivalentItems)
  5036. {
  5037. for (int i = firstElement; i < lastElement; ++i)
  5038. {
  5039. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5040. {
  5041. std::swap (array[i], array[i + 1]);
  5042. if (i > firstElement)
  5043. i -= 2;
  5044. }
  5045. }
  5046. }
  5047. else
  5048. {
  5049. int fromStack[30], toStack[30];
  5050. int stackIndex = 0;
  5051. for (;;)
  5052. {
  5053. const int size = (lastElement - firstElement) + 1;
  5054. if (size <= 8)
  5055. {
  5056. int j = lastElement;
  5057. int maxIndex;
  5058. while (j > firstElement)
  5059. {
  5060. maxIndex = firstElement;
  5061. for (int k = firstElement + 1; k <= j; ++k)
  5062. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5063. maxIndex = k;
  5064. std::swap (array[j], array[maxIndex]);
  5065. --j;
  5066. }
  5067. }
  5068. else
  5069. {
  5070. const int mid = firstElement + (size >> 1);
  5071. std::swap (array[mid], array[firstElement]);
  5072. int i = firstElement;
  5073. int j = lastElement + 1;
  5074. for (;;)
  5075. {
  5076. while (++i <= lastElement
  5077. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5078. {}
  5079. while (--j > firstElement
  5080. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5081. {}
  5082. if (j < i)
  5083. break;
  5084. std::swap (array[i], array[j]);
  5085. }
  5086. std::swap (array[j], array[firstElement]);
  5087. if (j - 1 - firstElement >= lastElement - i)
  5088. {
  5089. if (firstElement + 1 < j)
  5090. {
  5091. fromStack [stackIndex] = firstElement;
  5092. toStack [stackIndex] = j - 1;
  5093. ++stackIndex;
  5094. }
  5095. if (i < lastElement)
  5096. {
  5097. firstElement = i;
  5098. continue;
  5099. }
  5100. }
  5101. else
  5102. {
  5103. if (i < lastElement)
  5104. {
  5105. fromStack [stackIndex] = i;
  5106. toStack [stackIndex] = lastElement;
  5107. ++stackIndex;
  5108. }
  5109. if (firstElement + 1 < j)
  5110. {
  5111. lastElement = j - 1;
  5112. continue;
  5113. }
  5114. }
  5115. }
  5116. if (--stackIndex < 0)
  5117. break;
  5118. jassert (stackIndex < numElementsInArray (fromStack));
  5119. firstElement = fromStack [stackIndex];
  5120. lastElement = toStack [stackIndex];
  5121. }
  5122. }
  5123. }
  5124. }
  5125. /**
  5126. Searches a sorted array of elements, looking for the index at which a specified value
  5127. should be inserted for it to be in the correct order.
  5128. The comparator object that is passed-in must define a public method with the following
  5129. signature:
  5130. @code
  5131. int compareElements (ElementType first, ElementType second);
  5132. @endcode
  5133. ..and this method must return:
  5134. - a value of < 0 if the first comes before the second
  5135. - a value of 0 if the two objects are equivalent
  5136. - a value of > 0 if the second comes before the first
  5137. To improve performance, the compareElements() method can be declared as static or const.
  5138. @param comparator an object which defines a compareElements() method
  5139. @param array the array to search
  5140. @param newElement the value that is going to be inserted
  5141. @param firstElement the index of the first element to search
  5142. @param lastElement the index of the last element in the range (this is non-inclusive)
  5143. */
  5144. template <class ElementType, class ElementComparator>
  5145. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5146. ElementType* const array,
  5147. const ElementType newElement,
  5148. int firstElement,
  5149. int lastElement)
  5150. {
  5151. jassert (firstElement <= lastElement);
  5152. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5153. // avoids getting warning messages about the parameter being unused
  5154. while (firstElement < lastElement)
  5155. {
  5156. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5157. {
  5158. ++firstElement;
  5159. break;
  5160. }
  5161. else
  5162. {
  5163. const int halfway = (firstElement + lastElement) >> 1;
  5164. if (halfway == firstElement)
  5165. {
  5166. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5167. ++firstElement;
  5168. break;
  5169. }
  5170. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5171. {
  5172. firstElement = halfway;
  5173. }
  5174. else
  5175. {
  5176. lastElement = halfway;
  5177. }
  5178. }
  5179. }
  5180. return firstElement;
  5181. }
  5182. /**
  5183. A simple ElementComparator class that can be used to sort an array of
  5184. objects that support the '<' operator.
  5185. This will work for primitive types and objects that implement operator<().
  5186. Example: @code
  5187. Array <int> myArray;
  5188. DefaultElementComparator<int> sorter;
  5189. myArray.sort (sorter);
  5190. @endcode
  5191. @see ElementComparator
  5192. */
  5193. template <class ElementType>
  5194. class DefaultElementComparator
  5195. {
  5196. private:
  5197. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5198. public:
  5199. static int compareElements (ParameterType first, ParameterType second)
  5200. {
  5201. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5202. }
  5203. };
  5204. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5205. /*** End of inlined file: juce_ElementComparator.h ***/
  5206. /*** Start of inlined file: juce_CriticalSection.h ***/
  5207. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5208. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5209. /*** Start of inlined file: juce_ScopedLock.h ***/
  5210. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5211. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5212. /**
  5213. Automatically locks and unlocks a mutex object.
  5214. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5215. The templated class could be a CriticalSection, SpinLock, or anything else that
  5216. provides enter() and exit() methods.
  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...
  5224. // myCriticalSection gets unlocked here.
  5225. }
  5226. @endcode
  5227. @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock
  5228. */
  5229. template <class LockType>
  5230. class GenericScopedLock
  5231. {
  5232. public:
  5233. /** Creates a GenericScopedLock.
  5234. As soon as it is created, this will acquire the lock, and when the GenericScopedLock
  5235. object is deleted, the lock will be released.
  5236. Make sure this object is created and deleted by the same thread,
  5237. otherwise there are no guarantees what will happen! Best just to use it
  5238. as a local stack object, rather than creating one with the new() operator.
  5239. */
  5240. inline explicit GenericScopedLock (const LockType& lock) noexcept : lock_ (lock) { lock.enter(); }
  5241. /** Destructor.
  5242. The lock will be released when the destructor is called.
  5243. Make sure this object is created and deleted by the same thread, otherwise there are
  5244. no guarantees what will happen!
  5245. */
  5246. inline ~GenericScopedLock() noexcept { lock_.exit(); }
  5247. private:
  5248. const LockType& lock_;
  5249. JUCE_DECLARE_NON_COPYABLE (GenericScopedLock);
  5250. };
  5251. /**
  5252. Automatically unlocks and re-locks a mutex object.
  5253. This is the reverse of a GenericScopedLock object - instead of locking the mutex
  5254. for the lifetime of this object, it unlocks it.
  5255. Make sure you don't try to unlock mutexes that aren't actually locked!
  5256. e.g. @code
  5257. CriticalSection myCriticalSection;
  5258. for (;;)
  5259. {
  5260. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5261. // myCriticalSection is now locked
  5262. ... do some stuff with it locked ..
  5263. while (xyz)
  5264. {
  5265. ... do some stuff with it locked ..
  5266. const GenericScopedUnlock<CriticalSection> unlocker (myCriticalSection);
  5267. // myCriticalSection is now unlocked for the remainder of this block,
  5268. // and re-locked at the end.
  5269. ...do some stuff with it unlocked ...
  5270. }
  5271. // myCriticalSection gets unlocked here.
  5272. }
  5273. @endcode
  5274. @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock
  5275. */
  5276. template <class LockType>
  5277. class GenericScopedUnlock
  5278. {
  5279. public:
  5280. /** Creates a GenericScopedUnlock.
  5281. As soon as it is created, this will unlock the CriticalSection, and
  5282. when the ScopedLock object is deleted, the CriticalSection will
  5283. be re-locked.
  5284. Make sure this object is created and deleted by the same thread,
  5285. otherwise there are no guarantees what will happen! Best just to use it
  5286. as a local stack object, rather than creating one with the new() operator.
  5287. */
  5288. inline explicit GenericScopedUnlock (const LockType& lock) noexcept : lock_ (lock) { lock.exit(); }
  5289. /** Destructor.
  5290. The CriticalSection will be unlocked when the destructor is called.
  5291. Make sure this object is created and deleted by the same thread,
  5292. otherwise there are no guarantees what will happen!
  5293. */
  5294. inline ~GenericScopedUnlock() noexcept { lock_.enter(); }
  5295. private:
  5296. const LockType& lock_;
  5297. JUCE_DECLARE_NON_COPYABLE (GenericScopedUnlock);
  5298. };
  5299. /**
  5300. Automatically locks and unlocks a mutex object.
  5301. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5302. The templated class could be a CriticalSection, SpinLock, or anything else that
  5303. provides enter() and exit() methods.
  5304. e.g. @code
  5305. CriticalSection myCriticalSection;
  5306. for (;;)
  5307. {
  5308. const GenericScopedTryLock<CriticalSection> myScopedTryLock (myCriticalSection);
  5309. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5310. // should test this with the isLocked() method before doing your thread-unsafe
  5311. // action..
  5312. if (myScopedTryLock.isLocked())
  5313. {
  5314. ...do some stuff...
  5315. }
  5316. else
  5317. {
  5318. ..our attempt at locking failed because another thread had already locked it..
  5319. }
  5320. // myCriticalSection gets unlocked here (if it was locked)
  5321. }
  5322. @endcode
  5323. @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock
  5324. */
  5325. template <class LockType>
  5326. class GenericScopedTryLock
  5327. {
  5328. public:
  5329. /** Creates a GenericScopedTryLock.
  5330. As soon as it is created, this will attempt to acquire the lock, and when the
  5331. GenericScopedTryLock is deleted, the lock will be released (if the lock was
  5332. successfully acquired).
  5333. Make sure this object is created and deleted by the same thread,
  5334. otherwise there are no guarantees what will happen! Best just to use it
  5335. as a local stack object, rather than creating one with the new() operator.
  5336. */
  5337. inline explicit GenericScopedTryLock (const LockType& lock) noexcept
  5338. : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  5339. /** Destructor.
  5340. The mutex will be unlocked (if it had been successfully locked) when the
  5341. destructor is called.
  5342. Make sure this object is created and deleted by the same thread,
  5343. otherwise there are no guarantees what will happen!
  5344. */
  5345. inline ~GenericScopedTryLock() noexcept { if (lockWasSuccessful) lock_.exit(); }
  5346. /** Returns true if the mutex was successfully locked. */
  5347. bool isLocked() const noexcept { return lockWasSuccessful; }
  5348. private:
  5349. const LockType& lock_;
  5350. const bool lockWasSuccessful;
  5351. JUCE_DECLARE_NON_COPYABLE (GenericScopedTryLock);
  5352. };
  5353. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5354. /*** End of inlined file: juce_ScopedLock.h ***/
  5355. /**
  5356. A mutex class.
  5357. A CriticalSection acts as a re-entrant mutex lock. The best way to lock and unlock
  5358. one of these is by using RAII in the form of a local ScopedLock object - have a look
  5359. through the codebase for many examples of how to do this.
  5360. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  5361. */
  5362. class JUCE_API CriticalSection
  5363. {
  5364. public:
  5365. /** Creates a CriticalSection object. */
  5366. CriticalSection() noexcept;
  5367. /** Destructor.
  5368. If the critical section is deleted whilst locked, any subsequent behaviour
  5369. is unpredictable.
  5370. */
  5371. ~CriticalSection() noexcept;
  5372. /** Acquires the lock.
  5373. If the lock is already held by the caller thread, the method returns immediately.
  5374. If the lock is currently held by another thread, this will wait until it becomes free.
  5375. It's strongly recommended that you never call this method directly - instead use the
  5376. ScopedLock class to manage the locking using an RAII pattern instead.
  5377. @see exit, tryEnter, ScopedLock
  5378. */
  5379. void enter() const noexcept;
  5380. /** Attempts to lock this critical section without blocking.
  5381. This method behaves identically to CriticalSection::enter, except that the caller thread
  5382. does not wait if the lock is currently held by another thread but returns false immediately.
  5383. @returns false if the lock is currently held by another thread, true otherwise.
  5384. @see enter
  5385. */
  5386. bool tryEnter() const noexcept;
  5387. /** Releases the lock.
  5388. If the caller thread hasn't got the lock, this can have unpredictable results.
  5389. If the enter() method has been called multiple times by the thread, each
  5390. call must be matched by a call to exit() before other threads will be allowed
  5391. to take over the lock.
  5392. @see enter, ScopedLock
  5393. */
  5394. void exit() const noexcept;
  5395. /** Provides the type of scoped lock to use with a CriticalSection. */
  5396. typedef GenericScopedLock <CriticalSection> ScopedLockType;
  5397. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  5398. typedef GenericScopedUnlock <CriticalSection> ScopedUnlockType;
  5399. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  5400. typedef GenericScopedTryLock <CriticalSection> ScopedTryLockType;
  5401. private:
  5402. #if JUCE_WINDOWS
  5403. // To avoid including windows.h in the public JUCE headers, we'll just allocate a
  5404. // block of memory here that's big enough to be used internally as a windows critical
  5405. // section structure.
  5406. #if JUCE_64BIT
  5407. uint8 internal [44];
  5408. #else
  5409. uint8 internal [24];
  5410. #endif
  5411. #else
  5412. mutable pthread_mutex_t internal;
  5413. #endif
  5414. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5415. };
  5416. /**
  5417. A class that can be used in place of a real CriticalSection object, but which
  5418. doesn't perform any locking.
  5419. This is currently used by some templated classes, and most compilers should
  5420. manage to optimise it out of existence.
  5421. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  5422. */
  5423. class JUCE_API DummyCriticalSection
  5424. {
  5425. public:
  5426. inline DummyCriticalSection() noexcept {}
  5427. inline ~DummyCriticalSection() noexcept {}
  5428. inline void enter() const noexcept {}
  5429. inline bool tryEnter() const noexcept { return true; }
  5430. inline void exit() const noexcept {}
  5431. /** A dummy scoped-lock type to use with a dummy critical section. */
  5432. struct ScopedLockType
  5433. {
  5434. ScopedLockType (const DummyCriticalSection&) noexcept {}
  5435. };
  5436. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5437. typedef ScopedLockType ScopedUnlockType;
  5438. private:
  5439. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5440. };
  5441. /**
  5442. Automatically locks and unlocks a CriticalSection object.
  5443. Use one of these as a local variable to provide RAII-based locking of a CriticalSection.
  5444. e.g. @code
  5445. CriticalSection myCriticalSection;
  5446. for (;;)
  5447. {
  5448. const ScopedLock myScopedLock (myCriticalSection);
  5449. // myCriticalSection is now locked
  5450. ...do some stuff...
  5451. // myCriticalSection gets unlocked here.
  5452. }
  5453. @endcode
  5454. @see CriticalSection, ScopedUnlock
  5455. */
  5456. typedef CriticalSection::ScopedLockType ScopedLock;
  5457. /**
  5458. Automatically unlocks and re-locks a CriticalSection object.
  5459. This is the reverse of a ScopedLock object - instead of locking the critical
  5460. section for the lifetime of this object, it unlocks it.
  5461. Make sure you don't try to unlock critical sections that aren't actually locked!
  5462. e.g. @code
  5463. CriticalSection myCriticalSection;
  5464. for (;;)
  5465. {
  5466. const ScopedLock myScopedLock (myCriticalSection);
  5467. // myCriticalSection is now locked
  5468. ... do some stuff with it locked ..
  5469. while (xyz)
  5470. {
  5471. ... do some stuff with it locked ..
  5472. const ScopedUnlock unlocker (myCriticalSection);
  5473. // myCriticalSection is now unlocked for the remainder of this block,
  5474. // and re-locked at the end.
  5475. ...do some stuff with it unlocked ...
  5476. }
  5477. // myCriticalSection gets unlocked here.
  5478. }
  5479. @endcode
  5480. @see CriticalSection, ScopedLock
  5481. */
  5482. typedef CriticalSection::ScopedUnlockType ScopedUnlock;
  5483. /**
  5484. Automatically tries to lock and unlock a CriticalSection object.
  5485. Use one of these as a local variable to control access to a CriticalSection.
  5486. e.g. @code
  5487. CriticalSection myCriticalSection;
  5488. for (;;)
  5489. {
  5490. const ScopedTryLock myScopedTryLock (myCriticalSection);
  5491. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5492. // should test this with the isLocked() method before doing your thread-unsafe
  5493. // action..
  5494. if (myScopedTryLock.isLocked())
  5495. {
  5496. ...do some stuff...
  5497. }
  5498. else
  5499. {
  5500. ..our attempt at locking failed because another thread had already locked it..
  5501. }
  5502. // myCriticalSection gets unlocked here (if it was locked)
  5503. }
  5504. @endcode
  5505. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  5506. */
  5507. typedef CriticalSection::ScopedTryLockType ScopedTryLock;
  5508. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5509. /*** End of inlined file: juce_CriticalSection.h ***/
  5510. /**
  5511. Holds a resizable array of primitive or copy-by-value objects.
  5512. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5513. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5514. do so, the class must fulfil these requirements:
  5515. - it must have a copy constructor and assignment operator
  5516. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5517. objects whose functionality relies on external pointers or references to themselves can be used.
  5518. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5519. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5520. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5521. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5522. specialised class StringArray, which provides more useful functions.
  5523. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5524. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5525. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5526. */
  5527. template <typename ElementType,
  5528. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5529. class Array
  5530. {
  5531. private:
  5532. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5533. public:
  5534. /** Creates an empty array. */
  5535. Array() noexcept
  5536. : numUsed (0)
  5537. {
  5538. }
  5539. /** Creates a copy of another array.
  5540. @param other the array to copy
  5541. */
  5542. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5543. {
  5544. const ScopedLockType lock (other.getLock());
  5545. numUsed = other.numUsed;
  5546. data.setAllocatedSize (other.numUsed);
  5547. for (int i = 0; i < numUsed; ++i)
  5548. new (data.elements + i) ElementType (other.data.elements[i]);
  5549. }
  5550. /** Initalises from a null-terminated C array of values.
  5551. @param values the array to copy from
  5552. */
  5553. template <typename TypeToCreateFrom>
  5554. explicit Array (const TypeToCreateFrom* values)
  5555. : numUsed (0)
  5556. {
  5557. while (*values != TypeToCreateFrom())
  5558. add (*values++);
  5559. }
  5560. /** Initalises from a C array of values.
  5561. @param values the array to copy from
  5562. @param numValues the number of values in the array
  5563. */
  5564. template <typename TypeToCreateFrom>
  5565. Array (const TypeToCreateFrom* values, int numValues)
  5566. : numUsed (numValues)
  5567. {
  5568. data.setAllocatedSize (numValues);
  5569. for (int i = 0; i < numValues; ++i)
  5570. new (data.elements + i) ElementType (values[i]);
  5571. }
  5572. /** Destructor. */
  5573. ~Array()
  5574. {
  5575. for (int i = 0; i < numUsed; ++i)
  5576. data.elements[i].~ElementType();
  5577. }
  5578. /** Copies another array.
  5579. @param other the array to copy
  5580. */
  5581. Array& operator= (const Array& other)
  5582. {
  5583. if (this != &other)
  5584. {
  5585. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5586. swapWithArray (otherCopy);
  5587. }
  5588. return *this;
  5589. }
  5590. /** Compares this array to another one.
  5591. Two arrays are considered equal if they both contain the same set of
  5592. elements, in the same order.
  5593. @param other the other array to compare with
  5594. */
  5595. template <class OtherArrayType>
  5596. bool operator== (const OtherArrayType& other) const
  5597. {
  5598. const ScopedLockType lock (getLock());
  5599. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  5600. if (numUsed != other.numUsed)
  5601. return false;
  5602. for (int i = numUsed; --i >= 0;)
  5603. if (! (data.elements [i] == other.data.elements [i]))
  5604. return false;
  5605. return true;
  5606. }
  5607. /** Compares this array to another one.
  5608. Two arrays are considered equal if they both contain the same set of
  5609. elements, in the same order.
  5610. @param other the other array to compare with
  5611. */
  5612. template <class OtherArrayType>
  5613. bool operator!= (const OtherArrayType& other) const
  5614. {
  5615. return ! operator== (other);
  5616. }
  5617. /** Removes all elements from the array.
  5618. This will remove all the elements, and free any storage that the array is
  5619. using. To clear the array without freeing the storage, use the clearQuick()
  5620. method instead.
  5621. @see clearQuick
  5622. */
  5623. void clear()
  5624. {
  5625. const ScopedLockType lock (getLock());
  5626. for (int i = 0; i < numUsed; ++i)
  5627. data.elements[i].~ElementType();
  5628. data.setAllocatedSize (0);
  5629. numUsed = 0;
  5630. }
  5631. /** Removes all elements from the array without freeing the array's allocated storage.
  5632. @see clear
  5633. */
  5634. void clearQuick()
  5635. {
  5636. const ScopedLockType lock (getLock());
  5637. for (int i = 0; i < numUsed; ++i)
  5638. data.elements[i].~ElementType();
  5639. numUsed = 0;
  5640. }
  5641. /** Returns the current number of elements in the array.
  5642. */
  5643. inline int size() const noexcept
  5644. {
  5645. return numUsed;
  5646. }
  5647. /** Returns one of the elements in the array.
  5648. If the index passed in is beyond the range of valid elements, this
  5649. will return zero.
  5650. If you're certain that the index will always be a valid element, you
  5651. can call getUnchecked() instead, which is faster.
  5652. @param index the index of the element being requested (0 is the first element in the array)
  5653. @see getUnchecked, getFirst, getLast
  5654. */
  5655. inline ElementType operator[] (const int index) const
  5656. {
  5657. const ScopedLockType lock (getLock());
  5658. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5659. : ElementType();
  5660. }
  5661. /** Returns one of the elements in the array, without checking the index passed in.
  5662. Unlike the operator[] method, this will try to return an element without
  5663. checking that the index is within the bounds of the array, so should only
  5664. be used when you're confident that it will always be a valid index.
  5665. @param index the index of the element being requested (0 is the first element in the array)
  5666. @see operator[], getFirst, getLast
  5667. */
  5668. inline const ElementType getUnchecked (const int index) const
  5669. {
  5670. const ScopedLockType lock (getLock());
  5671. jassert (isPositiveAndBelow (index, numUsed));
  5672. return data.elements [index];
  5673. }
  5674. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5675. This is like getUnchecked, but returns a direct reference to the element, so that
  5676. you can alter it directly. Obviously this can be dangerous, so only use it when
  5677. absolutely necessary.
  5678. @param index the index of the element being requested (0 is the first element in the array)
  5679. @see operator[], getFirst, getLast
  5680. */
  5681. inline ElementType& getReference (const int index) const noexcept
  5682. {
  5683. const ScopedLockType lock (getLock());
  5684. jassert (isPositiveAndBelow (index, numUsed));
  5685. return data.elements [index];
  5686. }
  5687. /** Returns the first element in the array, or 0 if the array is empty.
  5688. @see operator[], getUnchecked, getLast
  5689. */
  5690. inline ElementType getFirst() const
  5691. {
  5692. const ScopedLockType lock (getLock());
  5693. return (numUsed > 0) ? data.elements [0]
  5694. : ElementType();
  5695. }
  5696. /** Returns the last element in the array, or 0 if the array is empty.
  5697. @see operator[], getUnchecked, getFirst
  5698. */
  5699. inline ElementType getLast() const
  5700. {
  5701. const ScopedLockType lock (getLock());
  5702. return (numUsed > 0) ? data.elements [numUsed - 1]
  5703. : ElementType();
  5704. }
  5705. /** Returns a pointer to the actual array data.
  5706. This pointer will only be valid until the next time a non-const method
  5707. is called on the array.
  5708. */
  5709. inline ElementType* getRawDataPointer() noexcept
  5710. {
  5711. return data.elements;
  5712. }
  5713. /** Returns a pointer to the first element in the array.
  5714. This method is provided for compatibility with standard C++ iteration mechanisms.
  5715. */
  5716. inline ElementType* begin() const noexcept
  5717. {
  5718. return data.elements;
  5719. }
  5720. /** Returns a pointer to the element which follows the last element in the array.
  5721. This method is provided for compatibility with standard C++ iteration mechanisms.
  5722. */
  5723. inline ElementType* end() const noexcept
  5724. {
  5725. return data.elements + numUsed;
  5726. }
  5727. /** Finds the index of the first element which matches the value passed in.
  5728. This will search the array for the given object, and return the index
  5729. of its first occurrence. If the object isn't found, the method will return -1.
  5730. @param elementToLookFor the value or object to look for
  5731. @returns the index of the object, or -1 if it's not found
  5732. */
  5733. int indexOf (ParameterType elementToLookFor) const
  5734. {
  5735. const ScopedLockType lock (getLock());
  5736. const ElementType* e = data.elements.getData();
  5737. const ElementType* const end = e + numUsed;
  5738. for (; e != end; ++e)
  5739. if (elementToLookFor == *e)
  5740. return static_cast <int> (e - data.elements.getData());
  5741. return -1;
  5742. }
  5743. /** Returns true if the array contains at least one occurrence of an object.
  5744. @param elementToLookFor the value or object to look for
  5745. @returns true if the item is found
  5746. */
  5747. bool contains (ParameterType elementToLookFor) const
  5748. {
  5749. const ScopedLockType lock (getLock());
  5750. const ElementType* e = data.elements.getData();
  5751. const ElementType* const end = e + numUsed;
  5752. for (; e != end; ++e)
  5753. if (elementToLookFor == *e)
  5754. return true;
  5755. return false;
  5756. }
  5757. /** Appends a new element at the end of the array.
  5758. @param newElement the new object to add to the array
  5759. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5760. */
  5761. void add (ParameterType newElement)
  5762. {
  5763. const ScopedLockType lock (getLock());
  5764. data.ensureAllocatedSize (numUsed + 1);
  5765. new (data.elements + numUsed++) ElementType (newElement);
  5766. }
  5767. /** Inserts a new element into the array at a given position.
  5768. If the index is less than 0 or greater than the size of the array, the
  5769. element will be added to the end of the array.
  5770. Otherwise, it will be inserted into the array, moving all the later elements
  5771. along to make room.
  5772. @param indexToInsertAt the index at which the new element should be
  5773. inserted (pass in -1 to add it to the end)
  5774. @param newElement the new object to add to the array
  5775. @see add, addSorted, addUsingDefaultSort, set
  5776. */
  5777. void insert (int indexToInsertAt, ParameterType newElement)
  5778. {
  5779. const ScopedLockType lock (getLock());
  5780. data.ensureAllocatedSize (numUsed + 1);
  5781. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5782. {
  5783. ElementType* const insertPos = data.elements + indexToInsertAt;
  5784. const int numberToMove = numUsed - indexToInsertAt;
  5785. if (numberToMove > 0)
  5786. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5787. new (insertPos) ElementType (newElement);
  5788. ++numUsed;
  5789. }
  5790. else
  5791. {
  5792. new (data.elements + numUsed++) ElementType (newElement);
  5793. }
  5794. }
  5795. /** Inserts multiple copies of an element into the array at a given position.
  5796. If the index is less than 0 or greater than the size of the array, the
  5797. element will be added to the end of the array.
  5798. Otherwise, it will be inserted into the array, moving all the later elements
  5799. along to make room.
  5800. @param indexToInsertAt the index at which the new element should be inserted
  5801. @param newElement the new object to add to the array
  5802. @param numberOfTimesToInsertIt how many copies of the value to insert
  5803. @see insert, add, addSorted, set
  5804. */
  5805. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5806. int numberOfTimesToInsertIt)
  5807. {
  5808. if (numberOfTimesToInsertIt > 0)
  5809. {
  5810. const ScopedLockType lock (getLock());
  5811. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5812. ElementType* insertPos;
  5813. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5814. {
  5815. insertPos = data.elements + indexToInsertAt;
  5816. const int numberToMove = numUsed - indexToInsertAt;
  5817. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5818. }
  5819. else
  5820. {
  5821. insertPos = data.elements + numUsed;
  5822. }
  5823. numUsed += numberOfTimesToInsertIt;
  5824. while (--numberOfTimesToInsertIt >= 0)
  5825. new (insertPos++) ElementType (newElement);
  5826. }
  5827. }
  5828. /** Inserts an array of values into this array at a given position.
  5829. If the index is less than 0 or greater than the size of the array, the
  5830. new elements will be added to the end of the array.
  5831. Otherwise, they will be inserted into the array, moving all the later elements
  5832. along to make room.
  5833. @param indexToInsertAt the index at which the first new element should be inserted
  5834. @param newElements the new values to add to the array
  5835. @param numberOfElements how many items are in the array
  5836. @see insert, add, addSorted, set
  5837. */
  5838. void insertArray (int indexToInsertAt,
  5839. const ElementType* newElements,
  5840. int numberOfElements)
  5841. {
  5842. if (numberOfElements > 0)
  5843. {
  5844. const ScopedLockType lock (getLock());
  5845. data.ensureAllocatedSize (numUsed + numberOfElements);
  5846. ElementType* insertPos;
  5847. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5848. {
  5849. insertPos = data.elements + indexToInsertAt;
  5850. const int numberToMove = numUsed - indexToInsertAt;
  5851. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5852. }
  5853. else
  5854. {
  5855. insertPos = data.elements + numUsed;
  5856. }
  5857. numUsed += numberOfElements;
  5858. while (--numberOfElements >= 0)
  5859. new (insertPos++) ElementType (*newElements++);
  5860. }
  5861. }
  5862. /** Appends a new element at the end of the array as long as the array doesn't
  5863. already contain it.
  5864. If the array already contains an element that matches the one passed in, nothing
  5865. will be done.
  5866. @param newElement the new object to add to the array
  5867. */
  5868. void addIfNotAlreadyThere (ParameterType newElement)
  5869. {
  5870. const ScopedLockType lock (getLock());
  5871. if (! contains (newElement))
  5872. add (newElement);
  5873. }
  5874. /** Replaces an element with a new value.
  5875. If the index is less than zero, this method does nothing.
  5876. If the index is beyond the end of the array, the item is added to the end of the array.
  5877. @param indexToChange the index whose value you want to change
  5878. @param newValue the new value to set for this index.
  5879. @see add, insert
  5880. */
  5881. void set (const int indexToChange, ParameterType newValue)
  5882. {
  5883. jassert (indexToChange >= 0);
  5884. const ScopedLockType lock (getLock());
  5885. if (isPositiveAndBelow (indexToChange, numUsed))
  5886. {
  5887. data.elements [indexToChange] = newValue;
  5888. }
  5889. else if (indexToChange >= 0)
  5890. {
  5891. data.ensureAllocatedSize (numUsed + 1);
  5892. new (data.elements + numUsed++) ElementType (newValue);
  5893. }
  5894. }
  5895. /** Replaces an element with a new value without doing any bounds-checking.
  5896. This just sets a value directly in the array's internal storage, so you'd
  5897. better make sure it's in range!
  5898. @param indexToChange the index whose value you want to change
  5899. @param newValue the new value to set for this index.
  5900. @see set, getUnchecked
  5901. */
  5902. void setUnchecked (const int indexToChange, ParameterType newValue)
  5903. {
  5904. const ScopedLockType lock (getLock());
  5905. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5906. data.elements [indexToChange] = newValue;
  5907. }
  5908. /** Adds elements from an array to the end of this array.
  5909. @param elementsToAdd the array of elements to add
  5910. @param numElementsToAdd how many elements are in this other array
  5911. @see add
  5912. */
  5913. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5914. {
  5915. const ScopedLockType lock (getLock());
  5916. if (numElementsToAdd > 0)
  5917. {
  5918. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5919. while (--numElementsToAdd >= 0)
  5920. {
  5921. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5922. ++numUsed;
  5923. }
  5924. }
  5925. }
  5926. /** This swaps the contents of this array with those of another array.
  5927. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5928. because it just swaps their internal pointers.
  5929. */
  5930. void swapWithArray (Array& otherArray) noexcept
  5931. {
  5932. const ScopedLockType lock1 (getLock());
  5933. const ScopedLockType lock2 (otherArray.getLock());
  5934. data.swapWith (otherArray.data);
  5935. swapVariables (numUsed, otherArray.numUsed);
  5936. }
  5937. /** Adds elements from another array to the end of this array.
  5938. @param arrayToAddFrom the array from which to copy the elements
  5939. @param startIndex the first element of the other array to start copying from
  5940. @param numElementsToAdd how many elements to add from the other array. If this
  5941. value is negative or greater than the number of available elements,
  5942. all available elements will be copied.
  5943. @see add
  5944. */
  5945. template <class OtherArrayType>
  5946. void addArray (const OtherArrayType& arrayToAddFrom,
  5947. int startIndex = 0,
  5948. int numElementsToAdd = -1)
  5949. {
  5950. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5951. {
  5952. const ScopedLockType lock2 (getLock());
  5953. if (startIndex < 0)
  5954. {
  5955. jassertfalse;
  5956. startIndex = 0;
  5957. }
  5958. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5959. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5960. while (--numElementsToAdd >= 0)
  5961. add (arrayToAddFrom.getUnchecked (startIndex++));
  5962. }
  5963. }
  5964. /** Inserts a new element into the array, assuming that the array is sorted.
  5965. This will use a comparator to find the position at which the new element
  5966. should go. If the array isn't sorted, the behaviour of this
  5967. method will be unpredictable.
  5968. @param comparator the comparator to use to compare the elements - see the sort()
  5969. method for details about the form this object should take
  5970. @param newElement the new element to insert to the array
  5971. @returns the index at which the new item was added
  5972. @see addUsingDefaultSort, add, sort
  5973. */
  5974. template <class ElementComparator>
  5975. int addSorted (ElementComparator& comparator, ParameterType newElement)
  5976. {
  5977. const ScopedLockType lock (getLock());
  5978. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  5979. insert (index, newElement);
  5980. return index;
  5981. }
  5982. /** Inserts a new element into the array, assuming that the array is sorted.
  5983. This will use the DefaultElementComparator class for sorting, so your ElementType
  5984. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5985. method will be unpredictable.
  5986. @param newElement the new element to insert to the array
  5987. @see addSorted, sort
  5988. */
  5989. void addUsingDefaultSort (ParameterType newElement)
  5990. {
  5991. DefaultElementComparator <ElementType> comparator;
  5992. addSorted (comparator, newElement);
  5993. }
  5994. /** Finds the index of an element in the array, assuming that the array is sorted.
  5995. This will use a comparator to do a binary-chop to find the index of the given
  5996. element, if it exists. If the array isn't sorted, the behaviour of this
  5997. method will be unpredictable.
  5998. @param comparator the comparator to use to compare the elements - see the sort()
  5999. method for details about the form this object should take
  6000. @param elementToLookFor the element to search for
  6001. @returns the index of the element, or -1 if it's not found
  6002. @see addSorted, sort
  6003. */
  6004. template <class ElementComparator>
  6005. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  6006. {
  6007. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6008. // avoids getting warning messages about the parameter being unused
  6009. const ScopedLockType lock (getLock());
  6010. int start = 0;
  6011. int end = numUsed;
  6012. for (;;)
  6013. {
  6014. if (start >= end)
  6015. {
  6016. return -1;
  6017. }
  6018. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  6019. {
  6020. return start;
  6021. }
  6022. else
  6023. {
  6024. const int halfway = (start + end) >> 1;
  6025. if (halfway == start)
  6026. return -1;
  6027. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  6028. start = halfway;
  6029. else
  6030. end = halfway;
  6031. }
  6032. }
  6033. }
  6034. /** Removes an element from the array.
  6035. This will remove the element at a given index, and move back
  6036. all the subsequent elements to close the gap.
  6037. If the index passed in is out-of-range, nothing will happen.
  6038. @param indexToRemove the index of the element to remove
  6039. @returns the element that has been removed
  6040. @see removeValue, removeRange
  6041. */
  6042. ElementType remove (const int indexToRemove)
  6043. {
  6044. const ScopedLockType lock (getLock());
  6045. if (isPositiveAndBelow (indexToRemove, numUsed))
  6046. {
  6047. --numUsed;
  6048. ElementType* const e = data.elements + indexToRemove;
  6049. ElementType removed (*e);
  6050. e->~ElementType();
  6051. const int numberToShift = numUsed - indexToRemove;
  6052. if (numberToShift > 0)
  6053. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  6054. if ((numUsed << 1) < data.numAllocated)
  6055. minimiseStorageOverheads();
  6056. return removed;
  6057. }
  6058. else
  6059. {
  6060. return ElementType();
  6061. }
  6062. }
  6063. /** Removes an item from the array.
  6064. This will remove the first occurrence of the given element from the array.
  6065. If the item isn't found, no action is taken.
  6066. @param valueToRemove the object to try to remove
  6067. @see remove, removeRange
  6068. */
  6069. void removeValue (ParameterType valueToRemove)
  6070. {
  6071. const ScopedLockType lock (getLock());
  6072. ElementType* const e = data.elements;
  6073. for (int i = 0; i < numUsed; ++i)
  6074. {
  6075. if (valueToRemove == e[i])
  6076. {
  6077. remove (i);
  6078. break;
  6079. }
  6080. }
  6081. }
  6082. /** Removes a range of elements from the array.
  6083. This will remove a set of elements, starting from the given index,
  6084. and move subsequent elements down to close the gap.
  6085. If the range extends beyond the bounds of the array, it will
  6086. be safely clipped to the size of the array.
  6087. @param startIndex the index of the first element to remove
  6088. @param numberToRemove how many elements should be removed
  6089. @see remove, removeValue
  6090. */
  6091. void removeRange (int startIndex, int numberToRemove)
  6092. {
  6093. const ScopedLockType lock (getLock());
  6094. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  6095. startIndex = jlimit (0, numUsed, startIndex);
  6096. if (endIndex > startIndex)
  6097. {
  6098. ElementType* const e = data.elements + startIndex;
  6099. numberToRemove = endIndex - startIndex;
  6100. for (int i = 0; i < numberToRemove; ++i)
  6101. e[i].~ElementType();
  6102. const int numToShift = numUsed - endIndex;
  6103. if (numToShift > 0)
  6104. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  6105. numUsed -= numberToRemove;
  6106. if ((numUsed << 1) < data.numAllocated)
  6107. minimiseStorageOverheads();
  6108. }
  6109. }
  6110. /** Removes the last n elements from the array.
  6111. @param howManyToRemove how many elements to remove from the end of the array
  6112. @see remove, removeValue, removeRange
  6113. */
  6114. void removeLast (int howManyToRemove = 1)
  6115. {
  6116. const ScopedLockType lock (getLock());
  6117. if (howManyToRemove > numUsed)
  6118. howManyToRemove = numUsed;
  6119. for (int i = 1; i <= howManyToRemove; ++i)
  6120. data.elements [numUsed - i].~ElementType();
  6121. numUsed -= howManyToRemove;
  6122. if ((numUsed << 1) < data.numAllocated)
  6123. minimiseStorageOverheads();
  6124. }
  6125. /** Removes any elements which are also in another array.
  6126. @param otherArray the other array in which to look for elements to remove
  6127. @see removeValuesNotIn, remove, removeValue, removeRange
  6128. */
  6129. template <class OtherArrayType>
  6130. void removeValuesIn (const OtherArrayType& otherArray)
  6131. {
  6132. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6133. const ScopedLockType lock2 (getLock());
  6134. if (this == &otherArray)
  6135. {
  6136. clear();
  6137. }
  6138. else
  6139. {
  6140. if (otherArray.size() > 0)
  6141. {
  6142. for (int i = numUsed; --i >= 0;)
  6143. if (otherArray.contains (data.elements [i]))
  6144. remove (i);
  6145. }
  6146. }
  6147. }
  6148. /** Removes any elements which are not found in another array.
  6149. Only elements which occur in this other array will be retained.
  6150. @param otherArray the array in which to look for elements NOT to remove
  6151. @see removeValuesIn, remove, removeValue, removeRange
  6152. */
  6153. template <class OtherArrayType>
  6154. void removeValuesNotIn (const OtherArrayType& otherArray)
  6155. {
  6156. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6157. const ScopedLockType lock2 (getLock());
  6158. if (this != &otherArray)
  6159. {
  6160. if (otherArray.size() <= 0)
  6161. {
  6162. clear();
  6163. }
  6164. else
  6165. {
  6166. for (int i = numUsed; --i >= 0;)
  6167. if (! otherArray.contains (data.elements [i]))
  6168. remove (i);
  6169. }
  6170. }
  6171. }
  6172. /** Swaps over two elements in the array.
  6173. This swaps over the elements found at the two indexes passed in.
  6174. If either index is out-of-range, this method will do nothing.
  6175. @param index1 index of one of the elements to swap
  6176. @param index2 index of the other element to swap
  6177. */
  6178. void swap (const int index1,
  6179. const int index2)
  6180. {
  6181. const ScopedLockType lock (getLock());
  6182. if (isPositiveAndBelow (index1, numUsed)
  6183. && isPositiveAndBelow (index2, numUsed))
  6184. {
  6185. swapVariables (data.elements [index1],
  6186. data.elements [index2]);
  6187. }
  6188. }
  6189. /** Moves one of the values to a different position.
  6190. This will move the value to a specified index, shuffling along
  6191. any intervening elements as required.
  6192. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6193. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6194. @param currentIndex the index of the value to be moved. If this isn't a
  6195. valid index, then nothing will be done
  6196. @param newIndex the index at which you'd like this value to end up. If this
  6197. is less than zero, the value will be moved to the end
  6198. of the array
  6199. */
  6200. void move (const int currentIndex, int newIndex) noexcept
  6201. {
  6202. if (currentIndex != newIndex)
  6203. {
  6204. const ScopedLockType lock (getLock());
  6205. if (isPositiveAndBelow (currentIndex, numUsed))
  6206. {
  6207. if (! isPositiveAndBelow (newIndex, numUsed))
  6208. newIndex = numUsed - 1;
  6209. char tempCopy [sizeof (ElementType)];
  6210. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  6211. if (newIndex > currentIndex)
  6212. {
  6213. memmove (data.elements + currentIndex,
  6214. data.elements + currentIndex + 1,
  6215. (newIndex - currentIndex) * sizeof (ElementType));
  6216. }
  6217. else
  6218. {
  6219. memmove (data.elements + newIndex + 1,
  6220. data.elements + newIndex,
  6221. (currentIndex - newIndex) * sizeof (ElementType));
  6222. }
  6223. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  6224. }
  6225. }
  6226. }
  6227. /** Reduces the amount of storage being used by the array.
  6228. Arrays typically allocate slightly more storage than they need, and after
  6229. removing elements, they may have quite a lot of unused space allocated.
  6230. This method will reduce the amount of allocated storage to a minimum.
  6231. */
  6232. void minimiseStorageOverheads()
  6233. {
  6234. const ScopedLockType lock (getLock());
  6235. data.shrinkToNoMoreThan (numUsed);
  6236. }
  6237. /** Increases the array's internal storage to hold a minimum number of elements.
  6238. Calling this before adding a large known number of elements means that
  6239. the array won't have to keep dynamically resizing itself as the elements
  6240. are added, and it'll therefore be more efficient.
  6241. */
  6242. void ensureStorageAllocated (const int minNumElements)
  6243. {
  6244. const ScopedLockType lock (getLock());
  6245. data.ensureAllocatedSize (minNumElements);
  6246. }
  6247. /** Sorts the elements in the array.
  6248. This will use a comparator object to sort the elements into order. The object
  6249. passed must have a method of the form:
  6250. @code
  6251. int compareElements (ElementType first, ElementType second);
  6252. @endcode
  6253. ..and this method must return:
  6254. - a value of < 0 if the first comes before the second
  6255. - a value of 0 if the two objects are equivalent
  6256. - a value of > 0 if the second comes before the first
  6257. To improve performance, the compareElements() method can be declared as static or const.
  6258. @param comparator the comparator to use for comparing elements.
  6259. @param retainOrderOfEquivalentItems if this is true, then items
  6260. which the comparator says are equivalent will be
  6261. kept in the order in which they currently appear
  6262. in the array. This is slower to perform, but may
  6263. be important in some cases. If it's false, a faster
  6264. algorithm is used, but equivalent elements may be
  6265. rearranged.
  6266. @see addSorted, indexOfSorted, sortArray
  6267. */
  6268. template <class ElementComparator>
  6269. void sort (ElementComparator& comparator,
  6270. const bool retainOrderOfEquivalentItems = false) const
  6271. {
  6272. const ScopedLockType lock (getLock());
  6273. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6274. // avoids getting warning messages about the parameter being unused
  6275. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6276. }
  6277. /** Returns the CriticalSection that locks this array.
  6278. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6279. an object of ScopedLockType as an RAII lock for it.
  6280. */
  6281. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  6282. /** Returns the type of scoped lock to use for locking this array */
  6283. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6284. private:
  6285. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6286. int numUsed;
  6287. };
  6288. #endif // __JUCE_ARRAY_JUCEHEADER__
  6289. /*** End of inlined file: juce_Array.h ***/
  6290. #endif
  6291. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6292. #endif
  6293. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6294. /*** Start of inlined file: juce_DynamicObject.h ***/
  6295. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6296. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6297. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6298. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6299. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6300. /*** Start of inlined file: juce_Variant.h ***/
  6301. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6302. #define __JUCE_VARIANT_JUCEHEADER__
  6303. /*** Start of inlined file: juce_Identifier.h ***/
  6304. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6305. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6306. /*** Start of inlined file: juce_StringPool.h ***/
  6307. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  6308. #define __JUCE_STRINGPOOL_JUCEHEADER__
  6309. /**
  6310. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  6311. comparison speed when dealing with many duplicate strings.
  6312. When you add a string to a pool using getPooledString, it'll return a character
  6313. array containing the same string. This array is owned by the pool, and the same array
  6314. is returned every time a matching string is asked for. This means that it's trivial to
  6315. compare two pooled strings for equality, as you can simply compare their pointers. It
  6316. also cuts down on storage if you're using many copies of the same string.
  6317. */
  6318. class JUCE_API StringPool
  6319. {
  6320. public:
  6321. /** Creates an empty pool. */
  6322. StringPool() noexcept;
  6323. /** Destructor */
  6324. ~StringPool();
  6325. /** Returns a pointer to a copy of the string that is passed in.
  6326. The pool will always return the same pointer when asked for a string that matches it.
  6327. The pool will own all the pointers that it returns, deleting them when the pool itself
  6328. is deleted.
  6329. */
  6330. const String::CharPointerType getPooledString (const String& original);
  6331. /** Returns a pointer to a copy of the string that is passed in.
  6332. The pool will always return the same pointer when asked for a string that matches it.
  6333. The pool will own all the pointers that it returns, deleting them when the pool itself
  6334. is deleted.
  6335. */
  6336. const String::CharPointerType getPooledString (const char* original);
  6337. /** Returns a pointer to a copy of the string that is passed in.
  6338. The pool will always return the same pointer when asked for a string that matches it.
  6339. The pool will own all the pointers that it returns, deleting them when the pool itself
  6340. is deleted.
  6341. */
  6342. const String::CharPointerType getPooledString (const wchar_t* original);
  6343. /** Returns the number of strings in the pool. */
  6344. int size() const noexcept;
  6345. /** Returns one of the strings in the pool, by index. */
  6346. const String::CharPointerType operator[] (int index) const noexcept;
  6347. private:
  6348. Array <String> strings;
  6349. };
  6350. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  6351. /*** End of inlined file: juce_StringPool.h ***/
  6352. /**
  6353. Represents a string identifier, designed for accessing properties by name.
  6354. Identifier objects are very light and fast to copy, but slower to initialise
  6355. from a string, so it's much faster to keep a static identifier object to refer
  6356. to frequently-used names, rather than constructing them each time you need it.
  6357. @see NamedPropertySet, ValueTree
  6358. */
  6359. class JUCE_API Identifier
  6360. {
  6361. public:
  6362. /** Creates a null identifier. */
  6363. Identifier() noexcept;
  6364. /** Creates an identifier with a specified name.
  6365. Because this name may need to be used in contexts such as script variables or XML
  6366. tags, it must only contain ascii letters and digits, or the underscore character.
  6367. */
  6368. Identifier (const char* name);
  6369. /** Creates an identifier with a specified name.
  6370. Because this name may need to be used in contexts such as script variables or XML
  6371. tags, it must only contain ascii letters and digits, or the underscore character.
  6372. */
  6373. Identifier (const String& name);
  6374. /** Creates a copy of another identifier. */
  6375. Identifier (const Identifier& other) noexcept;
  6376. /** Creates a copy of another identifier. */
  6377. Identifier& operator= (const Identifier& other) noexcept;
  6378. /** Destructor */
  6379. ~Identifier();
  6380. /** Compares two identifiers. This is a very fast operation. */
  6381. inline bool operator== (const Identifier& other) const noexcept { return name == other.name; }
  6382. /** Compares two identifiers. This is a very fast operation. */
  6383. inline bool operator!= (const Identifier& other) const noexcept { return name != other.name; }
  6384. /** Returns this identifier as a string. */
  6385. const String toString() const { return name; }
  6386. /** Returns this identifier's raw string pointer. */
  6387. operator const String::CharPointerType() const noexcept { return name; }
  6388. private:
  6389. String::CharPointerType name;
  6390. static StringPool& getPool();
  6391. };
  6392. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6393. /*** End of inlined file: juce_Identifier.h ***/
  6394. /*** Start of inlined file: juce_OutputStream.h ***/
  6395. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6396. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6397. /*** Start of inlined file: juce_NewLine.h ***/
  6398. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6399. #define __JUCE_NEWLINE_JUCEHEADER__
  6400. /** This class is used for represent a new-line character sequence.
  6401. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6402. @code
  6403. myOutputStream << "Hello World" << newLine << newLine;
  6404. @endcode
  6405. The exact character sequence that will be used for the new-line can be set and
  6406. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6407. */
  6408. class JUCE_API NewLine
  6409. {
  6410. public:
  6411. /** Returns the default new-line sequence that the library uses.
  6412. @see OutputStream::setNewLineString()
  6413. */
  6414. static const char* getDefault() noexcept { return "\r\n"; }
  6415. /** Returns the default new-line sequence that the library uses.
  6416. @see getDefault()
  6417. */
  6418. operator const String() const { return getDefault(); }
  6419. };
  6420. /** An predefined object representing a new-line, which can be written to a string or stream.
  6421. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6422. @code
  6423. myOutputStream << "Hello World" << newLine << newLine;
  6424. @endcode
  6425. */
  6426. extern NewLine newLine;
  6427. /** Writes a new-line sequence to a string.
  6428. You can use the predefined object 'newLine' to invoke this, e.g.
  6429. @code
  6430. myString << "Hello World" << newLine << newLine;
  6431. @endcode
  6432. */
  6433. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6434. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6435. /*** End of inlined file: juce_NewLine.h ***/
  6436. /*** Start of inlined file: juce_InputStream.h ***/
  6437. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6438. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6439. /*** Start of inlined file: juce_MemoryBlock.h ***/
  6440. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6441. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  6442. /**
  6443. A class to hold a resizable block of raw data.
  6444. */
  6445. class JUCE_API MemoryBlock
  6446. {
  6447. public:
  6448. /** Create an uninitialised block with 0 size. */
  6449. MemoryBlock() noexcept;
  6450. /** Creates a memory block with a given initial size.
  6451. @param initialSize the size of block to create
  6452. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  6453. */
  6454. MemoryBlock (const size_t initialSize,
  6455. bool initialiseToZero = false);
  6456. /** Creates a copy of another memory block. */
  6457. MemoryBlock (const MemoryBlock& other);
  6458. /** Creates a memory block using a copy of a block of data.
  6459. @param dataToInitialiseFrom some data to copy into this block
  6460. @param sizeInBytes how much space to use
  6461. */
  6462. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  6463. /** Destructor. */
  6464. ~MemoryBlock() noexcept;
  6465. /** Copies another memory block onto this one.
  6466. This block will be resized and copied to exactly match the other one.
  6467. */
  6468. MemoryBlock& operator= (const MemoryBlock& other);
  6469. /** Compares two memory blocks.
  6470. @returns true only if the two blocks are the same size and have identical contents.
  6471. */
  6472. bool operator== (const MemoryBlock& other) const noexcept;
  6473. /** Compares two memory blocks.
  6474. @returns true if the two blocks are different sizes or have different contents.
  6475. */
  6476. bool operator!= (const MemoryBlock& other) const noexcept;
  6477. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  6478. */
  6479. bool matches (const void* data, size_t dataSize) const noexcept;
  6480. /** Returns a void pointer to the data.
  6481. Note that the pointer returned will probably become invalid when the
  6482. block is resized.
  6483. */
  6484. void* getData() const noexcept { return data; }
  6485. /** Returns a byte from the memory block.
  6486. This returns a reference, so you can also use it to set a byte.
  6487. */
  6488. template <typename Type>
  6489. char& operator[] (const Type offset) const noexcept { return data [offset]; }
  6490. /** Returns the block's current allocated size, in bytes. */
  6491. size_t getSize() const noexcept { return size; }
  6492. /** Resizes the memory block.
  6493. This will try to keep as much of the block's current content as it can,
  6494. and can optionally be made to clear any new space that gets allocated at
  6495. the end of the block.
  6496. @param newSize the new desired size for the block
  6497. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6498. whether to clear the new section or just leave it
  6499. uninitialised
  6500. @see ensureSize
  6501. */
  6502. void setSize (const size_t newSize,
  6503. bool initialiseNewSpaceToZero = false);
  6504. /** Increases the block's size only if it's smaller than a given size.
  6505. @param minimumSize if the block is already bigger than this size, no action
  6506. will be taken; otherwise it will be increased to this size
  6507. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6508. whether to clear the new section or just leave it
  6509. uninitialised
  6510. @see setSize
  6511. */
  6512. void ensureSize (const size_t minimumSize,
  6513. bool initialiseNewSpaceToZero = false);
  6514. /** Fills the entire memory block with a repeated byte value.
  6515. This is handy for clearing a block of memory to zero.
  6516. */
  6517. void fillWith (uint8 valueToUse) noexcept;
  6518. /** Adds another block of data to the end of this one.
  6519. This block's size will be increased accordingly.
  6520. */
  6521. void append (const void* data, size_t numBytes);
  6522. /** Exchanges the contents of this and another memory block.
  6523. No actual copying is required for this, so it's very fast.
  6524. */
  6525. void swapWith (MemoryBlock& other) noexcept;
  6526. /** Copies data into this MemoryBlock from a memory address.
  6527. @param srcData the memory location of the data to copy into this block
  6528. @param destinationOffset the offset in this block at which the data being copied should begin
  6529. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  6530. it will be clipped so not to do anything nasty)
  6531. */
  6532. void copyFrom (const void* srcData,
  6533. int destinationOffset,
  6534. size_t numBytes) noexcept;
  6535. /** Copies data from this MemoryBlock to a memory address.
  6536. @param destData the memory location to write to
  6537. @param sourceOffset the offset within this block from which the copied data will be read
  6538. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  6539. zeros will be used for that portion of the data)
  6540. */
  6541. void copyTo (void* destData,
  6542. int sourceOffset,
  6543. size_t numBytes) const noexcept;
  6544. /** Chops out a section of the block.
  6545. This will remove a section of the memory block and close the gap around it,
  6546. shifting any subsequent data downwards and reducing the size of the block.
  6547. If the range specified goes beyond the size of the block, it will be clipped.
  6548. */
  6549. void removeSection (size_t startByte, size_t numBytesToRemove);
  6550. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  6551. characters in the system's default encoding. */
  6552. const String toString() const;
  6553. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  6554. The block will be resized to the number of valid bytes read from the string.
  6555. Non-hex characters in the string will be ignored.
  6556. @see String::toHexString()
  6557. */
  6558. void loadFromHexString (const String& sourceHexString);
  6559. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  6560. void setBitRange (size_t bitRangeStart,
  6561. size_t numBits,
  6562. int binaryNumberToApply) noexcept;
  6563. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  6564. int getBitRange (size_t bitRangeStart,
  6565. size_t numBitsToRead) const noexcept;
  6566. /** Returns a string of characters that represent the binary contents of this block.
  6567. Uses a 64-bit encoding system to allow binary data to be turned into a string
  6568. of simple non-extended characters, e.g. for storage in XML.
  6569. @see fromBase64Encoding
  6570. */
  6571. const String toBase64Encoding() const;
  6572. /** Takes a string of encoded characters and turns it into binary data.
  6573. The string passed in must have been created by to64BitEncoding(), and this
  6574. block will be resized to recreate the original data block.
  6575. @see toBase64Encoding
  6576. */
  6577. bool fromBase64Encoding (const String& encodedString);
  6578. private:
  6579. HeapBlock <char> data;
  6580. size_t size;
  6581. static const char* const encodingTable;
  6582. JUCE_LEAK_DETECTOR (MemoryBlock);
  6583. };
  6584. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  6585. /*** End of inlined file: juce_MemoryBlock.h ***/
  6586. /** The base class for streams that read data.
  6587. Input and output streams are used throughout the library - subclasses can override
  6588. some or all of the virtual functions to implement their behaviour.
  6589. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6590. */
  6591. class JUCE_API InputStream
  6592. {
  6593. public:
  6594. /** Destructor. */
  6595. virtual ~InputStream() {}
  6596. /** Returns the total number of bytes available for reading in this stream.
  6597. Note that this is the number of bytes available from the start of the
  6598. stream, not from the current position.
  6599. If the size of the stream isn't actually known, this may return -1.
  6600. */
  6601. virtual int64 getTotalLength() = 0;
  6602. /** Returns true if the stream has no more data to read. */
  6603. virtual bool isExhausted() = 0;
  6604. /** Reads a set of bytes from the stream into a memory buffer.
  6605. This is the only read method that subclasses actually need to implement, as the
  6606. InputStream base class implements the other read methods in terms of this one (although
  6607. it's often more efficient for subclasses to implement them directly).
  6608. @param destBuffer the destination buffer for the data
  6609. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6610. memory block passed in is big enough to contain this
  6611. many bytes.
  6612. @returns the actual number of bytes that were read, which may be less than
  6613. maxBytesToRead if the stream is exhausted before it gets that far
  6614. */
  6615. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6616. /** Reads a byte from the stream.
  6617. If the stream is exhausted, this will return zero.
  6618. @see OutputStream::writeByte
  6619. */
  6620. virtual char readByte();
  6621. /** Reads a boolean from the stream.
  6622. The bool is encoded as a single byte - 1 for true, 0 for false.
  6623. If the stream is exhausted, this will return false.
  6624. @see OutputStream::writeBool
  6625. */
  6626. virtual bool readBool();
  6627. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6628. If the next two bytes read are byte1 and byte2, this returns
  6629. (byte1 | (byte2 << 8)).
  6630. If the stream is exhausted partway through reading the bytes, this will return zero.
  6631. @see OutputStream::writeShort, readShortBigEndian
  6632. */
  6633. virtual short readShort();
  6634. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6635. If the next two bytes read are byte1 and byte2, this returns
  6636. (byte2 | (byte1 << 8)).
  6637. If the stream is exhausted partway through reading the bytes, this will return zero.
  6638. @see OutputStream::writeShortBigEndian, readShort
  6639. */
  6640. virtual short readShortBigEndian();
  6641. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6642. If the next four bytes are byte1 to byte4, this returns
  6643. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6644. If the stream is exhausted partway through reading the bytes, this will return zero.
  6645. @see OutputStream::writeInt, readIntBigEndian
  6646. */
  6647. virtual int readInt();
  6648. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6649. If the next four bytes are byte1 to byte4, this returns
  6650. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6651. If the stream is exhausted partway through reading the bytes, this will return zero.
  6652. @see OutputStream::writeIntBigEndian, readInt
  6653. */
  6654. virtual int readIntBigEndian();
  6655. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6656. If the next eight bytes are byte1 to byte8, this returns
  6657. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6658. If the stream is exhausted partway through reading the bytes, this will return zero.
  6659. @see OutputStream::writeInt64, readInt64BigEndian
  6660. */
  6661. virtual int64 readInt64();
  6662. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6663. If the next eight bytes are byte1 to byte8, this returns
  6664. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6665. If the stream is exhausted partway through reading the bytes, this will return zero.
  6666. @see OutputStream::writeInt64BigEndian, readInt64
  6667. */
  6668. virtual int64 readInt64BigEndian();
  6669. /** Reads four bytes as a 32-bit floating point value.
  6670. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6671. If the stream is exhausted partway through reading the bytes, this will return zero.
  6672. @see OutputStream::writeFloat, readDouble
  6673. */
  6674. virtual float readFloat();
  6675. /** Reads four bytes as a 32-bit floating point value.
  6676. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6677. If the stream is exhausted partway through reading the bytes, this will return zero.
  6678. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6679. */
  6680. virtual float readFloatBigEndian();
  6681. /** Reads eight bytes as a 64-bit floating point value.
  6682. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6683. If the stream is exhausted partway through reading the bytes, this will return zero.
  6684. @see OutputStream::writeDouble, readFloat
  6685. */
  6686. virtual double readDouble();
  6687. /** Reads eight bytes as a 64-bit floating point value.
  6688. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6689. If the stream is exhausted partway through reading the bytes, this will return zero.
  6690. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6691. */
  6692. virtual double readDoubleBigEndian();
  6693. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6694. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6695. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6696. @see OutputStream::writeCompressedInt()
  6697. */
  6698. virtual int readCompressedInt();
  6699. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6700. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6701. After this call, the stream's position will be left pointing to the next character
  6702. following the line-feed, but the linefeeds aren't included in the string that
  6703. is returned.
  6704. */
  6705. virtual const String readNextLine();
  6706. /** Reads a zero-terminated UTF8 string from the stream.
  6707. This will read characters from the stream until it hits a zero character or
  6708. end-of-stream.
  6709. @see OutputStream::writeString, readEntireStreamAsString
  6710. */
  6711. virtual const String readString();
  6712. /** Tries to read the whole stream and turn it into a string.
  6713. This will read from the stream's current position until the end-of-stream, and
  6714. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6715. */
  6716. virtual const String readEntireStreamAsString();
  6717. /** Reads from the stream and appends the data to a MemoryBlock.
  6718. @param destBlock the block to append the data onto
  6719. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6720. of bytes that will be read - if it's negative, data
  6721. will be read until the stream is exhausted.
  6722. @returns the number of bytes that were added to the memory block
  6723. */
  6724. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6725. int maxNumBytesToRead = -1);
  6726. /** Returns the offset of the next byte that will be read from the stream.
  6727. @see setPosition
  6728. */
  6729. virtual int64 getPosition() = 0;
  6730. /** Tries to move the current read position of the stream.
  6731. The position is an absolute number of bytes from the stream's start.
  6732. Some streams might not be able to do this, in which case they should do
  6733. nothing and return false. Others might be able to manage it by resetting
  6734. themselves and skipping to the correct position, although this is
  6735. obviously a bit slow.
  6736. @returns true if the stream manages to reposition itself correctly
  6737. @see getPosition
  6738. */
  6739. virtual bool setPosition (int64 newPosition) = 0;
  6740. /** Reads and discards a number of bytes from the stream.
  6741. Some input streams might implement this efficiently, but the base
  6742. class will just keep reading data until the requisite number of bytes
  6743. have been done.
  6744. */
  6745. virtual void skipNextBytes (int64 numBytesToSkip);
  6746. protected:
  6747. InputStream() noexcept {}
  6748. private:
  6749. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6750. };
  6751. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6752. /*** End of inlined file: juce_InputStream.h ***/
  6753. class File;
  6754. /**
  6755. The base class for streams that write data to some kind of destination.
  6756. Input and output streams are used throughout the library - subclasses can override
  6757. some or all of the virtual functions to implement their behaviour.
  6758. @see InputStream, MemoryOutputStream, FileOutputStream
  6759. */
  6760. class JUCE_API OutputStream
  6761. {
  6762. protected:
  6763. OutputStream();
  6764. public:
  6765. /** Destructor.
  6766. Some subclasses might want to do things like call flush() during their
  6767. destructors.
  6768. */
  6769. virtual ~OutputStream();
  6770. /** If the stream is using a buffer, this will ensure it gets written
  6771. out to the destination. */
  6772. virtual void flush() = 0;
  6773. /** Tries to move the stream's output position.
  6774. Not all streams will be able to seek to a new position - this will return
  6775. false if it fails to work.
  6776. @see getPosition
  6777. */
  6778. virtual bool setPosition (int64 newPosition) = 0;
  6779. /** Returns the stream's current position.
  6780. @see setPosition
  6781. */
  6782. virtual int64 getPosition() = 0;
  6783. /** Writes a block of data to the stream.
  6784. When creating a subclass of OutputStream, this is the only write method
  6785. that needs to be overloaded - the base class has methods for writing other
  6786. types of data which use this to do the work.
  6787. @returns false if the write operation fails for some reason
  6788. */
  6789. virtual bool write (const void* dataToWrite,
  6790. int howManyBytes) = 0;
  6791. /** Writes a single byte to the stream.
  6792. @see InputStream::readByte
  6793. */
  6794. virtual void writeByte (char byte);
  6795. /** Writes a boolean to the stream as a single byte.
  6796. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6797. @see InputStream::readBool
  6798. */
  6799. virtual void writeBool (bool boolValue);
  6800. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6801. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6802. @see InputStream::readShort
  6803. */
  6804. virtual void writeShort (short value);
  6805. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6806. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6807. @see InputStream::readShortBigEndian
  6808. */
  6809. virtual void writeShortBigEndian (short value);
  6810. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6811. @see InputStream::readInt
  6812. */
  6813. virtual void writeInt (int value);
  6814. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6815. @see InputStream::readIntBigEndian
  6816. */
  6817. virtual void writeIntBigEndian (int value);
  6818. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6819. @see InputStream::readInt64
  6820. */
  6821. virtual void writeInt64 (int64 value);
  6822. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6823. @see InputStream::readInt64BigEndian
  6824. */
  6825. virtual void writeInt64BigEndian (int64 value);
  6826. /** Writes a 32-bit floating point value to the stream in a binary format.
  6827. The binary 32-bit encoding of the float is written as a little-endian int.
  6828. @see InputStream::readFloat
  6829. */
  6830. virtual void writeFloat (float value);
  6831. /** Writes a 32-bit floating point value to the stream in a binary format.
  6832. The binary 32-bit encoding of the float is written as a big-endian int.
  6833. @see InputStream::readFloatBigEndian
  6834. */
  6835. virtual void writeFloatBigEndian (float value);
  6836. /** Writes a 64-bit floating point value to the stream in a binary format.
  6837. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6838. @see InputStream::readDouble
  6839. */
  6840. virtual void writeDouble (double value);
  6841. /** Writes a 64-bit floating point value to the stream in a binary format.
  6842. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6843. @see InputStream::readDoubleBigEndian
  6844. */
  6845. virtual void writeDoubleBigEndian (double value);
  6846. /** Writes a byte to the output stream a given number of times. */
  6847. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6848. /** Writes a condensed binary encoding of a 32-bit integer.
  6849. If you're storing a lot of integers which are unlikely to have very large values,
  6850. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6851. under 0xffff only 3 bytes, etc.
  6852. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6853. @see InputStream::readCompressedInt
  6854. */
  6855. virtual void writeCompressedInt (int value);
  6856. /** Stores a string in the stream in a binary format.
  6857. This isn't the method to use if you're trying to append text to the end of a
  6858. text-file! It's intended for storing a string so that it can be retrieved later
  6859. by InputStream::readString().
  6860. It writes the string to the stream as UTF8, including the null termination character.
  6861. For appending text to a file, instead use writeText, or operator<<
  6862. @see InputStream::readString, writeText, operator<<
  6863. */
  6864. virtual void writeString (const String& text);
  6865. /** Writes a string of text to the stream.
  6866. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6867. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6868. of a file).
  6869. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6870. */
  6871. virtual void writeText (const String& text,
  6872. bool asUTF16,
  6873. bool writeUTF16ByteOrderMark);
  6874. /** Reads data from an input stream and writes it to this stream.
  6875. @param source the stream to read from
  6876. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6877. less than zero, it will keep reading until the input
  6878. is exhausted)
  6879. */
  6880. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6881. /** Sets the string that will be written to the stream when the writeNewLine()
  6882. method is called.
  6883. By default this will be set the the value of NewLine::getDefault().
  6884. */
  6885. void setNewLineString (const String& newLineString);
  6886. /** Returns the current new-line string that was set by setNewLineString(). */
  6887. const String& getNewLineString() const noexcept { return newLineString; }
  6888. private:
  6889. String newLineString;
  6890. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6891. };
  6892. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6893. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6894. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6895. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6896. /** Writes a character to a stream. */
  6897. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6898. /** Writes a null-terminated text string to a stream. */
  6899. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6900. /** Writes a block of data from a MemoryBlock to a stream. */
  6901. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6902. /** Writes the contents of a file to a stream. */
  6903. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6904. /** Writes a new-line to a stream.
  6905. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6906. @code
  6907. myOutputStream << "Hello World" << newLine << newLine;
  6908. @endcode
  6909. @see OutputStream::setNewLineString
  6910. */
  6911. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6912. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6913. /*** End of inlined file: juce_OutputStream.h ***/
  6914. #ifndef DOXYGEN
  6915. class DynamicObject;
  6916. #endif
  6917. /**
  6918. A variant class, that can be used to hold a range of primitive values.
  6919. A var object can hold a range of simple primitive values, strings, or
  6920. a reference-counted pointer to a DynamicObject. The var class is intended
  6921. to act like the values used in dynamic scripting languages.
  6922. @see DynamicObject
  6923. */
  6924. class JUCE_API var
  6925. {
  6926. public:
  6927. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6928. typedef Identifier identifier;
  6929. /** Creates a void variant. */
  6930. var() noexcept;
  6931. /** Destructor. */
  6932. ~var() noexcept;
  6933. /** A static var object that can be used where you need an empty variant object. */
  6934. static const var null;
  6935. var (const var& valueToCopy);
  6936. var (int value) noexcept;
  6937. var (int64 value) noexcept;
  6938. var (bool value) noexcept;
  6939. var (double value) noexcept;
  6940. var (const char* value);
  6941. var (const wchar_t* value);
  6942. var (const String& value);
  6943. var (DynamicObject* object);
  6944. var (MethodFunction method) noexcept;
  6945. var& operator= (const var& valueToCopy);
  6946. var& operator= (int value);
  6947. var& operator= (int64 value);
  6948. var& operator= (bool value);
  6949. var& operator= (double value);
  6950. var& operator= (const char* value);
  6951. var& operator= (const wchar_t* value);
  6952. var& operator= (const String& value);
  6953. var& operator= (DynamicObject* object);
  6954. var& operator= (MethodFunction method);
  6955. void swapWith (var& other) noexcept;
  6956. operator int() const;
  6957. operator int64() const;
  6958. operator bool() const;
  6959. operator float() const;
  6960. operator double() const;
  6961. operator const String() const;
  6962. const String toString() const;
  6963. DynamicObject* getObject() const;
  6964. bool isVoid() const noexcept;
  6965. bool isInt() const noexcept;
  6966. bool isInt64() const noexcept;
  6967. bool isBool() const noexcept;
  6968. bool isDouble() const noexcept;
  6969. bool isString() const noexcept;
  6970. bool isObject() const noexcept;
  6971. bool isMethod() const noexcept;
  6972. /** Writes a binary representation of this value to a stream.
  6973. The data can be read back later using readFromStream().
  6974. */
  6975. void writeToStream (OutputStream& output) const;
  6976. /** Reads back a stored binary representation of a value.
  6977. The data in the stream must have been written using writeToStream(), or this
  6978. will have unpredictable results.
  6979. */
  6980. static const var readFromStream (InputStream& input);
  6981. /** If this variant is an object, this returns one of its properties. */
  6982. const var operator[] (const Identifier& propertyName) const;
  6983. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6984. const var call (const Identifier& method) const;
  6985. /** If this variant is an object, this invokes one of its methods with one argument. */
  6986. const var call (const Identifier& method, const var& arg1) const;
  6987. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6988. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6989. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6990. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6991. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6992. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6993. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6994. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6995. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6996. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6997. /** If this variant is a method pointer, this invokes it on a target object. */
  6998. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  6999. /** Returns true if this var has the same value as the one supplied. */
  7000. bool equals (const var& other) const noexcept;
  7001. /** Returns true if this var has the same value and type as the one supplied.
  7002. This differs from equals() because e.g. "0" and 0 will be considered different.
  7003. */
  7004. bool equalsWithSameType (const var& other) const noexcept;
  7005. private:
  7006. class VariantType;
  7007. friend class VariantType;
  7008. class VariantType_Void;
  7009. friend class VariantType_Void;
  7010. class VariantType_Int;
  7011. friend class VariantType_Int;
  7012. class VariantType_Int64;
  7013. friend class VariantType_Int64;
  7014. class VariantType_Double;
  7015. friend class VariantType_Double;
  7016. class VariantType_Float;
  7017. friend class VariantType_Float;
  7018. class VariantType_Bool;
  7019. friend class VariantType_Bool;
  7020. class VariantType_String;
  7021. friend class VariantType_String;
  7022. class VariantType_Object;
  7023. friend class VariantType_Object;
  7024. class VariantType_Method;
  7025. friend class VariantType_Method;
  7026. union ValueUnion
  7027. {
  7028. int intValue;
  7029. int64 int64Value;
  7030. bool boolValue;
  7031. double doubleValue;
  7032. String* stringValue;
  7033. DynamicObject* objectValue;
  7034. MethodFunction methodValue;
  7035. };
  7036. const VariantType* type;
  7037. ValueUnion value;
  7038. };
  7039. bool operator== (const var& v1, const var& v2) noexcept;
  7040. bool operator!= (const var& v1, const var& v2) noexcept;
  7041. bool operator== (const var& v1, const String& v2) noexcept;
  7042. bool operator!= (const var& v1, const String& v2) noexcept;
  7043. #endif // __JUCE_VARIANT_JUCEHEADER__
  7044. /*** End of inlined file: juce_Variant.h ***/
  7045. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  7046. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7047. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7048. /**
  7049. Helps to manipulate singly-linked lists of objects.
  7050. For objects that are designed to contain a pointer to the subsequent item in the
  7051. list, this class contains methods to deal with the list. To use it, the ObjectType
  7052. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  7053. @code
  7054. struct MyObject
  7055. {
  7056. int x, y, z;
  7057. // A linkable object must contain a member with this name and type, which must be
  7058. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  7059. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  7060. LinkedListPointer<MyObject> nextListItem;
  7061. };
  7062. LinkedListPointer<MyObject> myList;
  7063. myList.append (new MyObject());
  7064. myList.append (new MyObject());
  7065. int numItems = myList.size(); // returns 2
  7066. MyObject* lastInList = myList.getLast();
  7067. @endcode
  7068. */
  7069. template <class ObjectType>
  7070. class LinkedListPointer
  7071. {
  7072. public:
  7073. /** Creates a null pointer to an empty list. */
  7074. LinkedListPointer() noexcept
  7075. : item (nullptr)
  7076. {
  7077. }
  7078. /** Creates a pointer to a list whose head is the item provided. */
  7079. explicit LinkedListPointer (ObjectType* const headItem) noexcept
  7080. : item (headItem)
  7081. {
  7082. }
  7083. /** Sets this pointer to point to a new list. */
  7084. LinkedListPointer& operator= (ObjectType* const newItem) noexcept
  7085. {
  7086. item = newItem;
  7087. return *this;
  7088. }
  7089. /** Returns the item which this pointer points to. */
  7090. inline operator ObjectType*() const noexcept
  7091. {
  7092. return item;
  7093. }
  7094. /** Returns the item which this pointer points to. */
  7095. inline ObjectType* get() const noexcept
  7096. {
  7097. return item;
  7098. }
  7099. /** Returns the last item in the list which this pointer points to.
  7100. This will iterate the list and return the last item found. Obviously the speed
  7101. of this operation will be proportional to the size of the list. If the list is
  7102. empty the return value will be this object.
  7103. If you're planning on appending a number of items to your list, it's much more
  7104. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  7105. */
  7106. LinkedListPointer& getLast() noexcept
  7107. {
  7108. LinkedListPointer* l = this;
  7109. while (l->item != nullptr)
  7110. l = &(l->item->nextListItem);
  7111. return *l;
  7112. }
  7113. /** Returns the number of items in the list.
  7114. Obviously with a simple linked list, getting the size involves iterating the list, so
  7115. this can be a lengthy operation - be careful when using this method in your code.
  7116. */
  7117. int size() const noexcept
  7118. {
  7119. int total = 0;
  7120. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7121. ++total;
  7122. return total;
  7123. }
  7124. /** Returns the item at a given index in the list.
  7125. Since the only way to find an item is to iterate the list, this operation can obviously
  7126. be slow, depending on its size, so you should be careful when using this in algorithms.
  7127. */
  7128. LinkedListPointer& operator[] (int index) noexcept
  7129. {
  7130. LinkedListPointer* l = this;
  7131. while (--index >= 0 && l->item != nullptr)
  7132. l = &(l->item->nextListItem);
  7133. return *l;
  7134. }
  7135. /** Returns the item at a given index in the list.
  7136. Since the only way to find an item is to iterate the list, this operation can obviously
  7137. be slow, depending on its size, so you should be careful when using this in algorithms.
  7138. */
  7139. const LinkedListPointer& operator[] (int index) const noexcept
  7140. {
  7141. const LinkedListPointer* l = this;
  7142. while (--index >= 0 && l->item != nullptr)
  7143. l = &(l->item->nextListItem);
  7144. return *l;
  7145. }
  7146. /** Returns true if the list contains the given item. */
  7147. bool contains (const ObjectType* const itemToLookFor) const noexcept
  7148. {
  7149. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7150. if (itemToLookFor == i)
  7151. return true;
  7152. return false;
  7153. }
  7154. /** Inserts an item into the list, placing it before the item that this pointer
  7155. currently points to.
  7156. */
  7157. void insertNext (ObjectType* const newItem)
  7158. {
  7159. jassert (newItem != nullptr);
  7160. jassert (newItem->nextListItem == nullptr);
  7161. newItem->nextListItem = item;
  7162. item = newItem;
  7163. }
  7164. /** Inserts an item at a numeric index in the list.
  7165. Obviously this will involve iterating the list to find the item at the given index,
  7166. so be careful about the impact this may have on execution time.
  7167. */
  7168. void insertAtIndex (int index, ObjectType* newItem)
  7169. {
  7170. jassert (newItem != nullptr);
  7171. LinkedListPointer* l = this;
  7172. while (index != 0 && l->item != nullptr)
  7173. {
  7174. l = &(l->item->nextListItem);
  7175. --index;
  7176. }
  7177. l->insertNext (newItem);
  7178. }
  7179. /** Replaces the object that this pointer points to, appending the rest of the list to
  7180. the new object, and returning the old one.
  7181. */
  7182. ObjectType* replaceNext (ObjectType* const newItem) noexcept
  7183. {
  7184. jassert (newItem != nullptr);
  7185. jassert (newItem->nextListItem == nullptr);
  7186. ObjectType* const oldItem = item;
  7187. item = newItem;
  7188. item->nextListItem = oldItem->nextListItem.item;
  7189. oldItem->nextListItem = (ObjectType*) 0;
  7190. return oldItem;
  7191. }
  7192. /** Adds an item to the end of the list.
  7193. This operation involves iterating the whole list, so can be slow - if you need to
  7194. append a number of items to your list, it's much more efficient to use the Appender
  7195. class than to repeatedly call append().
  7196. */
  7197. void append (ObjectType* const newItem)
  7198. {
  7199. getLast().item = newItem;
  7200. }
  7201. /** Creates copies of all the items in another list and adds them to this one.
  7202. This will use the ObjectType's copy constructor to try to create copies of each
  7203. item in the other list, and appends them to this list.
  7204. */
  7205. void addCopyOfList (const LinkedListPointer& other)
  7206. {
  7207. LinkedListPointer* insertPoint = this;
  7208. for (ObjectType* i = other.item; i != nullptr; i = i->nextListItem)
  7209. {
  7210. insertPoint->insertNext (new ObjectType (*i));
  7211. insertPoint = &(insertPoint->item->nextListItem);
  7212. }
  7213. }
  7214. /** Removes the head item from the list.
  7215. This won't delete the object that is removed, but returns it, so the caller can
  7216. delete it if necessary.
  7217. */
  7218. ObjectType* removeNext() noexcept
  7219. {
  7220. ObjectType* const oldItem = item;
  7221. if (oldItem != nullptr)
  7222. {
  7223. item = oldItem->nextListItem;
  7224. oldItem->nextListItem = (ObjectType*) 0;
  7225. }
  7226. return oldItem;
  7227. }
  7228. /** Removes a specific item from the list.
  7229. Note that this will not delete the item, it simply unlinks it from the list.
  7230. */
  7231. void remove (ObjectType* const itemToRemove)
  7232. {
  7233. LinkedListPointer* const l = findPointerTo (itemToRemove);
  7234. if (l != nullptr)
  7235. l->removeNext();
  7236. }
  7237. /** Iterates the list, calling the delete operator on all of its elements and
  7238. leaving this pointer empty.
  7239. */
  7240. void deleteAll()
  7241. {
  7242. while (item != nullptr)
  7243. {
  7244. ObjectType* const oldItem = item;
  7245. item = oldItem->nextListItem;
  7246. delete oldItem;
  7247. }
  7248. }
  7249. /** Finds a pointer to a given item.
  7250. If the item is found in the list, this returns the pointer that points to it. If
  7251. the item isn't found, this returns null.
  7252. */
  7253. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
  7254. {
  7255. LinkedListPointer* l = this;
  7256. while (l->item != nullptr)
  7257. {
  7258. if (l->item == itemToLookFor)
  7259. return l;
  7260. l = &(l->item->nextListItem);
  7261. }
  7262. return nullptr;
  7263. }
  7264. /** Copies the items in the list to an array.
  7265. The destArray must contain enough elements to hold the entire list - no checks are
  7266. made for this!
  7267. */
  7268. void copyToArray (ObjectType** destArray) const noexcept
  7269. {
  7270. jassert (destArray != nullptr);
  7271. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7272. *destArray++ = i;
  7273. }
  7274. /**
  7275. Allows efficient repeated insertions into a list.
  7276. You can create an Appender object which points to the last element in your
  7277. list, and then repeatedly call Appender::append() to add items to the end
  7278. of the list in O(1) time.
  7279. */
  7280. class Appender
  7281. {
  7282. public:
  7283. /** Creates an appender which will add items to the given list.
  7284. */
  7285. Appender (LinkedListPointer& endOfListPointer) noexcept
  7286. : endOfList (&endOfListPointer)
  7287. {
  7288. // This can only be used to add to the end of a list.
  7289. jassert (endOfListPointer.item == nullptr);
  7290. }
  7291. /** Appends an item to the list. */
  7292. void append (ObjectType* const newItem) noexcept
  7293. {
  7294. *endOfList = newItem;
  7295. endOfList = &(newItem->nextListItem);
  7296. }
  7297. private:
  7298. LinkedListPointer* endOfList;
  7299. JUCE_DECLARE_NON_COPYABLE (Appender);
  7300. };
  7301. private:
  7302. ObjectType* item;
  7303. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7304. };
  7305. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7306. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7307. class XmlElement;
  7308. /** Holds a set of named var objects.
  7309. This can be used as a basic structure to hold a set of var object, which can
  7310. be retrieved by using their identifier.
  7311. */
  7312. class JUCE_API NamedValueSet
  7313. {
  7314. public:
  7315. /** Creates an empty set. */
  7316. NamedValueSet() noexcept;
  7317. /** Creates a copy of another set. */
  7318. NamedValueSet (const NamedValueSet& other);
  7319. /** Replaces this set with a copy of another set. */
  7320. NamedValueSet& operator= (const NamedValueSet& other);
  7321. /** Destructor. */
  7322. ~NamedValueSet();
  7323. bool operator== (const NamedValueSet& other) const;
  7324. bool operator!= (const NamedValueSet& other) const;
  7325. /** Returns the total number of values that the set contains. */
  7326. int size() const noexcept;
  7327. /** Returns the value of a named item.
  7328. If the name isn't found, this will return a void variant.
  7329. @see getProperty
  7330. */
  7331. const var& operator[] (const Identifier& name) const;
  7332. /** Tries to return the named value, but if no such value is found, this will
  7333. instead return the supplied default value.
  7334. */
  7335. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7336. /** Changes or adds a named value.
  7337. @returns true if a value was changed or added; false if the
  7338. value was already set the the value passed-in.
  7339. */
  7340. bool set (const Identifier& name, const var& newValue);
  7341. /** Returns true if the set contains an item with the specified name. */
  7342. bool contains (const Identifier& name) const;
  7343. /** Removes a value from the set.
  7344. @returns true if a value was removed; false if there was no value
  7345. with the name that was given.
  7346. */
  7347. bool remove (const Identifier& name);
  7348. /** Returns the name of the value at a given index.
  7349. The index must be between 0 and size() - 1.
  7350. */
  7351. const Identifier getName (int index) const;
  7352. /** Returns the value of the item at a given index.
  7353. The index must be between 0 and size() - 1.
  7354. */
  7355. const var getValueAt (int index) const;
  7356. /** Removes all values. */
  7357. void clear();
  7358. /** Returns a pointer to the var that holds a named value, or null if there is
  7359. no value with this name.
  7360. Do not use this method unless you really need access to the internal var object
  7361. for some reason - for normal reading and writing always prefer operator[]() and set().
  7362. */
  7363. var* getVarPointer (const Identifier& name) const;
  7364. /** Sets properties to the values of all of an XML element's attributes. */
  7365. void setFromXmlAttributes (const XmlElement& xml);
  7366. /** Sets attributes in an XML element corresponding to each of this object's
  7367. properties.
  7368. */
  7369. void copyToXmlAttributes (XmlElement& xml) const;
  7370. private:
  7371. class NamedValue
  7372. {
  7373. public:
  7374. NamedValue() noexcept;
  7375. NamedValue (const NamedValue&);
  7376. NamedValue (const Identifier& name, const var& value);
  7377. NamedValue& operator= (const NamedValue&);
  7378. bool operator== (const NamedValue& other) const noexcept;
  7379. LinkedListPointer<NamedValue> nextListItem;
  7380. Identifier name;
  7381. var value;
  7382. private:
  7383. JUCE_LEAK_DETECTOR (NamedValue);
  7384. };
  7385. friend class LinkedListPointer<NamedValue>;
  7386. LinkedListPointer<NamedValue> values;
  7387. };
  7388. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7389. /*** End of inlined file: juce_NamedValueSet.h ***/
  7390. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7391. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7392. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7393. /**
  7394. Adds reference-counting to an object.
  7395. To add reference-counting to a class, derive it from this class, and
  7396. use the ReferenceCountedObjectPtr class to point to it.
  7397. e.g. @code
  7398. class MyClass : public ReferenceCountedObject
  7399. {
  7400. void foo();
  7401. // This is a neat way of declaring a typedef for a pointer class,
  7402. // rather than typing out the full templated name each time..
  7403. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7404. };
  7405. MyClass::Ptr p = new MyClass();
  7406. MyClass::Ptr p2 = p;
  7407. p = nullptr;
  7408. p2->foo();
  7409. @endcode
  7410. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7411. careful not to delete the object manually.
  7412. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7413. */
  7414. class JUCE_API ReferenceCountedObject
  7415. {
  7416. public:
  7417. /** Increments the object's reference count.
  7418. This is done automatically by the smart pointer, but is public just
  7419. in case it's needed for nefarious purposes.
  7420. */
  7421. inline void incReferenceCount() noexcept
  7422. {
  7423. ++refCount;
  7424. }
  7425. /** Decreases the object's reference count.
  7426. If the count gets to zero, the object will be deleted.
  7427. */
  7428. inline void decReferenceCount() noexcept
  7429. {
  7430. jassert (getReferenceCount() > 0);
  7431. if (--refCount == 0)
  7432. delete this;
  7433. }
  7434. /** Returns the object's current reference count. */
  7435. inline int getReferenceCount() const noexcept
  7436. {
  7437. return refCount.get();
  7438. }
  7439. protected:
  7440. /** Creates the reference-counted object (with an initial ref count of zero). */
  7441. ReferenceCountedObject()
  7442. {
  7443. }
  7444. /** Destructor. */
  7445. virtual ~ReferenceCountedObject()
  7446. {
  7447. // it's dangerous to delete an object that's still referenced by something else!
  7448. jassert (getReferenceCount() == 0);
  7449. }
  7450. private:
  7451. Atomic <int> refCount;
  7452. };
  7453. /**
  7454. A smart-pointer class which points to a reference-counted object.
  7455. The template parameter specifies the class of the object you want to point to - the easiest
  7456. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7457. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7458. mathods called incReferenceCount() and decReferenceCount().
  7459. When using this class, you'll probably want to create a typedef to abbreviate the full
  7460. templated name - e.g.
  7461. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7462. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7463. */
  7464. template <class ReferenceCountedObjectClass>
  7465. class ReferenceCountedObjectPtr
  7466. {
  7467. public:
  7468. /** Creates a pointer to a null object. */
  7469. inline ReferenceCountedObjectPtr() noexcept
  7470. : referencedObject (nullptr)
  7471. {
  7472. }
  7473. /** Creates a pointer to an object.
  7474. This will increment the object's reference-count if it is non-null.
  7475. */
  7476. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) noexcept
  7477. : referencedObject (refCountedObject)
  7478. {
  7479. if (refCountedObject != nullptr)
  7480. refCountedObject->incReferenceCount();
  7481. }
  7482. /** Copies another pointer.
  7483. This will increment the object's reference-count (if it is non-null).
  7484. */
  7485. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) noexcept
  7486. : referencedObject (other.referencedObject)
  7487. {
  7488. if (referencedObject != nullptr)
  7489. referencedObject->incReferenceCount();
  7490. }
  7491. /** Changes this pointer to point at a different object.
  7492. The reference count of the old object is decremented, and it might be
  7493. deleted if it hits zero. The new object's count is incremented.
  7494. */
  7495. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7496. {
  7497. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7498. if (newObject != referencedObject)
  7499. {
  7500. if (newObject != nullptr)
  7501. newObject->incReferenceCount();
  7502. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7503. referencedObject = newObject;
  7504. if (oldObject != nullptr)
  7505. oldObject->decReferenceCount();
  7506. }
  7507. return *this;
  7508. }
  7509. /** Changes this pointer to point at a different object.
  7510. The reference count of the old object is decremented, and it might be
  7511. deleted if it hits zero. The new object's count is incremented.
  7512. */
  7513. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7514. {
  7515. if (referencedObject != newObject)
  7516. {
  7517. if (newObject != nullptr)
  7518. newObject->incReferenceCount();
  7519. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7520. referencedObject = newObject;
  7521. if (oldObject != nullptr)
  7522. oldObject->decReferenceCount();
  7523. }
  7524. return *this;
  7525. }
  7526. /** Destructor.
  7527. This will decrement the object's reference-count, and may delete it if it
  7528. gets to zero.
  7529. */
  7530. inline ~ReferenceCountedObjectPtr()
  7531. {
  7532. if (referencedObject != nullptr)
  7533. referencedObject->decReferenceCount();
  7534. }
  7535. /** Returns the object that this pointer references.
  7536. The pointer returned may be zero, of course.
  7537. */
  7538. inline operator ReferenceCountedObjectClass*() const noexcept
  7539. {
  7540. return referencedObject;
  7541. }
  7542. // the -> operator is called on the referenced object
  7543. inline ReferenceCountedObjectClass* operator->() const noexcept
  7544. {
  7545. return referencedObject;
  7546. }
  7547. /** Returns the object that this pointer references.
  7548. The pointer returned may be zero, of course.
  7549. */
  7550. inline ReferenceCountedObjectClass* getObject() const noexcept
  7551. {
  7552. return referencedObject;
  7553. }
  7554. private:
  7555. ReferenceCountedObjectClass* referencedObject;
  7556. };
  7557. /** Compares two ReferenceCountedObjectPointers. */
  7558. template <class ReferenceCountedObjectClass>
  7559. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) noexcept
  7560. {
  7561. return object1.getObject() == object2;
  7562. }
  7563. /** Compares two ReferenceCountedObjectPointers. */
  7564. template <class ReferenceCountedObjectClass>
  7565. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7566. {
  7567. return object1.getObject() == object2.getObject();
  7568. }
  7569. /** Compares two ReferenceCountedObjectPointers. */
  7570. template <class ReferenceCountedObjectClass>
  7571. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7572. {
  7573. return object1 == object2.getObject();
  7574. }
  7575. /** Compares two ReferenceCountedObjectPointers. */
  7576. template <class ReferenceCountedObjectClass>
  7577. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) noexcept
  7578. {
  7579. return object1.getObject() != object2;
  7580. }
  7581. /** Compares two ReferenceCountedObjectPointers. */
  7582. template <class ReferenceCountedObjectClass>
  7583. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7584. {
  7585. return object1.getObject() != object2.getObject();
  7586. }
  7587. /** Compares two ReferenceCountedObjectPointers. */
  7588. template <class ReferenceCountedObjectClass>
  7589. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7590. {
  7591. return object1 != object2.getObject();
  7592. }
  7593. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7594. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7595. /**
  7596. Represents a dynamically implemented object.
  7597. This class is primarily intended for wrapping scripting language objects,
  7598. but could be used for other purposes.
  7599. An instance of a DynamicObject can be used to store named properties, and
  7600. by subclassing hasMethod() and invokeMethod(), you can give your object
  7601. methods.
  7602. */
  7603. class JUCE_API DynamicObject : public ReferenceCountedObject
  7604. {
  7605. public:
  7606. DynamicObject();
  7607. /** Destructor. */
  7608. virtual ~DynamicObject();
  7609. /** Returns true if the object has a property with this name.
  7610. Note that if the property is actually a method, this will return false.
  7611. */
  7612. virtual bool hasProperty (const Identifier& propertyName) const;
  7613. /** Returns a named property.
  7614. This returns a void if no such property exists.
  7615. */
  7616. virtual const var getProperty (const Identifier& propertyName) const;
  7617. /** Sets a named property. */
  7618. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7619. /** Removes a named property. */
  7620. virtual void removeProperty (const Identifier& propertyName);
  7621. /** Checks whether this object has the specified method.
  7622. The default implementation of this just checks whether there's a property
  7623. with this name that's actually a method, but this can be overridden for
  7624. building objects with dynamic invocation.
  7625. */
  7626. virtual bool hasMethod (const Identifier& methodName) const;
  7627. /** Invokes a named method on this object.
  7628. The default implementation looks up the named property, and if it's a method
  7629. call, then it invokes it.
  7630. This method is virtual to allow more dynamic invocation to used for objects
  7631. where the methods may not already be set as properies.
  7632. */
  7633. virtual const var invokeMethod (const Identifier& methodName,
  7634. const var* parameters,
  7635. int numParameters);
  7636. /** Sets up a method.
  7637. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7638. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7639. the code easier to read,
  7640. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7641. @code
  7642. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7643. @endcode
  7644. */
  7645. void setMethod (const Identifier& methodName,
  7646. var::MethodFunction methodFunction);
  7647. /** Removes all properties and methods from the object. */
  7648. void clear();
  7649. private:
  7650. NamedValueSet properties;
  7651. JUCE_LEAK_DETECTOR (DynamicObject);
  7652. };
  7653. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7654. /*** End of inlined file: juce_DynamicObject.h ***/
  7655. #endif
  7656. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7657. #endif
  7658. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7659. /*** Start of inlined file: juce_HashMap.h ***/
  7660. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7661. #define __JUCE_HASHMAP_JUCEHEADER__
  7662. /*** Start of inlined file: juce_OwnedArray.h ***/
  7663. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7664. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7665. /** An array designed for holding objects.
  7666. This holds a list of pointers to objects, and will automatically
  7667. delete the objects when they are removed from the array, or when the
  7668. array is itself deleted.
  7669. Declare it in the form: OwnedArray<MyObjectClass>
  7670. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7671. After adding objects, they are 'owned' by the array and will be deleted when
  7672. removed or replaced.
  7673. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7674. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7675. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7676. */
  7677. template <class ObjectClass,
  7678. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7679. class OwnedArray
  7680. {
  7681. public:
  7682. /** Creates an empty array. */
  7683. OwnedArray() noexcept
  7684. : numUsed (0)
  7685. {
  7686. }
  7687. /** Deletes the array and also deletes any objects inside it.
  7688. To get rid of the array without deleting its objects, use its
  7689. clear (false) method before deleting it.
  7690. */
  7691. ~OwnedArray()
  7692. {
  7693. clear (true);
  7694. }
  7695. /** Clears the array, optionally deleting the objects inside it first. */
  7696. void clear (const bool deleteObjects = true)
  7697. {
  7698. const ScopedLockType lock (getLock());
  7699. if (deleteObjects)
  7700. {
  7701. while (numUsed > 0)
  7702. delete data.elements [--numUsed];
  7703. }
  7704. data.setAllocatedSize (0);
  7705. numUsed = 0;
  7706. }
  7707. /** Returns the number of items currently in the array.
  7708. @see operator[]
  7709. */
  7710. inline int size() const noexcept
  7711. {
  7712. return numUsed;
  7713. }
  7714. /** Returns a pointer to the object at this index in the array.
  7715. If the index is out-of-range, this will return a null pointer, (and
  7716. it could be null anyway, because it's ok for the array to hold null
  7717. pointers as well as objects).
  7718. @see getUnchecked
  7719. */
  7720. inline ObjectClass* operator[] (const int index) const noexcept
  7721. {
  7722. const ScopedLockType lock (getLock());
  7723. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7724. : static_cast <ObjectClass*> (nullptr);
  7725. }
  7726. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7727. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7728. it can be used when you're sure the index if always going to be legal.
  7729. */
  7730. inline ObjectClass* getUnchecked (const int index) const noexcept
  7731. {
  7732. const ScopedLockType lock (getLock());
  7733. jassert (isPositiveAndBelow (index, numUsed));
  7734. return data.elements [index];
  7735. }
  7736. /** Returns a pointer to the first object in the array.
  7737. This will return a null pointer if the array's empty.
  7738. @see getLast
  7739. */
  7740. inline ObjectClass* getFirst() const noexcept
  7741. {
  7742. const ScopedLockType lock (getLock());
  7743. return numUsed > 0 ? data.elements [0]
  7744. : static_cast <ObjectClass*> (nullptr);
  7745. }
  7746. /** Returns a pointer to the last object in the array.
  7747. This will return a null pointer if the array's empty.
  7748. @see getFirst
  7749. */
  7750. inline ObjectClass* getLast() const noexcept
  7751. {
  7752. const ScopedLockType lock (getLock());
  7753. return numUsed > 0 ? data.elements [numUsed - 1]
  7754. : static_cast <ObjectClass*> (nullptr);
  7755. }
  7756. /** Returns a pointer to the actual array data.
  7757. This pointer will only be valid until the next time a non-const method
  7758. is called on the array.
  7759. */
  7760. inline ObjectClass** getRawDataPointer() noexcept
  7761. {
  7762. return data.elements;
  7763. }
  7764. /** Returns a pointer to the first element in the array.
  7765. This method is provided for compatibility with standard C++ iteration mechanisms.
  7766. */
  7767. inline ObjectClass** begin() const noexcept
  7768. {
  7769. return data.elements;
  7770. }
  7771. /** Returns a pointer to the element which follows the last element in the array.
  7772. This method is provided for compatibility with standard C++ iteration mechanisms.
  7773. */
  7774. inline ObjectClass** end() const noexcept
  7775. {
  7776. return data.elements + numUsed;
  7777. }
  7778. /** Finds the index of an object which might be in the array.
  7779. @param objectToLookFor the object to look for
  7780. @returns the index at which the object was found, or -1 if it's not found
  7781. */
  7782. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  7783. {
  7784. const ScopedLockType lock (getLock());
  7785. ObjectClass* const* e = data.elements.getData();
  7786. ObjectClass* const* const end = e + numUsed;
  7787. for (; e != end; ++e)
  7788. if (objectToLookFor == *e)
  7789. return static_cast <int> (e - data.elements.getData());
  7790. return -1;
  7791. }
  7792. /** Returns true if the array contains a specified object.
  7793. @param objectToLookFor the object to look for
  7794. @returns true if the object is in the array
  7795. */
  7796. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  7797. {
  7798. const ScopedLockType lock (getLock());
  7799. ObjectClass* const* e = data.elements.getData();
  7800. ObjectClass* const* const end = e + numUsed;
  7801. for (; e != end; ++e)
  7802. if (objectToLookFor == *e)
  7803. return true;
  7804. return false;
  7805. }
  7806. /** Appends a new object to the end of the array.
  7807. Note that the this object will be deleted by the OwnedArray when it
  7808. is removed, so be careful not to delete it somewhere else.
  7809. Also be careful not to add the same object to the array more than once,
  7810. as this will obviously cause deletion of dangling pointers.
  7811. @param newObject the new object to add to the array
  7812. @see set, insert, addIfNotAlreadyThere, addSorted
  7813. */
  7814. void add (const ObjectClass* const newObject) noexcept
  7815. {
  7816. const ScopedLockType lock (getLock());
  7817. data.ensureAllocatedSize (numUsed + 1);
  7818. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7819. }
  7820. /** Inserts a new object into the array at the given index.
  7821. Note that the this object will be deleted by the OwnedArray when it
  7822. is removed, so be careful not to delete it somewhere else.
  7823. If the index is less than 0 or greater than the size of the array, the
  7824. element will be added to the end of the array.
  7825. Otherwise, it will be inserted into the array, moving all the later elements
  7826. along to make room.
  7827. Be careful not to add the same object to the array more than once,
  7828. as this will obviously cause deletion of dangling pointers.
  7829. @param indexToInsertAt the index at which the new element should be inserted
  7830. @param newObject the new object to add to the array
  7831. @see add, addSorted, addIfNotAlreadyThere, set
  7832. */
  7833. void insert (int indexToInsertAt,
  7834. const ObjectClass* const newObject) noexcept
  7835. {
  7836. if (indexToInsertAt >= 0)
  7837. {
  7838. const ScopedLockType lock (getLock());
  7839. if (indexToInsertAt > numUsed)
  7840. indexToInsertAt = numUsed;
  7841. data.ensureAllocatedSize (numUsed + 1);
  7842. ObjectClass** const e = data.elements + indexToInsertAt;
  7843. const int numToMove = numUsed - indexToInsertAt;
  7844. if (numToMove > 0)
  7845. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7846. *e = const_cast <ObjectClass*> (newObject);
  7847. ++numUsed;
  7848. }
  7849. else
  7850. {
  7851. add (newObject);
  7852. }
  7853. }
  7854. /** Appends a new object at the end of the array as long as the array doesn't
  7855. already contain it.
  7856. If the array already contains a matching object, nothing will be done.
  7857. @param newObject the new object to add to the array
  7858. */
  7859. void addIfNotAlreadyThere (const ObjectClass* const newObject) noexcept
  7860. {
  7861. const ScopedLockType lock (getLock());
  7862. if (! contains (newObject))
  7863. add (newObject);
  7864. }
  7865. /** Replaces an object in the array with a different one.
  7866. If the index is less than zero, this method does nothing.
  7867. If the index is beyond the end of the array, the new object is added to the end of the array.
  7868. Be careful not to add the same object to the array more than once,
  7869. as this will obviously cause deletion of dangling pointers.
  7870. @param indexToChange the index whose value you want to change
  7871. @param newObject the new value to set for this index.
  7872. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7873. @see add, insert, remove
  7874. */
  7875. void set (const int indexToChange,
  7876. const ObjectClass* const newObject,
  7877. const bool deleteOldElement = true)
  7878. {
  7879. if (indexToChange >= 0)
  7880. {
  7881. ObjectClass* toDelete = nullptr;
  7882. {
  7883. const ScopedLockType lock (getLock());
  7884. if (indexToChange < numUsed)
  7885. {
  7886. if (deleteOldElement)
  7887. {
  7888. toDelete = data.elements [indexToChange];
  7889. if (toDelete == newObject)
  7890. toDelete = nullptr;
  7891. }
  7892. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7893. }
  7894. else
  7895. {
  7896. data.ensureAllocatedSize (numUsed + 1);
  7897. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7898. }
  7899. }
  7900. delete toDelete; // don't want to use a ScopedPointer here because if the
  7901. // object has a private destructor, both OwnedArray and
  7902. // ScopedPointer would need to be friend classes..
  7903. }
  7904. else
  7905. {
  7906. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7907. // any effect - but since the object is not being added, it may be leaking..
  7908. }
  7909. }
  7910. /** Adds elements from another array to the end of this array.
  7911. @param arrayToAddFrom the array from which to copy the elements
  7912. @param startIndex the first element of the other array to start copying from
  7913. @param numElementsToAdd how many elements to add from the other array. If this
  7914. value is negative or greater than the number of available elements,
  7915. all available elements will be copied.
  7916. @see add
  7917. */
  7918. template <class OtherArrayType>
  7919. void addArray (const OtherArrayType& arrayToAddFrom,
  7920. int startIndex = 0,
  7921. int numElementsToAdd = -1)
  7922. {
  7923. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7924. const ScopedLockType lock2 (getLock());
  7925. if (startIndex < 0)
  7926. {
  7927. jassertfalse;
  7928. startIndex = 0;
  7929. }
  7930. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7931. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7932. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7933. while (--numElementsToAdd >= 0)
  7934. {
  7935. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7936. ++numUsed;
  7937. }
  7938. }
  7939. /** Adds copies of the elements in another array to the end of this array.
  7940. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7941. containing pointers to the same kind of object. The objects involved must provide
  7942. a copy constructor, and this will be used to create new copies of each element, and
  7943. add them to this array.
  7944. @param arrayToAddFrom the array from which to copy the elements
  7945. @param startIndex the first element of the other array to start copying from
  7946. @param numElementsToAdd how many elements to add from the other array. If this
  7947. value is negative or greater than the number of available elements,
  7948. all available elements will be copied.
  7949. @see add
  7950. */
  7951. template <class OtherArrayType>
  7952. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7953. int startIndex = 0,
  7954. int numElementsToAdd = -1)
  7955. {
  7956. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7957. const ScopedLockType lock2 (getLock());
  7958. if (startIndex < 0)
  7959. {
  7960. jassertfalse;
  7961. startIndex = 0;
  7962. }
  7963. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7964. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7965. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7966. while (--numElementsToAdd >= 0)
  7967. {
  7968. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7969. ++numUsed;
  7970. }
  7971. }
  7972. /** Inserts a new object into the array assuming that the array is sorted.
  7973. This will use a comparator to find the position at which the new object
  7974. should go. If the array isn't sorted, the behaviour of this
  7975. method will be unpredictable.
  7976. @param comparator the comparator to use to compare the elements - see the sort method
  7977. for details about this object's structure
  7978. @param newObject the new object to insert to the array
  7979. @returns the index at which the new object was added
  7980. @see add, sort, indexOfSorted
  7981. */
  7982. template <class ElementComparator>
  7983. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept
  7984. {
  7985. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7986. // avoids getting warning messages about the parameter being unused
  7987. const ScopedLockType lock (getLock());
  7988. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  7989. insert (index, newObject);
  7990. return index;
  7991. }
  7992. /** Finds the index of an object in the array, assuming that the array is sorted.
  7993. This will use a comparator to do a binary-chop to find the index of the given
  7994. element, if it exists. If the array isn't sorted, the behaviour of this
  7995. method will be unpredictable.
  7996. @param comparator the comparator to use to compare the elements - see the sort()
  7997. method for details about the form this object should take
  7998. @param objectToLookFor the object to search for
  7999. @returns the index of the element, or -1 if it's not found
  8000. @see addSorted, sort
  8001. */
  8002. template <class ElementComparator>
  8003. int indexOfSorted (ElementComparator& comparator,
  8004. const ObjectClass* const objectToLookFor) const noexcept
  8005. {
  8006. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8007. // avoids getting warning messages about the parameter being unused
  8008. const ScopedLockType lock (getLock());
  8009. int start = 0;
  8010. int end = numUsed;
  8011. for (;;)
  8012. {
  8013. if (start >= end)
  8014. {
  8015. return -1;
  8016. }
  8017. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  8018. {
  8019. return start;
  8020. }
  8021. else
  8022. {
  8023. const int halfway = (start + end) >> 1;
  8024. if (halfway == start)
  8025. return -1;
  8026. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  8027. start = halfway;
  8028. else
  8029. end = halfway;
  8030. }
  8031. }
  8032. }
  8033. /** Removes an object from the array.
  8034. This will remove the object at a given index (optionally also
  8035. deleting it) and move back all the subsequent objects to close the gap.
  8036. If the index passed in is out-of-range, nothing will happen.
  8037. @param indexToRemove the index of the element to remove
  8038. @param deleteObject whether to delete the object that is removed
  8039. @see removeObject, removeRange
  8040. */
  8041. void remove (const int indexToRemove,
  8042. const bool deleteObject = true)
  8043. {
  8044. ObjectClass* toDelete = nullptr;
  8045. {
  8046. const ScopedLockType lock (getLock());
  8047. if (isPositiveAndBelow (indexToRemove, numUsed))
  8048. {
  8049. ObjectClass** const e = data.elements + indexToRemove;
  8050. if (deleteObject)
  8051. toDelete = *e;
  8052. --numUsed;
  8053. const int numToShift = numUsed - indexToRemove;
  8054. if (numToShift > 0)
  8055. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8056. }
  8057. }
  8058. delete toDelete; // don't want to use a ScopedPointer here because if the
  8059. // object has a private destructor, both OwnedArray and
  8060. // ScopedPointer would need to be friend classes..
  8061. if ((numUsed << 1) < data.numAllocated)
  8062. minimiseStorageOverheads();
  8063. }
  8064. /** Removes and returns an object from the array without deleting it.
  8065. This will remove the object at a given index and return it, moving back all
  8066. the subsequent objects to close the gap. If the index passed in is out-of-range,
  8067. nothing will happen.
  8068. @param indexToRemove the index of the element to remove
  8069. @see remove, removeObject, removeRange
  8070. */
  8071. ObjectClass* removeAndReturn (const int indexToRemove)
  8072. {
  8073. ObjectClass* removedItem = nullptr;
  8074. const ScopedLockType lock (getLock());
  8075. if (isPositiveAndBelow (indexToRemove, numUsed))
  8076. {
  8077. ObjectClass** const e = data.elements + indexToRemove;
  8078. removedItem = *e;
  8079. --numUsed;
  8080. const int numToShift = numUsed - indexToRemove;
  8081. if (numToShift > 0)
  8082. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8083. if ((numUsed << 1) < data.numAllocated)
  8084. minimiseStorageOverheads();
  8085. }
  8086. return removedItem;
  8087. }
  8088. /** Removes a specified object from the array.
  8089. If the item isn't found, no action is taken.
  8090. @param objectToRemove the object to try to remove
  8091. @param deleteObject whether to delete the object (if it's found)
  8092. @see remove, removeRange
  8093. */
  8094. void removeObject (const ObjectClass* const objectToRemove,
  8095. const bool deleteObject = true)
  8096. {
  8097. const ScopedLockType lock (getLock());
  8098. ObjectClass** const e = data.elements.getData();
  8099. for (int i = 0; i < numUsed; ++i)
  8100. {
  8101. if (objectToRemove == e[i])
  8102. {
  8103. remove (i, deleteObject);
  8104. break;
  8105. }
  8106. }
  8107. }
  8108. /** Removes a range of objects from the array.
  8109. This will remove a set of objects, starting from the given index,
  8110. and move any subsequent elements down to close the gap.
  8111. If the range extends beyond the bounds of the array, it will
  8112. be safely clipped to the size of the array.
  8113. @param startIndex the index of the first object to remove
  8114. @param numberToRemove how many objects should be removed
  8115. @param deleteObjects whether to delete the objects that get removed
  8116. @see remove, removeObject
  8117. */
  8118. void removeRange (int startIndex,
  8119. const int numberToRemove,
  8120. const bool deleteObjects = true)
  8121. {
  8122. const ScopedLockType lock (getLock());
  8123. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  8124. startIndex = jlimit (0, numUsed, startIndex);
  8125. if (endIndex > startIndex)
  8126. {
  8127. if (deleteObjects)
  8128. {
  8129. for (int i = startIndex; i < endIndex; ++i)
  8130. {
  8131. delete data.elements [i];
  8132. data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8133. }
  8134. }
  8135. const int rangeSize = endIndex - startIndex;
  8136. ObjectClass** e = data.elements + startIndex;
  8137. int numToShift = numUsed - endIndex;
  8138. numUsed -= rangeSize;
  8139. while (--numToShift >= 0)
  8140. {
  8141. *e = e [rangeSize];
  8142. ++e;
  8143. }
  8144. if ((numUsed << 1) < data.numAllocated)
  8145. minimiseStorageOverheads();
  8146. }
  8147. }
  8148. /** Removes the last n objects from the array.
  8149. @param howManyToRemove how many objects to remove from the end of the array
  8150. @param deleteObjects whether to also delete the objects that are removed
  8151. @see remove, removeObject, removeRange
  8152. */
  8153. void removeLast (int howManyToRemove = 1,
  8154. const bool deleteObjects = true)
  8155. {
  8156. const ScopedLockType lock (getLock());
  8157. if (howManyToRemove >= numUsed)
  8158. clear (deleteObjects);
  8159. else
  8160. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  8161. }
  8162. /** Swaps a pair of objects in the array.
  8163. If either of the indexes passed in is out-of-range, nothing will happen,
  8164. otherwise the two objects at these positions will be exchanged.
  8165. */
  8166. void swap (const int index1,
  8167. const int index2) noexcept
  8168. {
  8169. const ScopedLockType lock (getLock());
  8170. if (isPositiveAndBelow (index1, numUsed)
  8171. && isPositiveAndBelow (index2, numUsed))
  8172. {
  8173. swapVariables (data.elements [index1],
  8174. data.elements [index2]);
  8175. }
  8176. }
  8177. /** Moves one of the objects to a different position.
  8178. This will move the object to a specified index, shuffling along
  8179. any intervening elements as required.
  8180. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8181. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8182. @param currentIndex the index of the object to be moved. If this isn't a
  8183. valid index, then nothing will be done
  8184. @param newIndex the index at which you'd like this object to end up. If this
  8185. is less than zero, it will be moved to the end of the array
  8186. */
  8187. void move (const int currentIndex,
  8188. int newIndex) noexcept
  8189. {
  8190. if (currentIndex != newIndex)
  8191. {
  8192. const ScopedLockType lock (getLock());
  8193. if (isPositiveAndBelow (currentIndex, numUsed))
  8194. {
  8195. if (! isPositiveAndBelow (newIndex, numUsed))
  8196. newIndex = numUsed - 1;
  8197. ObjectClass* const value = data.elements [currentIndex];
  8198. if (newIndex > currentIndex)
  8199. {
  8200. memmove (data.elements + currentIndex,
  8201. data.elements + currentIndex + 1,
  8202. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8203. }
  8204. else
  8205. {
  8206. memmove (data.elements + newIndex + 1,
  8207. data.elements + newIndex,
  8208. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8209. }
  8210. data.elements [newIndex] = value;
  8211. }
  8212. }
  8213. }
  8214. /** This swaps the contents of this array with those of another array.
  8215. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8216. because it just swaps their internal pointers.
  8217. */
  8218. void swapWithArray (OwnedArray& otherArray) noexcept
  8219. {
  8220. const ScopedLockType lock1 (getLock());
  8221. const ScopedLockType lock2 (otherArray.getLock());
  8222. data.swapWith (otherArray.data);
  8223. swapVariables (numUsed, otherArray.numUsed);
  8224. }
  8225. /** Reduces the amount of storage being used by the array.
  8226. Arrays typically allocate slightly more storage than they need, and after
  8227. removing elements, they may have quite a lot of unused space allocated.
  8228. This method will reduce the amount of allocated storage to a minimum.
  8229. */
  8230. void minimiseStorageOverheads() noexcept
  8231. {
  8232. const ScopedLockType lock (getLock());
  8233. data.shrinkToNoMoreThan (numUsed);
  8234. }
  8235. /** Increases the array's internal storage to hold a minimum number of elements.
  8236. Calling this before adding a large known number of elements means that
  8237. the array won't have to keep dynamically resizing itself as the elements
  8238. are added, and it'll therefore be more efficient.
  8239. */
  8240. void ensureStorageAllocated (const int minNumElements) noexcept
  8241. {
  8242. const ScopedLockType lock (getLock());
  8243. data.ensureAllocatedSize (minNumElements);
  8244. }
  8245. /** Sorts the elements in the array.
  8246. This will use a comparator object to sort the elements into order. The object
  8247. passed must have a method of the form:
  8248. @code
  8249. int compareElements (ElementType first, ElementType second);
  8250. @endcode
  8251. ..and this method must return:
  8252. - a value of < 0 if the first comes before the second
  8253. - a value of 0 if the two objects are equivalent
  8254. - a value of > 0 if the second comes before the first
  8255. To improve performance, the compareElements() method can be declared as static or const.
  8256. @param comparator the comparator to use for comparing elements.
  8257. @param retainOrderOfEquivalentItems if this is true, then items
  8258. which the comparator says are equivalent will be
  8259. kept in the order in which they currently appear
  8260. in the array. This is slower to perform, but may
  8261. be important in some cases. If it's false, a faster
  8262. algorithm is used, but equivalent elements may be
  8263. rearranged.
  8264. @see sortArray, indexOfSorted
  8265. */
  8266. template <class ElementComparator>
  8267. void sort (ElementComparator& comparator,
  8268. const bool retainOrderOfEquivalentItems = false) const noexcept
  8269. {
  8270. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8271. // avoids getting warning messages about the parameter being unused
  8272. const ScopedLockType lock (getLock());
  8273. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8274. }
  8275. /** Returns the CriticalSection that locks this array.
  8276. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8277. an object of ScopedLockType as an RAII lock for it.
  8278. */
  8279. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  8280. /** Returns the type of scoped lock to use for locking this array */
  8281. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8282. private:
  8283. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8284. int numUsed;
  8285. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8286. };
  8287. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8288. /*** End of inlined file: juce_OwnedArray.h ***/
  8289. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8290. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8291. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8292. /**
  8293. This class holds a pointer which is automatically deleted when this object goes
  8294. out of scope.
  8295. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8296. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8297. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8298. created objects.
  8299. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8300. to an object. If you use the assignment operator to assign a different object to a
  8301. ScopedPointer, the old one will be automatically deleted.
  8302. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8303. object to which it points during its lifetime. This means that making a copy of a const
  8304. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8305. old one.
  8306. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8307. can use the release() method.
  8308. */
  8309. template <class ObjectType>
  8310. class ScopedPointer
  8311. {
  8312. public:
  8313. /** Creates a ScopedPointer containing a null pointer. */
  8314. inline ScopedPointer() noexcept : object (nullptr)
  8315. {
  8316. }
  8317. /** Creates a ScopedPointer that owns the specified object. */
  8318. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) noexcept
  8319. : object (objectToTakePossessionOf)
  8320. {
  8321. }
  8322. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8323. Because a pointer can only belong to one ScopedPointer, this transfers
  8324. the pointer from the other object to this one, and the other object is reset to
  8325. be a null pointer.
  8326. */
  8327. ScopedPointer (ScopedPointer& objectToTransferFrom) noexcept
  8328. : object (objectToTransferFrom.object)
  8329. {
  8330. objectToTransferFrom.object = nullptr;
  8331. }
  8332. /** Destructor.
  8333. This will delete the object that this ScopedPointer currently refers to.
  8334. */
  8335. inline ~ScopedPointer() { delete object; }
  8336. /** Changes this ScopedPointer to point to a new object.
  8337. Because a pointer can only belong to one ScopedPointer, this transfers
  8338. the pointer from the other object to this one, and the other object is reset to
  8339. be a null pointer.
  8340. If this ScopedPointer already points to an object, that object
  8341. will first be deleted.
  8342. */
  8343. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8344. {
  8345. if (this != objectToTransferFrom.getAddress())
  8346. {
  8347. // Two ScopedPointers should never be able to refer to the same object - if
  8348. // this happens, you must have done something dodgy!
  8349. jassert (object == nullptr || object != objectToTransferFrom.object);
  8350. ObjectType* const oldObject = object;
  8351. object = objectToTransferFrom.object;
  8352. objectToTransferFrom.object = nullptr;
  8353. delete oldObject;
  8354. }
  8355. return *this;
  8356. }
  8357. /** Changes this ScopedPointer to point to a new object.
  8358. If this ScopedPointer already points to an object, that object
  8359. will first be deleted.
  8360. The pointer that you pass is may be null.
  8361. */
  8362. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8363. {
  8364. if (object != newObjectToTakePossessionOf)
  8365. {
  8366. ObjectType* const oldObject = object;
  8367. object = newObjectToTakePossessionOf;
  8368. delete oldObject;
  8369. }
  8370. return *this;
  8371. }
  8372. /** Returns the object that this ScopedPointer refers to. */
  8373. inline operator ObjectType*() const noexcept { return object; }
  8374. /** Returns the object that this ScopedPointer refers to. */
  8375. inline ObjectType& operator*() const noexcept { return *object; }
  8376. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8377. inline ObjectType* operator->() const noexcept { return object; }
  8378. /** Removes the current object from this ScopedPointer without deleting it.
  8379. This will return the current object, and set the ScopedPointer to a null pointer.
  8380. */
  8381. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  8382. /** Swaps this object with that of another ScopedPointer.
  8383. The two objects simply exchange their pointers.
  8384. */
  8385. void swapWith (ScopedPointer <ObjectType>& other) noexcept
  8386. {
  8387. // Two ScopedPointers should never be able to refer to the same object - if
  8388. // this happens, you must have done something dodgy!
  8389. jassert (object != other.object);
  8390. std::swap (object, other.object);
  8391. }
  8392. private:
  8393. ObjectType* object;
  8394. // (Required as an alternative to the overloaded & operator).
  8395. const ScopedPointer* getAddress() const noexcept { return this; }
  8396. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8397. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8398. would let you do so by implicitly casting the source to its raw object pointer).
  8399. A side effect of this is that you may hit a puzzling compiler error when you write something
  8400. like this:
  8401. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8402. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8403. copy constructor is private. It's very easy to fis though - just write it like this:
  8404. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8405. It's good practice to always use the latter form when writing your object declarations anyway,
  8406. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8407. smart enough to replace your construction + assignment with a single constructor.
  8408. */
  8409. ScopedPointer (const ScopedPointer&);
  8410. #endif
  8411. };
  8412. /** Compares a ScopedPointer with another pointer.
  8413. This can be handy for checking whether this is a null pointer.
  8414. */
  8415. template <class ObjectType>
  8416. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8417. {
  8418. return static_cast <ObjectType*> (pointer1) == pointer2;
  8419. }
  8420. /** Compares a ScopedPointer with another pointer.
  8421. This can be handy for checking whether this is a null pointer.
  8422. */
  8423. template <class ObjectType>
  8424. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8425. {
  8426. return static_cast <ObjectType*> (pointer1) != pointer2;
  8427. }
  8428. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8429. /*** End of inlined file: juce_ScopedPointer.h ***/
  8430. /**
  8431. A simple class to generate hash functions for some primitive types, intended for
  8432. use with the HashMap class.
  8433. @see HashMap
  8434. */
  8435. class DefaultHashFunctions
  8436. {
  8437. public:
  8438. /** Generates a simple hash from an integer. */
  8439. static int generateHash (const int key, const int upperLimit) noexcept { return std::abs (key) % upperLimit; }
  8440. /** Generates a simple hash from a string. */
  8441. static int generateHash (const String& key, const int upperLimit) noexcept { return key.hashCode() % upperLimit; }
  8442. /** Generates a simple hash from a variant. */
  8443. static int generateHash (const var& key, const int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
  8444. };
  8445. /**
  8446. Holds a set of mappings between some key/value pairs.
  8447. The types of the key and value objects are set as template parameters.
  8448. You can also specify a class to supply a hash function that converts a key value
  8449. into an hashed integer. This class must have the form:
  8450. @code
  8451. struct MyHashGenerator
  8452. {
  8453. static int generateHash (MyKeyType key, int upperLimit)
  8454. {
  8455. // The function must return a value 0 <= x < upperLimit
  8456. return someFunctionOfMyKeyType (key) % upperLimit;
  8457. }
  8458. };
  8459. @endcode
  8460. Like the Array class, the key and value types are expected to be copy-by-value types, so
  8461. if you define them to be pointer types, this class won't delete the objects that they
  8462. point to.
  8463. If you don't supply a class for the HashFunctionToUse template parameter, the
  8464. default one provides some simple mappings for strings and ints.
  8465. @code
  8466. HashMap<int, String> hash;
  8467. hash.set (1, "item1");
  8468. hash.set (2, "item2");
  8469. DBG (hash [1]); // prints "item1"
  8470. DBG (hash [2]); // prints "item2"
  8471. // This iterates the map, printing all of its key -> value pairs..
  8472. for (HashMap<int, String>::Iterator i (hash); i.next();)
  8473. DBG (i.getKey() << " -> " << i.getValue());
  8474. @endcode
  8475. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  8476. */
  8477. template <typename KeyType,
  8478. typename ValueType,
  8479. class HashFunctionToUse = DefaultHashFunctions,
  8480. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8481. class HashMap
  8482. {
  8483. private:
  8484. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  8485. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  8486. public:
  8487. /** Creates an empty hash-map.
  8488. The numberOfSlots parameter specifies the number of hash entries the map will use. This
  8489. will be the "upperLimit" parameter that is passed to your generateHash() function. The number
  8490. of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable().
  8491. */
  8492. HashMap (const int numberOfSlots = defaultHashTableSize)
  8493. : totalNumItems (0)
  8494. {
  8495. slots.insertMultiple (0, nullptr, numberOfSlots);
  8496. }
  8497. /** Destructor. */
  8498. ~HashMap()
  8499. {
  8500. clear();
  8501. }
  8502. /** Removes all values from the map.
  8503. Note that this will clear the content, but won't affect the number of slots (see
  8504. remapTable and getNumSlots).
  8505. */
  8506. void clear()
  8507. {
  8508. const ScopedLockType sl (getLock());
  8509. for (int i = slots.size(); --i >= 0;)
  8510. {
  8511. HashEntry* h = slots.getUnchecked(i);
  8512. while (h != nullptr)
  8513. {
  8514. const ScopedPointer<HashEntry> deleter (h);
  8515. h = h->nextEntry;
  8516. }
  8517. slots.set (i, nullptr);
  8518. }
  8519. totalNumItems = 0;
  8520. }
  8521. /** Returns the current number of items in the map. */
  8522. inline int size() const noexcept
  8523. {
  8524. return totalNumItems;
  8525. }
  8526. /** Returns the value corresponding to a given key.
  8527. If the map doesn't contain the key, a default instance of the value type is returned.
  8528. @param keyToLookFor the key of the item being requested
  8529. */
  8530. inline const ValueType operator[] (KeyTypeParameter keyToLookFor) const
  8531. {
  8532. const ScopedLockType sl (getLock());
  8533. for (const HashEntry* entry = slots [generateHashFor (keyToLookFor)]; entry != nullptr; entry = entry->nextEntry)
  8534. if (entry->key == keyToLookFor)
  8535. return entry->value;
  8536. return ValueType();
  8537. }
  8538. /** Returns true if the map contains an item with the specied key. */
  8539. bool contains (KeyTypeParameter keyToLookFor) const
  8540. {
  8541. const ScopedLockType sl (getLock());
  8542. for (const HashEntry* entry = slots [generateHashFor (keyToLookFor)]; entry != nullptr; entry = entry->nextEntry)
  8543. if (entry->key == keyToLookFor)
  8544. return true;
  8545. return false;
  8546. }
  8547. /** Returns true if the hash contains at least one occurrence of a given value. */
  8548. bool containsValue (ValueTypeParameter valueToLookFor) const
  8549. {
  8550. const ScopedLockType sl (getLock());
  8551. for (int i = getNumSlots(); --i >= 0;)
  8552. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8553. if (entry->value == valueToLookFor)
  8554. return true;
  8555. return false;
  8556. }
  8557. /** Adds or replaces an element in the hash-map.
  8558. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  8559. will be added to the map.
  8560. */
  8561. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  8562. {
  8563. const ScopedLockType sl (getLock());
  8564. const int hashIndex = generateHashFor (newKey);
  8565. if (isPositiveAndBelow (hashIndex, getNumSlots()))
  8566. {
  8567. HashEntry* const firstEntry = slots.getUnchecked (hashIndex);
  8568. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  8569. {
  8570. if (entry->key == newKey)
  8571. {
  8572. entry->value = newValue;
  8573. return;
  8574. }
  8575. }
  8576. slots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  8577. ++totalNumItems;
  8578. if (totalNumItems > (getNumSlots() * 3) / 2)
  8579. remapTable (getNumSlots() * 2);
  8580. }
  8581. }
  8582. /** Removes an item with the given key. */
  8583. void remove (KeyTypeParameter keyToRemove)
  8584. {
  8585. const ScopedLockType sl (getLock());
  8586. const int hashIndex = generateHashFor (keyToRemove);
  8587. HashEntry* entry = slots [hashIndex];
  8588. HashEntry* previous = nullptr;
  8589. while (entry != nullptr)
  8590. {
  8591. if (entry->key == keyToRemove)
  8592. {
  8593. const ScopedPointer<HashEntry> deleter (entry);
  8594. entry = entry->nextEntry;
  8595. if (previous != nullptr)
  8596. previous->nextEntry = entry;
  8597. else
  8598. slots.set (hashIndex, entry);
  8599. --totalNumItems;
  8600. }
  8601. else
  8602. {
  8603. previous = entry;
  8604. entry = entry->nextEntry;
  8605. }
  8606. }
  8607. }
  8608. /** Removes all items with the given value. */
  8609. void removeValue (ValueTypeParameter valueToRemove)
  8610. {
  8611. const ScopedLockType sl (getLock());
  8612. for (int i = getNumSlots(); --i >= 0;)
  8613. {
  8614. HashEntry* entry = slots.getUnchecked(i);
  8615. HashEntry* previous = nullptr;
  8616. while (entry != nullptr)
  8617. {
  8618. if (entry->value == valueToRemove)
  8619. {
  8620. const ScopedPointer<HashEntry> deleter (entry);
  8621. entry = entry->nextEntry;
  8622. if (previous != nullptr)
  8623. previous->nextEntry = entry;
  8624. else
  8625. slots.set (i, entry);
  8626. --totalNumItems;
  8627. }
  8628. else
  8629. {
  8630. previous = entry;
  8631. entry = entry->nextEntry;
  8632. }
  8633. }
  8634. }
  8635. }
  8636. /** Remaps the hash-map to use a different number of slots for its hash function.
  8637. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8638. @see getNumSlots()
  8639. */
  8640. void remapTable (int newNumberOfSlots)
  8641. {
  8642. HashMap newTable (newNumberOfSlots);
  8643. for (int i = getNumSlots(); --i >= 0;)
  8644. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8645. newTable.set (entry->key, entry->value);
  8646. swapWith (newTable);
  8647. }
  8648. /** Returns the number of slots which are available for hashing.
  8649. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8650. @see getNumSlots()
  8651. */
  8652. inline int getNumSlots() const noexcept
  8653. {
  8654. return slots.size();
  8655. }
  8656. /** Efficiently swaps the contents of two hash-maps. */
  8657. void swapWith (HashMap& otherHashMap) noexcept
  8658. {
  8659. const ScopedLockType lock1 (getLock());
  8660. const ScopedLockType lock2 (otherHashMap.getLock());
  8661. slots.swapWithArray (otherHashMap.slots);
  8662. std::swap (totalNumItems, otherHashMap.totalNumItems);
  8663. }
  8664. /** Returns the CriticalSection that locks this structure.
  8665. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8666. an object of ScopedLockType as an RAII lock for it.
  8667. */
  8668. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  8669. /** Returns the type of scoped lock to use for locking this array */
  8670. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8671. private:
  8672. class HashEntry
  8673. {
  8674. public:
  8675. HashEntry (KeyTypeParameter key_, ValueTypeParameter value_, HashEntry* const nextEntry_)
  8676. : key (key_), value (value_), nextEntry (nextEntry_)
  8677. {}
  8678. const KeyType key;
  8679. ValueType value;
  8680. HashEntry* nextEntry;
  8681. JUCE_DECLARE_NON_COPYABLE (HashEntry);
  8682. };
  8683. public:
  8684. /** Iterates over the items in a HashMap.
  8685. To use it, repeatedly call next() until it returns false, e.g.
  8686. @code
  8687. HashMap <String, String> myMap;
  8688. HashMap<String, String>::Iterator i (myMap);
  8689. while (i.next())
  8690. {
  8691. DBG (i.getKey() << " -> " << i.getValue());
  8692. }
  8693. @endcode
  8694. The order in which items are iterated bears no resemblence to the order in which
  8695. they were originally added!
  8696. Obviously as soon as you call any non-const methods on the original hash-map, any
  8697. iterators that were created beforehand will cease to be valid, and should not be used.
  8698. @see HashMap
  8699. */
  8700. class Iterator
  8701. {
  8702. public:
  8703. Iterator (const HashMap& hashMapToIterate)
  8704. : hashMap (hashMapToIterate), entry (0), index (0)
  8705. {}
  8706. /** Moves to the next item, if one is available.
  8707. When this returns true, you can get the item's key and value using getKey() and
  8708. getValue(). If it returns false, the iteration has finished and you should stop.
  8709. */
  8710. bool next()
  8711. {
  8712. if (entry != nullptr)
  8713. entry = entry->nextEntry;
  8714. while (entry == nullptr)
  8715. {
  8716. if (index >= hashMap.getNumSlots())
  8717. return false;
  8718. entry = hashMap.slots.getUnchecked (index++);
  8719. }
  8720. return true;
  8721. }
  8722. /** Returns the current item's key.
  8723. This should only be called when a call to next() has just returned true.
  8724. */
  8725. const KeyType getKey() const
  8726. {
  8727. return entry != nullptr ? entry->key : KeyType();
  8728. }
  8729. /** Returns the current item's value.
  8730. This should only be called when a call to next() has just returned true.
  8731. */
  8732. const ValueType getValue() const
  8733. {
  8734. return entry != nullptr ? entry->value : ValueType();
  8735. }
  8736. private:
  8737. const HashMap& hashMap;
  8738. HashEntry* entry;
  8739. int index;
  8740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator);
  8741. };
  8742. private:
  8743. enum { defaultHashTableSize = 101 };
  8744. friend class Iterator;
  8745. Array <HashEntry*> slots;
  8746. int totalNumItems;
  8747. TypeOfCriticalSectionToUse lock;
  8748. int generateHashFor (KeyTypeParameter key) const
  8749. {
  8750. const int hash = HashFunctionToUse::generateHash (key, getNumSlots());
  8751. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  8752. return hash;
  8753. }
  8754. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap);
  8755. };
  8756. #endif // __JUCE_HASHMAP_JUCEHEADER__
  8757. /*** End of inlined file: juce_HashMap.h ***/
  8758. #endif
  8759. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  8760. #endif
  8761. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  8762. #endif
  8763. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  8764. #endif
  8765. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8766. /*** Start of inlined file: juce_PropertySet.h ***/
  8767. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8768. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8769. /*** Start of inlined file: juce_StringPairArray.h ***/
  8770. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8771. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8772. /*** Start of inlined file: juce_StringArray.h ***/
  8773. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8774. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8775. /**
  8776. A special array for holding a list of strings.
  8777. @see String, StringPairArray
  8778. */
  8779. class JUCE_API StringArray
  8780. {
  8781. public:
  8782. /** Creates an empty string array */
  8783. StringArray() noexcept;
  8784. /** Creates a copy of another string array */
  8785. StringArray (const StringArray& other);
  8786. /** Creates an array containing a single string. */
  8787. explicit StringArray (const String& firstValue);
  8788. /** Creates a copy of an array of string literals.
  8789. @param strings an array of strings to add. Null pointers in the array will be
  8790. treated as empty strings
  8791. @param numberOfStrings how many items there are in the array
  8792. */
  8793. StringArray (const char* const* strings, int numberOfStrings);
  8794. /** Creates a copy of a null-terminated array of string literals.
  8795. Each item from the array passed-in is added, until it encounters a null pointer,
  8796. at which point it stops.
  8797. */
  8798. explicit StringArray (const char* const* strings);
  8799. /** Creates a copy of a null-terminated array of string literals.
  8800. Each item from the array passed-in is added, until it encounters a null pointer,
  8801. at which point it stops.
  8802. */
  8803. explicit StringArray (const wchar_t* const* strings);
  8804. /** Creates a copy of an array of string literals.
  8805. @param strings an array of strings to add. Null pointers in the array will be
  8806. treated as empty strings
  8807. @param numberOfStrings how many items there are in the array
  8808. */
  8809. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8810. /** Destructor. */
  8811. ~StringArray();
  8812. /** Copies the contents of another string array into this one */
  8813. StringArray& operator= (const StringArray& other);
  8814. /** Compares two arrays.
  8815. Comparisons are case-sensitive.
  8816. @returns true only if the other array contains exactly the same strings in the same order
  8817. */
  8818. bool operator== (const StringArray& other) const noexcept;
  8819. /** Compares two arrays.
  8820. Comparisons are case-sensitive.
  8821. @returns false if the other array contains exactly the same strings in the same order
  8822. */
  8823. bool operator!= (const StringArray& other) const noexcept;
  8824. /** Returns the number of strings in the array */
  8825. inline int size() const noexcept { return strings.size(); };
  8826. /** Returns one of the strings from the array.
  8827. If the index is out-of-range, an empty string is returned.
  8828. Obviously the reference returned shouldn't be stored for later use, as the
  8829. string it refers to may disappear when the array changes.
  8830. */
  8831. const String& operator[] (int index) const noexcept;
  8832. /** Returns a reference to one of the strings in the array.
  8833. This lets you modify a string in-place in the array, but you must be sure that
  8834. the index is in-range.
  8835. */
  8836. String& getReference (int index) noexcept;
  8837. /** Searches for a string in the array.
  8838. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8839. @returns true if the string is found inside the array
  8840. */
  8841. bool contains (const String& stringToLookFor,
  8842. bool ignoreCase = false) const;
  8843. /** Searches for a string in the array.
  8844. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8845. @param stringToLookFor the string to try to find
  8846. @param ignoreCase whether the comparison should be case-insensitive
  8847. @param startIndex the first index to start searching from
  8848. @returns the index of the first occurrence of the string in this array,
  8849. or -1 if it isn't found.
  8850. */
  8851. int indexOf (const String& stringToLookFor,
  8852. bool ignoreCase = false,
  8853. int startIndex = 0) const;
  8854. /** Appends a string at the end of the array. */
  8855. void add (const String& stringToAdd);
  8856. /** Inserts a string into the array.
  8857. This will insert a string into the array at the given index, moving
  8858. up the other elements to make room for it.
  8859. If the index is less than zero or greater than the size of the array,
  8860. the new string will be added to the end of the array.
  8861. */
  8862. void insert (int index, const String& stringToAdd);
  8863. /** Adds a string to the array as long as it's not already in there.
  8864. The search can optionally be case-insensitive.
  8865. */
  8866. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8867. /** Replaces one of the strings in the array with another one.
  8868. If the index is higher than the array's size, the new string will be
  8869. added to the end of the array; if it's less than zero nothing happens.
  8870. */
  8871. void set (int index, const String& newString);
  8872. /** Appends some strings from another array to the end of this one.
  8873. @param other the array to add
  8874. @param startIndex the first element of the other array to add
  8875. @param numElementsToAdd the maximum number of elements to add (if this is
  8876. less than zero, they are all added)
  8877. */
  8878. void addArray (const StringArray& other,
  8879. int startIndex = 0,
  8880. int numElementsToAdd = -1);
  8881. /** Breaks up a string into tokens and adds them to this array.
  8882. This will tokenise the given string using whitespace characters as the
  8883. token delimiters, and will add these tokens to the end of the array.
  8884. @returns the number of tokens added
  8885. */
  8886. int addTokens (const String& stringToTokenise,
  8887. bool preserveQuotedStrings);
  8888. /** Breaks up a string into tokens and adds them to this array.
  8889. This will tokenise the given string (using the string passed in to define the
  8890. token delimiters), and will add these tokens to the end of the array.
  8891. @param stringToTokenise the string to tokenise
  8892. @param breakCharacters a string of characters, any of which will be considered
  8893. to be a token delimiter.
  8894. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8895. which are treated as quotes. Any text occurring
  8896. between quotes is not broken up into tokens.
  8897. @returns the number of tokens added
  8898. */
  8899. int addTokens (const String& stringToTokenise,
  8900. const String& breakCharacters,
  8901. const String& quoteCharacters);
  8902. /** Breaks up a string into lines and adds them to this array.
  8903. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8904. to the array. Line-break characters are omitted from the strings that are added to
  8905. the array.
  8906. */
  8907. int addLines (const String& stringToBreakUp);
  8908. /** Removes all elements from the array. */
  8909. void clear();
  8910. /** Removes a string from the array.
  8911. If the index is out-of-range, no action will be taken.
  8912. */
  8913. void remove (int index);
  8914. /** Finds a string in the array and removes it.
  8915. This will remove the first occurrence of the given string from the array. The
  8916. comparison may be case-insensitive depending on the ignoreCase parameter.
  8917. */
  8918. void removeString (const String& stringToRemove,
  8919. bool ignoreCase = false);
  8920. /** Removes a range of elements from the array.
  8921. This will remove a set of elements, starting from the given index,
  8922. and move subsequent elements down to close the gap.
  8923. If the range extends beyond the bounds of the array, it will
  8924. be safely clipped to the size of the array.
  8925. @param startIndex the index of the first element to remove
  8926. @param numberToRemove how many elements should be removed
  8927. */
  8928. void removeRange (int startIndex, int numberToRemove);
  8929. /** Removes any duplicated elements from the array.
  8930. If any string appears in the array more than once, only the first occurrence of
  8931. it will be retained.
  8932. @param ignoreCase whether to use a case-insensitive comparison
  8933. */
  8934. void removeDuplicates (bool ignoreCase);
  8935. /** Removes empty strings from the array.
  8936. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8937. characters will also be removed
  8938. */
  8939. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8940. /** Moves one of the strings to a different position.
  8941. This will move the string to a specified index, shuffling along
  8942. any intervening elements as required.
  8943. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8944. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8945. @param currentIndex the index of the value to be moved. If this isn't a
  8946. valid index, then nothing will be done
  8947. @param newIndex the index at which you'd like this value to end up. If this
  8948. is less than zero, the value will be moved to the end
  8949. of the array
  8950. */
  8951. void move (int currentIndex, int newIndex) noexcept;
  8952. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8953. void trim();
  8954. /** Adds numbers to the strings in the array, to make each string unique.
  8955. This will add numbers to the ends of groups of similar strings.
  8956. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8957. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8958. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8959. also has a number appended to it.
  8960. @param preNumberString when adding a number, this string is added before the number.
  8961. If you pass 0, a default string will be used, which adds
  8962. brackets around the number.
  8963. @param postNumberString this string is appended after any numbers that are added.
  8964. If you pass 0, a default string will be used, which adds
  8965. brackets around the number.
  8966. */
  8967. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8968. bool appendNumberToFirstInstance,
  8969. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (nullptr),
  8970. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (nullptr));
  8971. /** Joins the strings in the array together into one string.
  8972. This will join a range of elements from the array into a string, separating
  8973. them with a given string.
  8974. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8975. @param separatorString the string to insert between all the strings
  8976. @param startIndex the first element to join
  8977. @param numberOfElements how many elements to join together. If this is less
  8978. than zero, all available elements will be used.
  8979. */
  8980. const String joinIntoString (const String& separatorString,
  8981. int startIndex = 0,
  8982. int numberOfElements = -1) const;
  8983. /** Sorts the array into alphabetical order.
  8984. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8985. */
  8986. void sort (bool ignoreCase);
  8987. /** Reduces the amount of storage being used by the array.
  8988. Arrays typically allocate slightly more storage than they need, and after
  8989. removing elements, they may have quite a lot of unused space allocated.
  8990. This method will reduce the amount of allocated storage to a minimum.
  8991. */
  8992. void minimiseStorageOverheads();
  8993. private:
  8994. Array <String> strings;
  8995. JUCE_LEAK_DETECTOR (StringArray);
  8996. };
  8997. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8998. /*** End of inlined file: juce_StringArray.h ***/
  8999. /**
  9000. A container for holding a set of strings which are keyed by another string.
  9001. @see StringArray
  9002. */
  9003. class JUCE_API StringPairArray
  9004. {
  9005. public:
  9006. /** Creates an empty array */
  9007. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  9008. /** Creates a copy of another array */
  9009. StringPairArray (const StringPairArray& other);
  9010. /** Destructor. */
  9011. ~StringPairArray();
  9012. /** Copies the contents of another string array into this one */
  9013. StringPairArray& operator= (const StringPairArray& other);
  9014. /** Compares two arrays.
  9015. Comparisons are case-sensitive.
  9016. @returns true only if the other array contains exactly the same strings with the same keys
  9017. */
  9018. bool operator== (const StringPairArray& other) const;
  9019. /** Compares two arrays.
  9020. Comparisons are case-sensitive.
  9021. @returns false if the other array contains exactly the same strings with the same keys
  9022. */
  9023. bool operator!= (const StringPairArray& other) const;
  9024. /** Finds the value corresponding to a key string.
  9025. If no such key is found, this will just return an empty string. To check whether
  9026. a given key actually exists (because it might actually be paired with an empty string), use
  9027. the getAllKeys() method to obtain a list.
  9028. Obviously the reference returned shouldn't be stored for later use, as the
  9029. string it refers to may disappear when the array changes.
  9030. @see getValue
  9031. */
  9032. const String& operator[] (const String& key) const;
  9033. /** Finds the value corresponding to a key string.
  9034. If no such key is found, this will just return the value provided as a default.
  9035. @see operator[]
  9036. */
  9037. const String getValue (const String& key, const String& defaultReturnValue) const;
  9038. /** Returns a list of all keys in the array. */
  9039. const StringArray& getAllKeys() const noexcept { return keys; }
  9040. /** Returns a list of all values in the array. */
  9041. const StringArray& getAllValues() const noexcept { return values; }
  9042. /** Returns the number of strings in the array */
  9043. inline int size() const noexcept { return keys.size(); };
  9044. /** Adds or amends a key/value pair.
  9045. If a value already exists with this key, its value will be overwritten,
  9046. otherwise the key/value pair will be added to the array.
  9047. */
  9048. void set (const String& key, const String& value);
  9049. /** Adds the items from another array to this one.
  9050. This is equivalent to using set() to add each of the pairs from the other array.
  9051. */
  9052. void addArray (const StringPairArray& other);
  9053. /** Removes all elements from the array. */
  9054. void clear();
  9055. /** Removes a string from the array based on its key.
  9056. If the key isn't found, nothing will happen.
  9057. */
  9058. void remove (const String& key);
  9059. /** Removes a string from the array based on its index.
  9060. If the index is out-of-range, no action will be taken.
  9061. */
  9062. void remove (int index);
  9063. /** Indicates whether to use a case-insensitive search when looking up a key string.
  9064. */
  9065. void setIgnoresCase (bool shouldIgnoreCase);
  9066. /** Returns a descriptive string containing the items.
  9067. This is handy for dumping the contents of an array.
  9068. */
  9069. const String getDescription() const;
  9070. /** Reduces the amount of storage being used by the array.
  9071. Arrays typically allocate slightly more storage than they need, and after
  9072. removing elements, they may have quite a lot of unused space allocated.
  9073. This method will reduce the amount of allocated storage to a minimum.
  9074. */
  9075. void minimiseStorageOverheads();
  9076. private:
  9077. StringArray keys, values;
  9078. bool ignoreCase;
  9079. JUCE_LEAK_DETECTOR (StringPairArray);
  9080. };
  9081. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  9082. /*** End of inlined file: juce_StringPairArray.h ***/
  9083. /*** Start of inlined file: juce_XmlElement.h ***/
  9084. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  9085. #define __JUCE_XMLELEMENT_JUCEHEADER__
  9086. /*** Start of inlined file: juce_File.h ***/
  9087. #ifndef __JUCE_FILE_JUCEHEADER__
  9088. #define __JUCE_FILE_JUCEHEADER__
  9089. /*** Start of inlined file: juce_Time.h ***/
  9090. #ifndef __JUCE_TIME_JUCEHEADER__
  9091. #define __JUCE_TIME_JUCEHEADER__
  9092. /*** Start of inlined file: juce_RelativeTime.h ***/
  9093. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  9094. #define __JUCE_RELATIVETIME_JUCEHEADER__
  9095. /** A relative measure of time.
  9096. The time is stored as a number of seconds, at double-precision floating
  9097. point accuracy, and may be positive or negative.
  9098. If you need an absolute time, (i.e. a date + time), see the Time class.
  9099. */
  9100. class JUCE_API RelativeTime
  9101. {
  9102. public:
  9103. /** Creates a RelativeTime.
  9104. @param seconds the number of seconds, which may be +ve or -ve.
  9105. @see milliseconds, minutes, hours, days, weeks
  9106. */
  9107. explicit RelativeTime (double seconds = 0.0) noexcept;
  9108. /** Copies another relative time. */
  9109. RelativeTime (const RelativeTime& other) noexcept;
  9110. /** Copies another relative time. */
  9111. RelativeTime& operator= (const RelativeTime& other) noexcept;
  9112. /** Destructor. */
  9113. ~RelativeTime() noexcept;
  9114. /** Creates a new RelativeTime object representing a number of milliseconds.
  9115. @see minutes, hours, days, weeks
  9116. */
  9117. static const RelativeTime milliseconds (int milliseconds) noexcept;
  9118. /** Creates a new RelativeTime object representing a number of milliseconds.
  9119. @see minutes, hours, days, weeks
  9120. */
  9121. static const RelativeTime milliseconds (int64 milliseconds) noexcept;
  9122. /** Creates a new RelativeTime object representing a number of minutes.
  9123. @see milliseconds, hours, days, weeks
  9124. */
  9125. static const RelativeTime minutes (double numberOfMinutes) noexcept;
  9126. /** Creates a new RelativeTime object representing a number of hours.
  9127. @see milliseconds, minutes, days, weeks
  9128. */
  9129. static const RelativeTime hours (double numberOfHours) noexcept;
  9130. /** Creates a new RelativeTime object representing a number of days.
  9131. @see milliseconds, minutes, hours, weeks
  9132. */
  9133. static const RelativeTime days (double numberOfDays) noexcept;
  9134. /** Creates a new RelativeTime object representing a number of weeks.
  9135. @see milliseconds, minutes, hours, days
  9136. */
  9137. static const RelativeTime weeks (double numberOfWeeks) noexcept;
  9138. /** Returns the number of milliseconds this time represents.
  9139. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9140. */
  9141. int64 inMilliseconds() const noexcept;
  9142. /** Returns the number of seconds this time represents.
  9143. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  9144. */
  9145. double inSeconds() const noexcept { return seconds; }
  9146. /** Returns the number of minutes this time represents.
  9147. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  9148. */
  9149. double inMinutes() const noexcept;
  9150. /** Returns the number of hours this time represents.
  9151. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  9152. */
  9153. double inHours() const noexcept;
  9154. /** Returns the number of days this time represents.
  9155. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  9156. */
  9157. double inDays() const noexcept;
  9158. /** Returns the number of weeks this time represents.
  9159. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  9160. */
  9161. double inWeeks() const noexcept;
  9162. /** Returns a readable textual description of the time.
  9163. The exact format of the string returned will depend on
  9164. the magnitude of the time - e.g.
  9165. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  9166. so that only the two most significant units are printed.
  9167. The returnValueForZeroTime value is the result that is returned if the
  9168. length is zero. Depending on your application you might want to use this
  9169. to return something more relevant like "empty" or "0 secs", etc.
  9170. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9171. */
  9172. const String getDescription (const String& returnValueForZeroTime = "0") const;
  9173. /** Adds another RelativeTime to this one. */
  9174. const RelativeTime& operator+= (const RelativeTime& timeToAdd) noexcept;
  9175. /** Subtracts another RelativeTime from this one. */
  9176. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) noexcept;
  9177. /** Adds a number of seconds to this time. */
  9178. const RelativeTime& operator+= (double secondsToAdd) noexcept;
  9179. /** Subtracts a number of seconds from this time. */
  9180. const RelativeTime& operator-= (double secondsToSubtract) noexcept;
  9181. private:
  9182. double seconds;
  9183. };
  9184. /** Compares two RelativeTimes. */
  9185. bool operator== (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9186. /** Compares two RelativeTimes. */
  9187. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9188. /** Compares two RelativeTimes. */
  9189. bool operator> (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9190. /** Compares two RelativeTimes. */
  9191. bool operator< (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9192. /** Compares two RelativeTimes. */
  9193. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9194. /** Compares two RelativeTimes. */
  9195. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9196. /** Adds two RelativeTimes together. */
  9197. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9198. /** Subtracts two RelativeTimes. */
  9199. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9200. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  9201. /*** End of inlined file: juce_RelativeTime.h ***/
  9202. /**
  9203. Holds an absolute date and time.
  9204. Internally, the time is stored at millisecond precision.
  9205. @see RelativeTime
  9206. */
  9207. class JUCE_API Time
  9208. {
  9209. public:
  9210. /** Creates a Time object.
  9211. This default constructor creates a time of 1st January 1970, (which is
  9212. represented internally as 0ms).
  9213. To create a time object representing the current time, use getCurrentTime().
  9214. @see getCurrentTime
  9215. */
  9216. Time() noexcept;
  9217. /** Creates a time based on a number of milliseconds.
  9218. The internal millisecond count is set to 0 (1st January 1970). To create a
  9219. time object set to the current time, use getCurrentTime().
  9220. @param millisecondsSinceEpoch the number of milliseconds since the unix
  9221. 'epoch' (midnight Jan 1st 1970).
  9222. @see getCurrentTime, currentTimeMillis
  9223. */
  9224. explicit Time (int64 millisecondsSinceEpoch) noexcept;
  9225. /** Creates a time from a set of date components.
  9226. The timezone is assumed to be whatever the system is using as its locale.
  9227. @param year the year, in 4-digit format, e.g. 2004
  9228. @param month the month, in the range 0 to 11
  9229. @param day the day of the month, in the range 1 to 31
  9230. @param hours hours in 24-hour clock format, 0 to 23
  9231. @param minutes minutes 0 to 59
  9232. @param seconds seconds 0 to 59
  9233. @param milliseconds milliseconds 0 to 999
  9234. @param useLocalTime if true, encode using the current machine's local time; if
  9235. false, it will always work in GMT.
  9236. */
  9237. Time (int year,
  9238. int month,
  9239. int day,
  9240. int hours,
  9241. int minutes,
  9242. int seconds = 0,
  9243. int milliseconds = 0,
  9244. bool useLocalTime = true) noexcept;
  9245. /** Creates a copy of another Time object. */
  9246. Time (const Time& other) noexcept;
  9247. /** Destructor. */
  9248. ~Time() noexcept;
  9249. /** Copies this time from another one. */
  9250. Time& operator= (const Time& other) noexcept;
  9251. /** Returns a Time object that is set to the current system time.
  9252. @see currentTimeMillis
  9253. */
  9254. static const Time JUCE_CALLTYPE getCurrentTime() noexcept;
  9255. /** Returns the time as a number of milliseconds.
  9256. @returns the number of milliseconds this Time object represents, since
  9257. midnight jan 1st 1970.
  9258. @see getMilliseconds
  9259. */
  9260. int64 toMilliseconds() const noexcept { return millisSinceEpoch; }
  9261. /** Returns the year.
  9262. A 4-digit format is used, e.g. 2004.
  9263. */
  9264. int getYear() const noexcept;
  9265. /** Returns the number of the month.
  9266. The value returned is in the range 0 to 11.
  9267. @see getMonthName
  9268. */
  9269. int getMonth() const noexcept;
  9270. /** Returns the name of the month.
  9271. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9272. it'll return the long form, e.g. "January"
  9273. @see getMonth
  9274. */
  9275. const String getMonthName (bool threeLetterVersion) const;
  9276. /** Returns the day of the month.
  9277. The value returned is in the range 1 to 31.
  9278. */
  9279. int getDayOfMonth() const noexcept;
  9280. /** Returns the number of the day of the week.
  9281. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  9282. */
  9283. int getDayOfWeek() const noexcept;
  9284. /** Returns the name of the weekday.
  9285. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9286. false, it'll return the full version, e.g. "Tuesday".
  9287. */
  9288. const String getWeekdayName (bool threeLetterVersion) const;
  9289. /** Returns the number of hours since midnight.
  9290. This is in 24-hour clock format, in the range 0 to 23.
  9291. @see getHoursInAmPmFormat, isAfternoon
  9292. */
  9293. int getHours() const noexcept;
  9294. /** Returns true if the time is in the afternoon.
  9295. So it returns true for "PM", false for "AM".
  9296. @see getHoursInAmPmFormat, getHours
  9297. */
  9298. bool isAfternoon() const noexcept;
  9299. /** Returns the hours in 12-hour clock format.
  9300. This will return a value 1 to 12 - use isAfternoon() to find out
  9301. whether this is in the afternoon or morning.
  9302. @see getHours, isAfternoon
  9303. */
  9304. int getHoursInAmPmFormat() const noexcept;
  9305. /** Returns the number of minutes, 0 to 59. */
  9306. int getMinutes() const noexcept;
  9307. /** Returns the number of seconds, 0 to 59. */
  9308. int getSeconds() const noexcept;
  9309. /** Returns the number of milliseconds, 0 to 999.
  9310. Unlike toMilliseconds(), this just returns the position within the
  9311. current second rather than the total number since the epoch.
  9312. @see toMilliseconds
  9313. */
  9314. int getMilliseconds() const noexcept;
  9315. /** Returns true if the local timezone uses a daylight saving correction. */
  9316. bool isDaylightSavingTime() const noexcept;
  9317. /** Returns a 3-character string to indicate the local timezone. */
  9318. const String getTimeZone() const noexcept;
  9319. /** Quick way of getting a string version of a date and time.
  9320. For a more powerful way of formatting the date and time, see the formatted() method.
  9321. @param includeDate whether to include the date in the string
  9322. @param includeTime whether to include the time in the string
  9323. @param includeSeconds if the time is being included, this provides an option not to include
  9324. the seconds in it
  9325. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  9326. hour notation.
  9327. @see formatted
  9328. */
  9329. const String toString (bool includeDate,
  9330. bool includeTime,
  9331. bool includeSeconds = true,
  9332. bool use24HourClock = false) const noexcept;
  9333. /** Converts this date/time to a string with a user-defined format.
  9334. This uses the C strftime() function to format this time as a string. To save you
  9335. looking it up, these are the escape codes that strftime uses (other codes might
  9336. work on some platforms and not others, but these are the common ones):
  9337. %a is replaced by the locale's abbreviated weekday name.
  9338. %A is replaced by the locale's full weekday name.
  9339. %b is replaced by the locale's abbreviated month name.
  9340. %B is replaced by the locale's full month name.
  9341. %c is replaced by the locale's appropriate date and time representation.
  9342. %d is replaced by the day of the month as a decimal number [01,31].
  9343. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  9344. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  9345. %j is replaced by the day of the year as a decimal number [001,366].
  9346. %m is replaced by the month as a decimal number [01,12].
  9347. %M is replaced by the minute as a decimal number [00,59].
  9348. %p is replaced by the locale's equivalent of either a.m. or p.m.
  9349. %S is replaced by the second as a decimal number [00,61].
  9350. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  9351. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  9352. %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.
  9353. %x is replaced by the locale's appropriate date representation.
  9354. %X is replaced by the locale's appropriate time representation.
  9355. %y is replaced by the year without century as a decimal number [00,99].
  9356. %Y is replaced by the year with century as a decimal number.
  9357. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  9358. %% is replaced by %.
  9359. @see toString
  9360. */
  9361. const String formatted (const String& format) const;
  9362. /** Adds a RelativeTime to this time. */
  9363. Time& operator+= (const RelativeTime& delta);
  9364. /** Subtracts a RelativeTime from this time. */
  9365. Time& operator-= (const RelativeTime& delta);
  9366. /** Tries to set the computer's clock.
  9367. @returns true if this succeeds, although depending on the system, the
  9368. application might not have sufficient privileges to do this.
  9369. */
  9370. bool setSystemTimeToThisTime() const;
  9371. /** Returns the name of a day of the week.
  9372. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  9373. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9374. false, it'll return the full version, e.g. "Tuesday".
  9375. */
  9376. static const String getWeekdayName (int dayNumber,
  9377. bool threeLetterVersion);
  9378. /** Returns the name of one of the months.
  9379. @param monthNumber the month, 0 to 11
  9380. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9381. it'll return the long form, e.g. "January"
  9382. */
  9383. static const String getMonthName (int monthNumber,
  9384. bool threeLetterVersion);
  9385. // Static methods for getting system timers directly..
  9386. /** Returns the current system time.
  9387. Returns the number of milliseconds since midnight jan 1st 1970.
  9388. Should be accurate to within a few millisecs, depending on platform,
  9389. hardware, etc.
  9390. */
  9391. static int64 currentTimeMillis() noexcept;
  9392. /** Returns the number of millisecs since a fixed event (usually system startup).
  9393. This returns a monotonically increasing value which it unaffected by changes to the
  9394. system clock. It should be accurate to within a few millisecs, depending on platform,
  9395. hardware, etc.
  9396. @see getApproximateMillisecondCounter
  9397. */
  9398. static uint32 getMillisecondCounter() noexcept;
  9399. /** Returns the number of millisecs since a fixed event (usually system startup).
  9400. This has the same function as getMillisecondCounter(), but returns a more accurate
  9401. value, using a higher-resolution timer if one is available.
  9402. @see getMillisecondCounter
  9403. */
  9404. static double getMillisecondCounterHiRes() noexcept;
  9405. /** Waits until the getMillisecondCounter() reaches a given value.
  9406. This will make the thread sleep as efficiently as it can while it's waiting.
  9407. */
  9408. static void waitForMillisecondCounter (uint32 targetTime) noexcept;
  9409. /** Less-accurate but faster version of getMillisecondCounter().
  9410. This will return the last value that getMillisecondCounter() returned, so doesn't
  9411. need to make a system call, but is less accurate - it shouldn't be more than
  9412. 100ms away from the correct time, though, so is still accurate enough for a
  9413. lot of purposes.
  9414. @see getMillisecondCounter
  9415. */
  9416. static uint32 getApproximateMillisecondCounter() noexcept;
  9417. // High-resolution timers..
  9418. /** Returns the current high-resolution counter's tick-count.
  9419. This is a similar idea to getMillisecondCounter(), but with a higher
  9420. resolution.
  9421. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  9422. secondsToHighResolutionTicks
  9423. */
  9424. static int64 getHighResolutionTicks() noexcept;
  9425. /** Returns the resolution of the high-resolution counter in ticks per second.
  9426. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  9427. secondsToHighResolutionTicks
  9428. */
  9429. static int64 getHighResolutionTicksPerSecond() noexcept;
  9430. /** Converts a number of high-resolution ticks into seconds.
  9431. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9432. secondsToHighResolutionTicks
  9433. */
  9434. static double highResolutionTicksToSeconds (int64 ticks) noexcept;
  9435. /** Converts a number seconds into high-resolution ticks.
  9436. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9437. highResolutionTicksToSeconds
  9438. */
  9439. static int64 secondsToHighResolutionTicks (double seconds) noexcept;
  9440. private:
  9441. int64 millisSinceEpoch;
  9442. };
  9443. /** Adds a RelativeTime to a Time. */
  9444. JUCE_API const Time operator+ (const Time& time, const RelativeTime& delta);
  9445. /** Adds a RelativeTime to a Time. */
  9446. JUCE_API const Time operator+ (const RelativeTime& delta, const Time& time);
  9447. /** Subtracts a RelativeTime from a Time. */
  9448. JUCE_API const Time operator- (const Time& time, const RelativeTime& delta);
  9449. /** Returns the relative time difference between two times. */
  9450. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  9451. /** Compares two Time objects. */
  9452. JUCE_API bool operator== (const Time& time1, const Time& time2);
  9453. /** Compares two Time objects. */
  9454. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  9455. /** Compares two Time objects. */
  9456. JUCE_API bool operator< (const Time& time1, const Time& time2);
  9457. /** Compares two Time objects. */
  9458. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  9459. /** Compares two Time objects. */
  9460. JUCE_API bool operator> (const Time& time1, const Time& time2);
  9461. /** Compares two Time objects. */
  9462. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  9463. #endif // __JUCE_TIME_JUCEHEADER__
  9464. /*** End of inlined file: juce_Time.h ***/
  9465. class FileInputStream;
  9466. class FileOutputStream;
  9467. /**
  9468. Represents a local file or directory.
  9469. This class encapsulates the absolute pathname of a file or directory, and
  9470. has methods for finding out about the file and changing its properties.
  9471. To read or write to the file, there are methods for returning an input or
  9472. output stream.
  9473. @see FileInputStream, FileOutputStream
  9474. */
  9475. class JUCE_API File
  9476. {
  9477. public:
  9478. /** Creates an (invalid) file object.
  9479. The file is initially set to an empty path, so getFullPath() will return
  9480. an empty string, and comparing the file to File::nonexistent will return
  9481. true.
  9482. You can use its operator= method to point it at a proper file.
  9483. */
  9484. File() {}
  9485. /** Creates a file from an absolute path.
  9486. If the path supplied is a relative path, it is taken to be relative
  9487. to the current working directory (see File::getCurrentWorkingDirectory()),
  9488. but this isn't a recommended way of creating a file, because you
  9489. never know what the CWD is going to be.
  9490. On the Mac/Linux, the path can include "~" notation for referring to
  9491. user home directories.
  9492. */
  9493. File (const String& path);
  9494. /** Creates a copy of another file object. */
  9495. File (const File& other);
  9496. /** Destructor. */
  9497. ~File() {}
  9498. /** Sets the file based on an absolute pathname.
  9499. If the path supplied is a relative path, it is taken to be relative
  9500. to the current working directory (see File::getCurrentWorkingDirectory()),
  9501. but this isn't a recommended way of creating a file, because you
  9502. never know what the CWD is going to be.
  9503. On the Mac/Linux, the path can include "~" notation for referring to
  9504. user home directories.
  9505. */
  9506. File& operator= (const String& newFilePath);
  9507. /** Copies from another file object. */
  9508. File& operator= (const File& otherFile);
  9509. /** This static constant is used for referring to an 'invalid' file. */
  9510. static const File nonexistent;
  9511. /** Checks whether the file actually exists.
  9512. @returns true if the file exists, either as a file or a directory.
  9513. @see existsAsFile, isDirectory
  9514. */
  9515. bool exists() const;
  9516. /** Checks whether the file exists and is a file rather than a directory.
  9517. @returns true only if this is a real file, false if it's a directory
  9518. or doesn't exist
  9519. @see exists, isDirectory
  9520. */
  9521. bool existsAsFile() const;
  9522. /** Checks whether the file is a directory that exists.
  9523. @returns true only if the file is a directory which actually exists, so
  9524. false if it's a file or doesn't exist at all
  9525. @see exists, existsAsFile
  9526. */
  9527. bool isDirectory() const;
  9528. /** Returns the size of the file in bytes.
  9529. @returns the number of bytes in the file, or 0 if it doesn't exist.
  9530. */
  9531. int64 getSize() const;
  9532. /** Utility function to convert a file size in bytes to a neat string description.
  9533. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  9534. 2000000 would produce "2 MB", etc.
  9535. */
  9536. static const String descriptionOfSizeInBytes (int64 bytes);
  9537. /** Returns the complete, absolute path of this file.
  9538. This includes the filename and all its parent folders. On Windows it'll
  9539. also include the drive letter prefix; on Mac or Linux it'll be a complete
  9540. path starting from the root folder.
  9541. If you just want the file's name, you should use getFileName() or
  9542. getFileNameWithoutExtension().
  9543. @see getFileName, getRelativePathFrom
  9544. */
  9545. const String& getFullPathName() const noexcept { return fullPath; }
  9546. /** Returns the last section of the pathname.
  9547. Returns just the final part of the path - e.g. if the whole path
  9548. is "/moose/fish/foo.txt" this will return "foo.txt".
  9549. For a directory, it returns the final part of the path - e.g. for the
  9550. directory "/moose/fish" it'll return "fish".
  9551. If the filename begins with a dot, it'll return the whole filename, e.g. for
  9552. "/moose/.fish", it'll return ".fish"
  9553. @see getFullPathName, getFileNameWithoutExtension
  9554. */
  9555. const String getFileName() const;
  9556. /** Creates a relative path that refers to a file relatively to a given directory.
  9557. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  9558. would return "../../foo.txt".
  9559. If it's not possible to navigate from one file to the other, an absolute
  9560. path is returned. If the paths are invalid, an empty string may also be
  9561. returned.
  9562. @param directoryToBeRelativeTo the directory which the resultant string will
  9563. be relative to. If this is actually a file rather than
  9564. a directory, its parent directory will be used instead.
  9565. If it doesn't exist, it's assumed to be a directory.
  9566. @see getChildFile, isAbsolutePath
  9567. */
  9568. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  9569. /** Returns the file's extension.
  9570. Returns the file extension of this file, also including the dot.
  9571. e.g. "/moose/fish/foo.txt" would return ".txt"
  9572. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  9573. */
  9574. const String getFileExtension() const;
  9575. /** Checks whether the file has a given extension.
  9576. @param extensionToTest the extension to look for - it doesn't matter whether or
  9577. not this string has a dot at the start, so ".wav" and "wav"
  9578. will have the same effect. The comparison used is
  9579. case-insensitve. To compare with multiple extensions, this
  9580. parameter can contain multiple strings, separated by semi-colons -
  9581. so, for example: hasFileExtension (".jpeg;png;gif") would return
  9582. true if the file has any of those three extensions.
  9583. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  9584. */
  9585. bool hasFileExtension (const String& extensionToTest) const;
  9586. /** Returns a version of this file with a different file extension.
  9587. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  9588. @param newExtension the new extension, either with or without a dot at the start (this
  9589. doesn't make any difference). To get remove a file's extension altogether,
  9590. pass an empty string into this function.
  9591. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  9592. */
  9593. const File withFileExtension (const String& newExtension) const;
  9594. /** Returns the last part of the filename, without its file extension.
  9595. e.g. for "/moose/fish/foo.txt" this will return "foo".
  9596. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  9597. */
  9598. const String getFileNameWithoutExtension() const;
  9599. /** Returns a 32-bit hash-code that identifies this file.
  9600. This is based on the filename. Obviously it's possible, although unlikely, that
  9601. two files will have the same hash-code.
  9602. */
  9603. int hashCode() const;
  9604. /** Returns a 64-bit hash-code that identifies this file.
  9605. This is based on the filename. Obviously it's possible, although unlikely, that
  9606. two files will have the same hash-code.
  9607. */
  9608. int64 hashCode64() const;
  9609. /** Returns a file based on a relative path.
  9610. This will find a child file or directory of the current object.
  9611. e.g.
  9612. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9613. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9614. If the string is actually an absolute path, it will be treated as such, e.g.
  9615. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9616. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9617. */
  9618. const File getChildFile (String relativePath) const;
  9619. /** Returns a file which is in the same directory as this one.
  9620. This is equivalent to getParentDirectory().getChildFile (name).
  9621. @see getChildFile, getParentDirectory
  9622. */
  9623. const File getSiblingFile (const String& siblingFileName) const;
  9624. /** Returns the directory that contains this file or directory.
  9625. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9626. */
  9627. const File getParentDirectory() const;
  9628. /** Checks whether a file is somewhere inside a directory.
  9629. Returns true if this file is somewhere inside a subdirectory of the directory
  9630. that is passed in. Neither file actually has to exist, because the function
  9631. just checks the paths for similarities.
  9632. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9633. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9634. */
  9635. bool isAChildOf (const File& potentialParentDirectory) const;
  9636. /** Chooses a filename relative to this one that doesn't already exist.
  9637. If this file is a directory, this will return a child file of this
  9638. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9639. it finds one that isn't already there.
  9640. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9641. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9642. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9643. @param prefix the string to use for the filename before the number
  9644. @param suffix the string to add to the filename after the number
  9645. @param putNumbersInBrackets if true, this will create filenames in the
  9646. format "prefix(number)suffix", if false, it will leave the
  9647. brackets out.
  9648. */
  9649. const File getNonexistentChildFile (const String& prefix,
  9650. const String& suffix,
  9651. bool putNumbersInBrackets = true) const;
  9652. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9653. If this file doesn't exist, this will just return itself, otherwise it
  9654. will return an appropriate sibling that doesn't exist, e.g. if a file
  9655. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9656. @param putNumbersInBrackets whether to add brackets around the numbers that
  9657. get appended to the new filename.
  9658. */
  9659. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9660. /** Compares the pathnames for two files. */
  9661. bool operator== (const File& otherFile) const;
  9662. /** Compares the pathnames for two files. */
  9663. bool operator!= (const File& otherFile) const;
  9664. /** Compares the pathnames for two files. */
  9665. bool operator< (const File& otherFile) const;
  9666. /** Compares the pathnames for two files. */
  9667. bool operator> (const File& otherFile) const;
  9668. /** Checks whether a file can be created or written to.
  9669. @returns true if it's possible to create and write to this file. If the file
  9670. doesn't already exist, this will check its parent directory to
  9671. see if writing is allowed.
  9672. @see setReadOnly
  9673. */
  9674. bool hasWriteAccess() const;
  9675. /** Changes the write-permission of a file or directory.
  9676. @param shouldBeReadOnly whether to add or remove write-permission
  9677. @param applyRecursively if the file is a directory and this is true, it will
  9678. recurse through all the subfolders changing the permissions
  9679. of all files
  9680. @returns true if it manages to change the file's permissions.
  9681. @see hasWriteAccess
  9682. */
  9683. bool setReadOnly (bool shouldBeReadOnly,
  9684. bool applyRecursively = false) const;
  9685. /** Returns true if this file is a hidden or system file.
  9686. The criteria for deciding whether a file is hidden are platform-dependent.
  9687. */
  9688. bool isHidden() const;
  9689. /** If this file is a link, this returns the file that it points to.
  9690. If this file isn't actually link, it'll just return itself.
  9691. */
  9692. const File getLinkedTarget() const;
  9693. /** Returns the last modification time of this file.
  9694. @returns the time, or an invalid time if the file doesn't exist.
  9695. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9696. */
  9697. const Time getLastModificationTime() const;
  9698. /** Returns the last time this file was accessed.
  9699. @returns the time, or an invalid time if the file doesn't exist.
  9700. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9701. */
  9702. const Time getLastAccessTime() const;
  9703. /** Returns the time that this file was created.
  9704. @returns the time, or an invalid time if the file doesn't exist.
  9705. @see getLastModificationTime, getLastAccessTime
  9706. */
  9707. const Time getCreationTime() const;
  9708. /** Changes the modification time for this file.
  9709. @param newTime the time to apply to the file
  9710. @returns true if it manages to change the file's time.
  9711. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9712. */
  9713. bool setLastModificationTime (const Time& newTime) const;
  9714. /** Changes the last-access time for this file.
  9715. @param newTime the time to apply to the file
  9716. @returns true if it manages to change the file's time.
  9717. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9718. */
  9719. bool setLastAccessTime (const Time& newTime) const;
  9720. /** Changes the creation date for this file.
  9721. @param newTime the time to apply to the file
  9722. @returns true if it manages to change the file's time.
  9723. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9724. */
  9725. bool setCreationTime (const Time& newTime) const;
  9726. /** If possible, this will try to create a version string for the given file.
  9727. The OS may be able to look at the file and give a version for it - e.g. with
  9728. executables, bundles, dlls, etc. If no version is available, this will
  9729. return an empty string.
  9730. */
  9731. const String getVersion() const;
  9732. /** Creates an empty file if it doesn't already exist.
  9733. If the file that this object refers to doesn't exist, this will create a file
  9734. of zero size.
  9735. If it already exists or is a directory, this method will do nothing.
  9736. @returns true if the file has been created (or if it already existed).
  9737. @see createDirectory
  9738. */
  9739. bool create() const;
  9740. /** Creates a new directory for this filename.
  9741. This will try to create the file as a directory, and fill also create
  9742. any parent directories it needs in order to complete the operation.
  9743. @returns true if the directory has been created successfully, (or if it
  9744. already existed beforehand).
  9745. @see create
  9746. */
  9747. bool createDirectory() const;
  9748. /** Deletes a file.
  9749. If this file is actually a directory, it may not be deleted correctly if it
  9750. contains files. See deleteRecursively() as a better way of deleting directories.
  9751. @returns true if the file has been successfully deleted (or if it didn't exist to
  9752. begin with).
  9753. @see deleteRecursively
  9754. */
  9755. bool deleteFile() const;
  9756. /** Deletes a file or directory and all its subdirectories.
  9757. If this file is a directory, this will try to delete it and all its subfolders. If
  9758. it's just a file, it will just try to delete the file.
  9759. @returns true if the file and all its subfolders have been successfully deleted
  9760. (or if it didn't exist to begin with).
  9761. @see deleteFile
  9762. */
  9763. bool deleteRecursively() const;
  9764. /** Moves this file or folder to the trash.
  9765. @returns true if the operation succeeded. It could fail if the trash is full, or
  9766. if the file is write-protected, so you should check the return value
  9767. and act appropriately.
  9768. */
  9769. bool moveToTrash() const;
  9770. /** Moves or renames a file.
  9771. Tries to move a file to a different location.
  9772. If the target file already exists, this will attempt to delete it first, and
  9773. will fail if this can't be done.
  9774. Note that the destination file isn't the directory to put it in, it's the actual
  9775. filename that you want the new file to have.
  9776. @returns true if the operation succeeds
  9777. */
  9778. bool moveFileTo (const File& targetLocation) const;
  9779. /** Copies a file.
  9780. Tries to copy a file to a different location.
  9781. If the target file already exists, this will attempt to delete it first, and
  9782. will fail if this can't be done.
  9783. @returns true if the operation succeeds
  9784. */
  9785. bool copyFileTo (const File& targetLocation) const;
  9786. /** Copies a directory.
  9787. Tries to copy an entire directory, recursively.
  9788. If this file isn't a directory or if any target files can't be created, this
  9789. will return false.
  9790. @param newDirectory the directory that this one should be copied to. Note that this
  9791. is the name of the actual directory to create, not the directory
  9792. into which the new one should be placed, so there must be enough
  9793. write privileges to create it if it doesn't exist. Any files inside
  9794. it will be overwritten by similarly named ones that are copied.
  9795. */
  9796. bool copyDirectoryTo (const File& newDirectory) const;
  9797. /** Used in file searching, to specify whether to return files, directories, or both.
  9798. */
  9799. enum TypesOfFileToFind
  9800. {
  9801. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9802. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9803. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9804. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9805. };
  9806. /** Searches inside a directory for files matching a wildcard pattern.
  9807. Assuming that this file is a directory, this method will search it
  9808. for either files or subdirectories whose names match a filename pattern.
  9809. @param results an array to which File objects will be added for the
  9810. files that the search comes up with
  9811. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9812. return files, directories, or both. If the ignoreHiddenFiles flag
  9813. is also added to this value, hidden files won't be returned
  9814. @param searchRecursively if true, all subdirectories will be recursed into to do
  9815. an exhaustive search
  9816. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9817. @returns the number of results that have been found
  9818. @see getNumberOfChildFiles, DirectoryIterator
  9819. */
  9820. int findChildFiles (Array<File>& results,
  9821. int whatToLookFor,
  9822. bool searchRecursively,
  9823. const String& wildCardPattern = "*") const;
  9824. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9825. Assuming that this file is a directory, this method will search it
  9826. for either files or subdirectories whose names match a filename pattern,
  9827. and will return the number of matches found.
  9828. This isn't a recursive call, and will only search this directory, not
  9829. its children.
  9830. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9831. count files, directories, or both. If the ignoreHiddenFiles flag
  9832. is also added to this value, hidden files won't be counted
  9833. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9834. @returns the number of matches found
  9835. @see findChildFiles, DirectoryIterator
  9836. */
  9837. int getNumberOfChildFiles (int whatToLookFor,
  9838. const String& wildCardPattern = "*") const;
  9839. /** Returns true if this file is a directory that contains one or more subdirectories.
  9840. @see isDirectory, findChildFiles
  9841. */
  9842. bool containsSubDirectories() const;
  9843. /** Creates a stream to read from this file.
  9844. @returns a stream that will read from this file (initially positioned at the
  9845. start of the file), or 0 if the file can't be opened for some reason
  9846. @see createOutputStream, loadFileAsData
  9847. */
  9848. FileInputStream* createInputStream() const;
  9849. /** Creates a stream to write to this file.
  9850. If the file exists, the stream that is returned will be positioned ready for
  9851. writing at the end of the file, so you might want to use deleteFile() first
  9852. to write to an empty file.
  9853. @returns a stream that will write to this file (initially positioned at the
  9854. end of the file), or 0 if the file can't be opened for some reason
  9855. @see createInputStream, appendData, appendText
  9856. */
  9857. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9858. /** Loads a file's contents into memory as a block of binary data.
  9859. Of course, trying to load a very large file into memory will blow up, so
  9860. it's better to check first.
  9861. @param result the data block to which the file's contents should be appended - note
  9862. that if the memory block might already contain some data, you
  9863. might want to clear it first
  9864. @returns true if the file could all be read into memory
  9865. */
  9866. bool loadFileAsData (MemoryBlock& result) const;
  9867. /** Reads a file into memory as a string.
  9868. Attempts to load the entire file as a zero-terminated string.
  9869. This makes use of InputStream::readEntireStreamAsString, which should
  9870. automatically cope with unicode/acsii file formats.
  9871. */
  9872. const String loadFileAsString() const;
  9873. /** Appends a block of binary data to the end of the file.
  9874. This will try to write the given buffer to the end of the file.
  9875. @returns false if it can't write to the file for some reason
  9876. */
  9877. bool appendData (const void* dataToAppend,
  9878. int numberOfBytes) const;
  9879. /** Replaces this file's contents with a given block of data.
  9880. This will delete the file and replace it with the given data.
  9881. A nice feature of this method is that it's safe - instead of deleting
  9882. the file first and then re-writing it, it creates a new temporary file,
  9883. writes the data to that, and then moves the new file to replace the existing
  9884. file. This means that if the power gets pulled out or something crashes,
  9885. you're a lot less likely to end up with a corrupted or unfinished file..
  9886. Returns true if the operation succeeds, or false if it fails.
  9887. @see appendText
  9888. */
  9889. bool replaceWithData (const void* dataToWrite,
  9890. int numberOfBytes) const;
  9891. /** Appends a string to the end of the file.
  9892. This will try to append a text string to the file, as either 16-bit unicode
  9893. or 8-bit characters in the default system encoding.
  9894. It can also write the 'ff fe' unicode header bytes before the text to indicate
  9895. the endianness of the file.
  9896. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  9897. @see replaceWithText
  9898. */
  9899. bool appendText (const String& textToAppend,
  9900. bool asUnicode = false,
  9901. bool writeUnicodeHeaderBytes = false) const;
  9902. /** Replaces this file's contents with a given text string.
  9903. This will delete the file and replace it with the given text.
  9904. A nice feature of this method is that it's safe - instead of deleting
  9905. the file first and then re-writing it, it creates a new temporary file,
  9906. writes the text to that, and then moves the new file to replace the existing
  9907. file. This means that if the power gets pulled out or something crashes,
  9908. you're a lot less likely to end up with an empty file..
  9909. For an explanation of the parameters here, see the appendText() method.
  9910. Returns true if the operation succeeds, or false if it fails.
  9911. @see appendText
  9912. */
  9913. bool replaceWithText (const String& textToWrite,
  9914. bool asUnicode = false,
  9915. bool writeUnicodeHeaderBytes = false) const;
  9916. /** Attempts to scan the contents of this file and compare it to another file, returning
  9917. true if this is possible and they match byte-for-byte.
  9918. */
  9919. bool hasIdenticalContentTo (const File& other) const;
  9920. /** Creates a set of files to represent each file root.
  9921. e.g. on Windows this will create files for "c:\", "d:\" etc according
  9922. to which ones are available. On the Mac/Linux, this will probably
  9923. just add a single entry for "/".
  9924. */
  9925. static void findFileSystemRoots (Array<File>& results);
  9926. /** Finds the name of the drive on which this file lives.
  9927. @returns the volume label of the drive, or an empty string if this isn't possible
  9928. */
  9929. const String getVolumeLabel() const;
  9930. /** Returns the serial number of the volume on which this file lives.
  9931. @returns the serial number, or zero if there's a problem doing this
  9932. */
  9933. int getVolumeSerialNumber() const;
  9934. /** Returns the number of bytes free on the drive that this file lives on.
  9935. @returns the number of bytes free, or 0 if there's a problem finding this out
  9936. @see getVolumeTotalSize
  9937. */
  9938. int64 getBytesFreeOnVolume() const;
  9939. /** Returns the total size of the drive that contains this file.
  9940. @returns the total number of bytes that the volume can hold
  9941. @see getBytesFreeOnVolume
  9942. */
  9943. int64 getVolumeTotalSize() const;
  9944. /** Returns true if this file is on a CD or DVD drive. */
  9945. bool isOnCDRomDrive() const;
  9946. /** Returns true if this file is on a hard disk.
  9947. This will fail if it's a network drive, but will still be true for
  9948. removable hard-disks.
  9949. */
  9950. bool isOnHardDisk() const;
  9951. /** Returns true if this file is on a removable disk drive.
  9952. This might be a usb-drive, a CD-rom, or maybe a network drive.
  9953. */
  9954. bool isOnRemovableDrive() const;
  9955. /** Launches the file as a process.
  9956. - if the file is executable, this will run it.
  9957. - if it's a document of some kind, it will launch the document with its
  9958. default viewer application.
  9959. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  9960. @see revealToUser
  9961. */
  9962. bool startAsProcess (const String& parameters = String::empty) const;
  9963. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  9964. @see startAsProcess
  9965. */
  9966. void revealToUser() const;
  9967. /** A set of types of location that can be passed to the getSpecialLocation() method.
  9968. */
  9969. enum SpecialLocationType
  9970. {
  9971. /** The user's home folder. This is the same as using File ("~"). */
  9972. userHomeDirectory,
  9973. /** The user's default documents folder. On Windows, this might be the user's
  9974. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  9975. doesn't tend to have one of these, so it might just return their home folder.
  9976. */
  9977. userDocumentsDirectory,
  9978. /** The folder that contains the user's desktop objects. */
  9979. userDesktopDirectory,
  9980. /** The folder in which applications store their persistent user-specific settings.
  9981. On Windows, this might be "\Documents and Settings\username\Application Data".
  9982. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  9983. always create your own sub-folder to put them in, to avoid making a mess.
  9984. */
  9985. userApplicationDataDirectory,
  9986. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  9987. of the computer, rather than just the current user.
  9988. On the Mac it'll be "/Library", on Windows, it could be something like
  9989. "\Documents and Settings\All Users\Application Data".
  9990. Depending on the setup, this folder may be read-only.
  9991. */
  9992. commonApplicationDataDirectory,
  9993. /** The folder that should be used for temporary files.
  9994. Always delete them when you're finished, to keep the user's computer tidy!
  9995. */
  9996. tempDirectory,
  9997. /** Returns this application's executable file.
  9998. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9999. host app.
  10000. On the mac this will return the unix binary, not the package folder - see
  10001. currentApplicationFile for that.
  10002. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  10003. file link, invokedExecutableFile will return the name of the link.
  10004. */
  10005. currentExecutableFile,
  10006. /** Returns this application's location.
  10007. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10008. host app.
  10009. On the mac this will return the package folder (if it's in one), not the unix binary
  10010. that's inside it - compare with currentExecutableFile.
  10011. */
  10012. currentApplicationFile,
  10013. /** Returns the file that was invoked to launch this executable.
  10014. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  10015. will return the name of the link that was used, whereas currentExecutableFile will return
  10016. the actual location of the target executable.
  10017. */
  10018. invokedExecutableFile,
  10019. /** In a plugin, this will return the path of the host executable. */
  10020. hostApplicationPath,
  10021. /** The directory in which applications normally get installed.
  10022. So on windows, this would be something like "c:\program files", on the
  10023. Mac "/Applications", or "/usr" on linux.
  10024. */
  10025. globalApplicationsDirectory,
  10026. /** The most likely place where a user might store their music files.
  10027. */
  10028. userMusicDirectory,
  10029. /** The most likely place where a user might store their movie files.
  10030. */
  10031. userMoviesDirectory,
  10032. };
  10033. /** Finds the location of a special type of file or directory, such as a home folder or
  10034. documents folder.
  10035. @see SpecialLocationType
  10036. */
  10037. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  10038. /** Returns a temporary file in the system's temp directory.
  10039. This will try to return the name of a non-existent temp file.
  10040. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  10041. */
  10042. static const File createTempFile (const String& fileNameEnding);
  10043. /** Returns the current working directory.
  10044. @see setAsCurrentWorkingDirectory
  10045. */
  10046. static const File getCurrentWorkingDirectory();
  10047. /** Sets the current working directory to be this file.
  10048. For this to work the file must point to a valid directory.
  10049. @returns true if the current directory has been changed.
  10050. @see getCurrentWorkingDirectory
  10051. */
  10052. bool setAsCurrentWorkingDirectory() const;
  10053. /** The system-specific file separator character.
  10054. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10055. */
  10056. static const juce_wchar separator;
  10057. /** The system-specific file separator character, as a string.
  10058. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10059. */
  10060. static const String separatorString;
  10061. /** Removes illegal characters from a filename.
  10062. This will return a copy of the given string after removing characters
  10063. that are not allowed in a legal filename, and possibly shortening the
  10064. string if it's too long.
  10065. Because this will remove slashes, don't use it on an absolute pathname.
  10066. @see createLegalPathName
  10067. */
  10068. static const String createLegalFileName (const String& fileNameToFix);
  10069. /** Removes illegal characters from a pathname.
  10070. Similar to createLegalFileName(), but this won't remove slashes, so can
  10071. be used on a complete pathname.
  10072. @see createLegalFileName
  10073. */
  10074. static const String createLegalPathName (const String& pathNameToFix);
  10075. /** Indicates whether filenames are case-sensitive on the current operating system.
  10076. */
  10077. static bool areFileNamesCaseSensitive();
  10078. /** Returns true if the string seems to be a fully-specified absolute path.
  10079. */
  10080. static bool isAbsolutePath (const String& path);
  10081. /** Creates a file that simply contains this string, without doing the sanity-checking
  10082. that the normal constructors do.
  10083. Best to avoid this unless you really know what you're doing.
  10084. */
  10085. static const File createFileWithoutCheckingPath (const String& path);
  10086. /** Adds a separator character to the end of a path if it doesn't already have one. */
  10087. static const String addTrailingSeparator (const String& path);
  10088. private:
  10089. String fullPath;
  10090. // internal way of contructing a file without checking the path
  10091. friend class DirectoryIterator;
  10092. File (const String&, int);
  10093. const String getPathUpToLastSlash() const;
  10094. void createDirectoryInternal (const String& fileName) const;
  10095. bool copyInternal (const File& dest) const;
  10096. bool moveInternal (const File& dest) const;
  10097. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  10098. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  10099. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  10100. static const String parseAbsolutePath (const String& path);
  10101. JUCE_LEAK_DETECTOR (File);
  10102. };
  10103. #endif // __JUCE_FILE_JUCEHEADER__
  10104. /*** End of inlined file: juce_File.h ***/
  10105. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  10106. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10107. will be the name of a pointer to each child element.
  10108. E.g. @code
  10109. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10110. forEachXmlChildElement (*myParentXml, child)
  10111. {
  10112. if (child->hasTagName ("FOO"))
  10113. doSomethingWithXmlElement (child);
  10114. }
  10115. @endcode
  10116. @see forEachXmlChildElementWithTagName
  10117. */
  10118. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  10119. \
  10120. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  10121. childElementVariableName != 0; \
  10122. childElementVariableName = childElementVariableName->getNextElement())
  10123. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  10124. which have a specified tag.
  10125. This does the same job as the forEachXmlChildElement macro, but only for those
  10126. elements that have a particular tag name.
  10127. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10128. will be the name of a pointer to each child element. The requiredTagName is the
  10129. tag name to match.
  10130. E.g. @code
  10131. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10132. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  10133. {
  10134. // the child object is now guaranteed to be a <MYTAG> element..
  10135. doSomethingWithMYTAGElement (child);
  10136. }
  10137. @endcode
  10138. @see forEachXmlChildElement
  10139. */
  10140. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  10141. \
  10142. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  10143. childElementVariableName != 0; \
  10144. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  10145. /** Used to build a tree of elements representing an XML document.
  10146. An XML document can be parsed into a tree of XmlElements, each of which
  10147. represents an XML tag structure, and which may itself contain other
  10148. nested elements.
  10149. An XmlElement can also be converted back into a text document, and has
  10150. lots of useful methods for manipulating its attributes and sub-elements,
  10151. so XmlElements can actually be used as a handy general-purpose data
  10152. structure.
  10153. Here's an example of parsing some elements: @code
  10154. // check we're looking at the right kind of document..
  10155. if (myElement->hasTagName ("ANIMALS"))
  10156. {
  10157. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  10158. forEachXmlChildElement (*myElement, e)
  10159. {
  10160. if (e->hasTagName ("GIRAFFE"))
  10161. {
  10162. // found a giraffe, so use some of its attributes..
  10163. String giraffeName = e->getStringAttribute ("name");
  10164. int giraffeAge = e->getIntAttribute ("age");
  10165. bool isFriendly = e->getBoolAttribute ("friendly");
  10166. }
  10167. }
  10168. }
  10169. @endcode
  10170. And here's an example of how to create an XML document from scratch: @code
  10171. // create an outer node called "ANIMALS"
  10172. XmlElement animalsList ("ANIMALS");
  10173. for (int i = 0; i < numAnimals; ++i)
  10174. {
  10175. // create an inner element..
  10176. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  10177. giraffe->setAttribute ("name", "nigel");
  10178. giraffe->setAttribute ("age", 10);
  10179. giraffe->setAttribute ("friendly", true);
  10180. // ..and add our new element to the parent node
  10181. animalsList.addChildElement (giraffe);
  10182. }
  10183. // now we can turn the whole thing into a text document..
  10184. String myXmlDoc = animalsList.createDocument (String::empty);
  10185. @endcode
  10186. @see XmlDocument
  10187. */
  10188. class JUCE_API XmlElement
  10189. {
  10190. public:
  10191. /** Creates an XmlElement with this tag name. */
  10192. explicit XmlElement (const String& tagName) noexcept;
  10193. /** Creates a (deep) copy of another element. */
  10194. XmlElement (const XmlElement& other);
  10195. /** Creates a (deep) copy of another element. */
  10196. XmlElement& operator= (const XmlElement& other);
  10197. /** Deleting an XmlElement will also delete all its child elements. */
  10198. ~XmlElement() noexcept;
  10199. /** Compares two XmlElements to see if they contain the same text and attiributes.
  10200. The elements are only considered equivalent if they contain the same attiributes
  10201. with the same values, and have the same sub-nodes.
  10202. @param other the other element to compare to
  10203. @param ignoreOrderOfAttributes if true, this means that two elements with the
  10204. same attributes in a different order will be
  10205. considered the same; if false, the attributes must
  10206. be in the same order as well
  10207. */
  10208. bool isEquivalentTo (const XmlElement* other,
  10209. bool ignoreOrderOfAttributes) const noexcept;
  10210. /** Returns an XML text document that represents this element.
  10211. The string returned can be parsed to recreate the same XmlElement that
  10212. was used to create it.
  10213. @param dtdToUse the DTD to add to the document
  10214. @param allOnOneLine if true, this means that the document will not contain any
  10215. linefeeds, so it'll be smaller but not very easy to read.
  10216. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10217. document
  10218. @param encodingType the character encoding format string to put into the xml
  10219. header
  10220. @param lineWrapLength the line length that will be used before items get placed on
  10221. a new line. This isn't an absolute maximum length, it just
  10222. determines how lists of attributes get broken up
  10223. @see writeToStream, writeToFile
  10224. */
  10225. const String createDocument (const String& dtdToUse,
  10226. bool allOnOneLine = false,
  10227. bool includeXmlHeader = true,
  10228. const String& encodingType = "UTF-8",
  10229. int lineWrapLength = 60) const;
  10230. /** Writes the document to a stream as UTF-8.
  10231. @param output the stream to write to
  10232. @param dtdToUse the DTD to add to the document
  10233. @param allOnOneLine if true, this means that the document will not contain any
  10234. linefeeds, so it'll be smaller but not very easy to read.
  10235. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10236. document
  10237. @param encodingType the character encoding format string to put into the xml
  10238. header
  10239. @param lineWrapLength the line length that will be used before items get placed on
  10240. a new line. This isn't an absolute maximum length, it just
  10241. determines how lists of attributes get broken up
  10242. @see writeToFile, createDocument
  10243. */
  10244. void writeToStream (OutputStream& output,
  10245. const String& dtdToUse,
  10246. bool allOnOneLine = false,
  10247. bool includeXmlHeader = true,
  10248. const String& encodingType = "UTF-8",
  10249. int lineWrapLength = 60) const;
  10250. /** Writes the element to a file as an XML document.
  10251. To improve safety in case something goes wrong while writing the file, this
  10252. will actually write the document to a new temporary file in the same
  10253. directory as the destination file, and if this succeeds, it will rename this
  10254. new file as the destination file (overwriting any existing file that was there).
  10255. @param destinationFile the file to write to. If this already exists, it will be
  10256. overwritten.
  10257. @param dtdToUse the DTD to add to the document
  10258. @param encodingType the character encoding format string to put into the xml
  10259. header
  10260. @param lineWrapLength the line length that will be used before items get placed on
  10261. a new line. This isn't an absolute maximum length, it just
  10262. determines how lists of attributes get broken up
  10263. @returns true if the file is written successfully; false if something goes wrong
  10264. in the process
  10265. @see createDocument
  10266. */
  10267. bool writeToFile (const File& destinationFile,
  10268. const String& dtdToUse,
  10269. const String& encodingType = "UTF-8",
  10270. int lineWrapLength = 60) const;
  10271. /** Returns this element's tag type name.
  10272. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  10273. "MOOSE".
  10274. @see hasTagName
  10275. */
  10276. inline const String& getTagName() const noexcept { return tagName; }
  10277. /** Tests whether this element has a particular tag name.
  10278. @param possibleTagName the tag name you're comparing it with
  10279. @see getTagName
  10280. */
  10281. bool hasTagName (const String& possibleTagName) const noexcept;
  10282. /** Returns the number of XML attributes this element contains.
  10283. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  10284. return 2.
  10285. */
  10286. int getNumAttributes() const noexcept;
  10287. /** Returns the name of one of the elements attributes.
  10288. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10289. getAttributeName(1) would return "antlers".
  10290. @see getAttributeValue, getStringAttribute
  10291. */
  10292. const String& getAttributeName (int attributeIndex) const noexcept;
  10293. /** Returns the value of one of the elements attributes.
  10294. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10295. getAttributeName(1) would return "2".
  10296. @see getAttributeName, getStringAttribute
  10297. */
  10298. const String& getAttributeValue (int attributeIndex) const noexcept;
  10299. // Attribute-handling methods..
  10300. /** Checks whether the element contains an attribute with a certain name. */
  10301. bool hasAttribute (const String& attributeName) const noexcept;
  10302. /** Returns the value of a named attribute.
  10303. @param attributeName the name of the attribute to look up
  10304. */
  10305. const String& getStringAttribute (const String& attributeName) const noexcept;
  10306. /** Returns the value of a named attribute.
  10307. @param attributeName the name of the attribute to look up
  10308. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10309. with this name
  10310. */
  10311. const String getStringAttribute (const String& attributeName,
  10312. const String& defaultReturnValue) const;
  10313. /** Compares the value of a named attribute with a value passed-in.
  10314. @param attributeName the name of the attribute to look up
  10315. @param stringToCompareAgainst the value to compare it with
  10316. @param ignoreCase whether the comparison should be case-insensitive
  10317. @returns true if the value of the attribute is the same as the string passed-in;
  10318. false if it's different (or if no such attribute exists)
  10319. */
  10320. bool compareAttribute (const String& attributeName,
  10321. const String& stringToCompareAgainst,
  10322. bool ignoreCase = false) const noexcept;
  10323. /** Returns the value of a named attribute as an integer.
  10324. This will try to find the attribute and convert it to an integer (using
  10325. the String::getIntValue() method).
  10326. @param attributeName the name of the attribute to look up
  10327. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10328. with this name
  10329. @see setAttribute
  10330. */
  10331. int getIntAttribute (const String& attributeName,
  10332. int defaultReturnValue = 0) const;
  10333. /** Returns the value of a named attribute as floating-point.
  10334. This will try to find the attribute and convert it to an integer (using
  10335. the String::getDoubleValue() method).
  10336. @param attributeName the name of the attribute to look up
  10337. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10338. with this name
  10339. @see setAttribute
  10340. */
  10341. double getDoubleAttribute (const String& attributeName,
  10342. double defaultReturnValue = 0.0) const;
  10343. /** Returns the value of a named attribute as a boolean.
  10344. This will try to find the attribute and interpret it as a boolean. To do this,
  10345. it'll return true if the value is "1", "true", "y", etc, or false for other
  10346. values.
  10347. @param attributeName the name of the attribute to look up
  10348. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10349. with this name
  10350. */
  10351. bool getBoolAttribute (const String& attributeName,
  10352. bool defaultReturnValue = false) const;
  10353. /** Adds a named attribute to the element.
  10354. If the element already contains an attribute with this name, it's value will
  10355. be updated to the new value. If there's no such attribute yet, a new one will
  10356. be added.
  10357. Note that there are other setAttribute() methods that take integers,
  10358. doubles, etc. to make it easy to store numbers.
  10359. @param attributeName the name of the attribute to set
  10360. @param newValue the value to set it to
  10361. @see removeAttribute
  10362. */
  10363. void setAttribute (const String& attributeName,
  10364. const String& newValue);
  10365. /** Adds a named attribute to the element, setting it to an integer value.
  10366. If the element already contains an attribute with this name, it's value will
  10367. be updated to the new value. If there's no such attribute yet, a new one will
  10368. be added.
  10369. Note that there are other setAttribute() methods that take integers,
  10370. doubles, etc. to make it easy to store numbers.
  10371. @param attributeName the name of the attribute to set
  10372. @param newValue the value to set it to
  10373. */
  10374. void setAttribute (const String& attributeName,
  10375. int newValue);
  10376. /** Adds a named attribute to the element, setting it to a floating-point value.
  10377. If the element already contains an attribute with this name, it's value will
  10378. be updated to the new value. If there's no such attribute yet, a new one will
  10379. be added.
  10380. Note that there are other setAttribute() methods that take integers,
  10381. doubles, etc. to make it easy to store numbers.
  10382. @param attributeName the name of the attribute to set
  10383. @param newValue the value to set it to
  10384. */
  10385. void setAttribute (const String& attributeName,
  10386. double newValue);
  10387. /** Removes a named attribute from the element.
  10388. @param attributeName the name of the attribute to remove
  10389. @see removeAllAttributes
  10390. */
  10391. void removeAttribute (const String& attributeName) noexcept;
  10392. /** Removes all attributes from this element.
  10393. */
  10394. void removeAllAttributes() noexcept;
  10395. // Child element methods..
  10396. /** Returns the first of this element's sub-elements.
  10397. see getNextElement() for an example of how to iterate the sub-elements.
  10398. @see forEachXmlChildElement
  10399. */
  10400. XmlElement* getFirstChildElement() const noexcept { return firstChildElement; }
  10401. /** Returns the next of this element's siblings.
  10402. This can be used for iterating an element's sub-elements, e.g.
  10403. @code
  10404. XmlElement* child = myXmlDocument->getFirstChildElement();
  10405. while (child != nullptr)
  10406. {
  10407. ...do stuff with this child..
  10408. child = child->getNextElement();
  10409. }
  10410. @endcode
  10411. Note that when iterating the child elements, some of them might be
  10412. text elements as well as XML tags - use isTextElement() to work this
  10413. out.
  10414. Also, it's much easier and neater to use this method indirectly via the
  10415. forEachXmlChildElement macro.
  10416. @returns the sibling element that follows this one, or zero if this is the last
  10417. element in its parent
  10418. @see getNextElement, isTextElement, forEachXmlChildElement
  10419. */
  10420. inline XmlElement* getNextElement() const noexcept { return nextListItem; }
  10421. /** Returns the next of this element's siblings which has the specified tag
  10422. name.
  10423. This is like getNextElement(), but will scan through the list until it
  10424. finds an element with the given tag name.
  10425. @see getNextElement, forEachXmlChildElementWithTagName
  10426. */
  10427. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  10428. /** Returns the number of sub-elements in this element.
  10429. @see getChildElement
  10430. */
  10431. int getNumChildElements() const noexcept;
  10432. /** Returns the sub-element at a certain index.
  10433. It's not very efficient to iterate the sub-elements by index - see
  10434. getNextElement() for an example of how best to iterate.
  10435. @returns the n'th child of this element, or 0 if the index is out-of-range
  10436. @see getNextElement, isTextElement, getChildByName
  10437. */
  10438. XmlElement* getChildElement (int index) const noexcept;
  10439. /** Returns the first sub-element with a given tag-name.
  10440. @param tagNameToLookFor the tag name of the element you want to find
  10441. @returns the first element with this tag name, or 0 if none is found
  10442. @see getNextElement, isTextElement, getChildElement
  10443. */
  10444. XmlElement* getChildByName (const String& tagNameToLookFor) const noexcept;
  10445. /** Appends an element to this element's list of children.
  10446. Child elements are deleted automatically when their parent is deleted, so
  10447. make sure the object that you pass in will not be deleted by anything else,
  10448. and make sure it's not already the child of another element.
  10449. @see getFirstChildElement, getNextElement, getNumChildElements,
  10450. getChildElement, removeChildElement
  10451. */
  10452. void addChildElement (XmlElement* newChildElement) noexcept;
  10453. /** Inserts an element into this element's list of children.
  10454. Child elements are deleted automatically when their parent is deleted, so
  10455. make sure the object that you pass in will not be deleted by anything else,
  10456. and make sure it's not already the child of another element.
  10457. @param newChildNode the element to add
  10458. @param indexToInsertAt the index at which to insert the new element - if this is
  10459. below zero, it will be added to the end of the list
  10460. @see addChildElement, insertChildElement
  10461. */
  10462. void insertChildElement (XmlElement* newChildNode,
  10463. int indexToInsertAt) noexcept;
  10464. /** Creates a new element with the given name and returns it, after adding it
  10465. as a child element.
  10466. This is a handy method that means that instead of writing this:
  10467. @code
  10468. XmlElement* newElement = new XmlElement ("foobar");
  10469. myParentElement->addChildElement (newElement);
  10470. @endcode
  10471. ..you could just write this:
  10472. @code
  10473. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  10474. @endcode
  10475. */
  10476. XmlElement* createNewChildElement (const String& tagName);
  10477. /** Replaces one of this element's children with another node.
  10478. If the current element passed-in isn't actually a child of this element,
  10479. this will return false and the new one won't be added. Otherwise, the
  10480. existing element will be deleted, replaced with the new one, and it
  10481. will return true.
  10482. */
  10483. bool replaceChildElement (XmlElement* currentChildElement,
  10484. XmlElement* newChildNode) noexcept;
  10485. /** Removes a child element.
  10486. @param childToRemove the child to look for and remove
  10487. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  10488. just remove it
  10489. */
  10490. void removeChildElement (XmlElement* childToRemove,
  10491. bool shouldDeleteTheChild) noexcept;
  10492. /** Deletes all the child elements in the element.
  10493. @see removeChildElement, deleteAllChildElementsWithTagName
  10494. */
  10495. void deleteAllChildElements() noexcept;
  10496. /** Deletes all the child elements with a given tag name.
  10497. @see removeChildElement
  10498. */
  10499. void deleteAllChildElementsWithTagName (const String& tagName) noexcept;
  10500. /** Returns true if the given element is a child of this one. */
  10501. bool containsChildElement (const XmlElement* possibleChild) const noexcept;
  10502. /** Recursively searches all sub-elements to find one that contains the specified
  10503. child element.
  10504. */
  10505. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) noexcept;
  10506. /** Sorts the child elements using a comparator.
  10507. This will use a comparator object to sort the elements into order. The object
  10508. passed must have a method of the form:
  10509. @code
  10510. int compareElements (const XmlElement* first, const XmlElement* second);
  10511. @endcode
  10512. ..and this method must return:
  10513. - a value of < 0 if the first comes before the second
  10514. - a value of 0 if the two objects are equivalent
  10515. - a value of > 0 if the second comes before the first
  10516. To improve performance, the compareElements() method can be declared as static or const.
  10517. @param comparator the comparator to use for comparing elements.
  10518. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  10519. says are equivalent will be kept in the order in which they
  10520. currently appear in the array. This is slower to perform, but
  10521. may be important in some cases. If it's false, a faster algorithm
  10522. is used, but equivalent elements may be rearranged.
  10523. */
  10524. template <class ElementComparator>
  10525. void sortChildElements (ElementComparator& comparator,
  10526. bool retainOrderOfEquivalentItems = false)
  10527. {
  10528. const int num = getNumChildElements();
  10529. if (num > 1)
  10530. {
  10531. HeapBlock <XmlElement*> elems (num);
  10532. getChildElementsAsArray (elems);
  10533. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  10534. reorderChildElements (elems, num);
  10535. }
  10536. }
  10537. /** Returns true if this element is a section of text.
  10538. Elements can either be an XML tag element or a secton of text, so this
  10539. is used to find out what kind of element this one is.
  10540. @see getAllText, addTextElement, deleteAllTextElements
  10541. */
  10542. bool isTextElement() const noexcept;
  10543. /** Returns the text for a text element.
  10544. Note that if you have an element like this:
  10545. @code<xyz>hello</xyz>@endcode
  10546. then calling getText on the "xyz" element won't return "hello", because that is
  10547. actually stored in a special text sub-element inside the xyz element. To get the
  10548. "hello" string, you could either call getText on the (unnamed) sub-element, or
  10549. use getAllSubText() to do this automatically.
  10550. Note that leading and trailing whitespace will be included in the string - to remove
  10551. if, just call String::trim() on the result.
  10552. @see isTextElement, getAllSubText, getChildElementAllSubText
  10553. */
  10554. const String& getText() const noexcept;
  10555. /** Sets the text in a text element.
  10556. Note that this is only a valid call if this element is a text element. If it's
  10557. not, then no action will be performed. If you're trying to add text inside a normal
  10558. element, you probably want to use addTextElement() instead.
  10559. */
  10560. void setText (const String& newText);
  10561. /** Returns all the text from this element's child nodes.
  10562. This iterates all the child elements and when it finds text elements,
  10563. it concatenates their text into a big string which it returns.
  10564. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  10565. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  10566. Note that leading and trailing whitespace will be included in the string - to remove
  10567. if, just call String::trim() on the result.
  10568. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  10569. */
  10570. const String getAllSubText() const;
  10571. /** Returns all the sub-text of a named child element.
  10572. If there is a child element with the given tag name, this will return
  10573. all of its sub-text (by calling getAllSubText() on it). If there is
  10574. no such child element, this will return the default string passed-in.
  10575. @see getAllSubText
  10576. */
  10577. const String getChildElementAllSubText (const String& childTagName,
  10578. const String& defaultReturnValue) const;
  10579. /** Appends a section of text to this element.
  10580. @see isTextElement, getText, getAllSubText
  10581. */
  10582. void addTextElement (const String& text);
  10583. /** Removes all the text elements from this element.
  10584. @see isTextElement, getText, getAllSubText, addTextElement
  10585. */
  10586. void deleteAllTextElements() noexcept;
  10587. /** Creates a text element that can be added to a parent element.
  10588. */
  10589. static XmlElement* createTextElement (const String& text);
  10590. private:
  10591. struct XmlAttributeNode
  10592. {
  10593. XmlAttributeNode (const XmlAttributeNode& other) noexcept;
  10594. XmlAttributeNode (const String& name, const String& value) noexcept;
  10595. LinkedListPointer<XmlAttributeNode> nextListItem;
  10596. String name, value;
  10597. bool hasName (const String& name) const noexcept;
  10598. private:
  10599. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10600. };
  10601. friend class XmlDocument;
  10602. friend class LinkedListPointer<XmlAttributeNode>;
  10603. friend class LinkedListPointer <XmlElement>;
  10604. friend class LinkedListPointer <XmlElement>::Appender;
  10605. LinkedListPointer <XmlElement> nextListItem;
  10606. LinkedListPointer <XmlElement> firstChildElement;
  10607. LinkedListPointer <XmlAttributeNode> attributes;
  10608. String tagName;
  10609. XmlElement (int) noexcept;
  10610. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10611. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10612. void getChildElementsAsArray (XmlElement**) const noexcept;
  10613. void reorderChildElements (XmlElement**, int) noexcept;
  10614. JUCE_LEAK_DETECTOR (XmlElement);
  10615. };
  10616. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10617. /*** End of inlined file: juce_XmlElement.h ***/
  10618. /**
  10619. A set of named property values, which can be strings, integers, floating point, etc.
  10620. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10621. to load and save types other than strings.
  10622. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10623. messages and saves/loads the list from a file.
  10624. */
  10625. class JUCE_API PropertySet
  10626. {
  10627. public:
  10628. /** Creates an empty PropertySet.
  10629. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10630. case-insensitive way
  10631. */
  10632. PropertySet (bool ignoreCaseOfKeyNames = false);
  10633. /** Creates a copy of another PropertySet.
  10634. */
  10635. PropertySet (const PropertySet& other);
  10636. /** Copies another PropertySet over this one.
  10637. */
  10638. PropertySet& operator= (const PropertySet& other);
  10639. /** Destructor. */
  10640. virtual ~PropertySet();
  10641. /** Returns one of the properties as a string.
  10642. If the value isn't found in this set, then this will look for it in a fallback
  10643. property set (if you've specified one with the setFallbackPropertySet() method),
  10644. and if it can't find one there, it'll return the default value passed-in.
  10645. @param keyName the name of the property to retrieve
  10646. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10647. */
  10648. const String getValue (const String& keyName,
  10649. const String& defaultReturnValue = String::empty) const noexcept;
  10650. /** Returns one of the properties as an integer.
  10651. If the value isn't found in this set, then this will look for it in a fallback
  10652. property set (if you've specified one with the setFallbackPropertySet() method),
  10653. and if it can't find one there, it'll return the default value passed-in.
  10654. @param keyName the name of the property to retrieve
  10655. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10656. */
  10657. int getIntValue (const String& keyName,
  10658. const int defaultReturnValue = 0) const noexcept;
  10659. /** Returns one of the properties as an double.
  10660. If the value isn't found in this set, then this will look for it in a fallback
  10661. property set (if you've specified one with the setFallbackPropertySet() method),
  10662. and if it can't find one there, it'll return the default value passed-in.
  10663. @param keyName the name of the property to retrieve
  10664. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10665. */
  10666. double getDoubleValue (const String& keyName,
  10667. const double defaultReturnValue = 0.0) const noexcept;
  10668. /** Returns one of the properties as an boolean.
  10669. The result will be true if the string found for this key name can be parsed as a non-zero
  10670. integer.
  10671. If the value isn't found in this set, then this will look for it in a fallback
  10672. property set (if you've specified one with the setFallbackPropertySet() method),
  10673. and if it can't find one there, it'll return the default value passed-in.
  10674. @param keyName the name of the property to retrieve
  10675. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10676. */
  10677. bool getBoolValue (const String& keyName,
  10678. const bool defaultReturnValue = false) const noexcept;
  10679. /** Returns one of the properties as an XML element.
  10680. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10681. key isn't found, or if the entry contains an string that isn't valid XML.
  10682. If the value isn't found in this set, then this will look for it in a fallback
  10683. property set (if you've specified one with the setFallbackPropertySet() method),
  10684. and if it can't find one there, it'll return the default value passed-in.
  10685. @param keyName the name of the property to retrieve
  10686. */
  10687. XmlElement* getXmlValue (const String& keyName) const;
  10688. /** Sets a named property.
  10689. @param keyName the name of the property to set. (This mustn't be an empty string)
  10690. @param value the new value to set it to
  10691. */
  10692. void setValue (const String& keyName, const var& value);
  10693. /** Sets a named property to an XML element.
  10694. @param keyName the name of the property to set. (This mustn't be an empty string)
  10695. @param xml the new element to set it to. If this is zero, the value will be set to
  10696. an empty string
  10697. @see getXmlValue
  10698. */
  10699. void setValue (const String& keyName, const XmlElement* xml);
  10700. /** Deletes a property.
  10701. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10702. */
  10703. void removeValue (const String& keyName);
  10704. /** Returns true if the properies include the given key. */
  10705. bool containsKey (const String& keyName) const noexcept;
  10706. /** Removes all values. */
  10707. void clear();
  10708. /** Returns the keys/value pair array containing all the properties. */
  10709. StringPairArray& getAllProperties() noexcept { return properties; }
  10710. /** Returns the lock used when reading or writing to this set */
  10711. const CriticalSection& getLock() const noexcept { return lock; }
  10712. /** Returns an XML element which encapsulates all the items in this property set.
  10713. The string parameter is the tag name that should be used for the node.
  10714. @see restoreFromXml
  10715. */
  10716. XmlElement* createXml (const String& nodeName) const;
  10717. /** Reloads a set of properties that were previously stored as XML.
  10718. The node passed in must have been created by the createXml() method.
  10719. @see createXml
  10720. */
  10721. void restoreFromXml (const XmlElement& xml);
  10722. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10723. set in this one.
  10724. If you set this up to be a pointer to a second property set, then whenever one
  10725. of the getValue() methods fails to find an entry in this set, it will look up that
  10726. value in the fallback set, and if it finds it, it will return that.
  10727. Make sure that you don't delete the fallback set while it's still being used by
  10728. another set! To remove the fallback set, just call this method with a null pointer.
  10729. @see getFallbackPropertySet
  10730. */
  10731. void setFallbackPropertySet (PropertySet* fallbackProperties) noexcept;
  10732. /** Returns the fallback property set.
  10733. @see setFallbackPropertySet
  10734. */
  10735. PropertySet* getFallbackPropertySet() const noexcept { return fallbackProperties; }
  10736. protected:
  10737. /** Subclasses can override this to be told when one of the properies has been changed. */
  10738. virtual void propertyChanged();
  10739. private:
  10740. StringPairArray properties;
  10741. PropertySet* fallbackProperties;
  10742. CriticalSection lock;
  10743. bool ignoreCaseOfKeys;
  10744. JUCE_LEAK_DETECTOR (PropertySet);
  10745. };
  10746. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10747. /*** End of inlined file: juce_PropertySet.h ***/
  10748. #endif
  10749. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10750. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10751. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10752. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10753. /**
  10754. Holds a list of objects derived from ReferenceCountedObject.
  10755. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10756. and takes care of incrementing and decrementing their ref counts when they
  10757. are added and removed from the array.
  10758. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10759. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10760. @see Array, OwnedArray, StringArray
  10761. */
  10762. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10763. class ReferenceCountedArray
  10764. {
  10765. public:
  10766. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10767. /** Creates an empty array.
  10768. @see ReferenceCountedObject, Array, OwnedArray
  10769. */
  10770. ReferenceCountedArray() noexcept
  10771. : numUsed (0)
  10772. {
  10773. }
  10774. /** Creates a copy of another array */
  10775. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10776. {
  10777. const ScopedLockType lock (other.getLock());
  10778. numUsed = other.numUsed;
  10779. data.setAllocatedSize (numUsed);
  10780. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10781. for (int i = numUsed; --i >= 0;)
  10782. if (data.elements[i] != nullptr)
  10783. data.elements[i]->incReferenceCount();
  10784. }
  10785. /** Copies another array into this one.
  10786. Any existing objects in this array will first be released.
  10787. */
  10788. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10789. {
  10790. if (this != &other)
  10791. {
  10792. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10793. swapWithArray (otherCopy);
  10794. }
  10795. return *this;
  10796. }
  10797. /** Destructor.
  10798. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10799. */
  10800. ~ReferenceCountedArray()
  10801. {
  10802. clear();
  10803. }
  10804. /** Removes all objects from the array.
  10805. Any objects in the array that are not referenced from elsewhere will be deleted.
  10806. */
  10807. void clear()
  10808. {
  10809. const ScopedLockType lock (getLock());
  10810. while (numUsed > 0)
  10811. if (data.elements [--numUsed] != nullptr)
  10812. data.elements [numUsed]->decReferenceCount();
  10813. jassert (numUsed == 0);
  10814. data.setAllocatedSize (0);
  10815. }
  10816. /** Returns the current number of objects in the array. */
  10817. inline int size() const noexcept
  10818. {
  10819. return numUsed;
  10820. }
  10821. /** Returns a pointer to the object at this index in the array.
  10822. If the index is out-of-range, this will return a null pointer, (and
  10823. it could be null anyway, because it's ok for the array to hold null
  10824. pointers as well as objects).
  10825. @see getUnchecked
  10826. */
  10827. inline const ObjectClassPtr operator[] (const int index) const noexcept
  10828. {
  10829. const ScopedLockType lock (getLock());
  10830. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10831. : static_cast <ObjectClass*> (nullptr);
  10832. }
  10833. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10834. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10835. it can be used when you're sure the index if always going to be legal.
  10836. */
  10837. inline const ObjectClassPtr getUnchecked (const int index) const noexcept
  10838. {
  10839. const ScopedLockType lock (getLock());
  10840. jassert (isPositiveAndBelow (index, numUsed));
  10841. return data.elements [index];
  10842. }
  10843. /** Returns a pointer to the first object in the array.
  10844. This will return a null pointer if the array's empty.
  10845. @see getLast
  10846. */
  10847. inline const ObjectClassPtr getFirst() const noexcept
  10848. {
  10849. const ScopedLockType lock (getLock());
  10850. return numUsed > 0 ? data.elements [0]
  10851. : static_cast <ObjectClass*> (nullptr);
  10852. }
  10853. /** Returns a pointer to the last object in the array.
  10854. This will return a null pointer if the array's empty.
  10855. @see getFirst
  10856. */
  10857. inline const ObjectClassPtr getLast() const noexcept
  10858. {
  10859. const ScopedLockType lock (getLock());
  10860. return numUsed > 0 ? data.elements [numUsed - 1]
  10861. : static_cast <ObjectClass*> (nullptr);
  10862. }
  10863. /** Returns a pointer to the first element in the array.
  10864. This method is provided for compatibility with standard C++ iteration mechanisms.
  10865. */
  10866. inline ObjectClass** begin() const noexcept
  10867. {
  10868. return data.elements;
  10869. }
  10870. /** Returns a pointer to the element which follows the last element in the array.
  10871. This method is provided for compatibility with standard C++ iteration mechanisms.
  10872. */
  10873. inline ObjectClass** end() const noexcept
  10874. {
  10875. return data.elements + numUsed;
  10876. }
  10877. /** Finds the index of the first occurrence of an object in the array.
  10878. @param objectToLookFor the object to look for
  10879. @returns the index at which the object was found, or -1 if it's not found
  10880. */
  10881. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  10882. {
  10883. const ScopedLockType lock (getLock());
  10884. ObjectClass** e = data.elements.getData();
  10885. ObjectClass** const end = e + numUsed;
  10886. while (e != end)
  10887. {
  10888. if (objectToLookFor == *e)
  10889. return static_cast <int> (e - data.elements.getData());
  10890. ++e;
  10891. }
  10892. return -1;
  10893. }
  10894. /** Returns true if the array contains a specified object.
  10895. @param objectToLookFor the object to look for
  10896. @returns true if the object is in the array
  10897. */
  10898. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  10899. {
  10900. const ScopedLockType lock (getLock());
  10901. ObjectClass** e = data.elements.getData();
  10902. ObjectClass** const end = e + numUsed;
  10903. while (e != end)
  10904. {
  10905. if (objectToLookFor == *e)
  10906. return true;
  10907. ++e;
  10908. }
  10909. return false;
  10910. }
  10911. /** Appends a new object to the end of the array.
  10912. This will increase the new object's reference count.
  10913. @param newObject the new object to add to the array
  10914. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  10915. */
  10916. void add (ObjectClass* const newObject) noexcept
  10917. {
  10918. const ScopedLockType lock (getLock());
  10919. data.ensureAllocatedSize (numUsed + 1);
  10920. data.elements [numUsed++] = newObject;
  10921. if (newObject != nullptr)
  10922. newObject->incReferenceCount();
  10923. }
  10924. /** Inserts a new object into the array at the given index.
  10925. If the index is less than 0 or greater than the size of the array, the
  10926. element will be added to the end of the array.
  10927. Otherwise, it will be inserted into the array, moving all the later elements
  10928. along to make room.
  10929. This will increase the new object's reference count.
  10930. @param indexToInsertAt the index at which the new element should be inserted
  10931. @param newObject the new object to add to the array
  10932. @see add, addSorted, addIfNotAlreadyThere, set
  10933. */
  10934. void insert (int indexToInsertAt,
  10935. ObjectClass* const newObject) noexcept
  10936. {
  10937. if (indexToInsertAt >= 0)
  10938. {
  10939. const ScopedLockType lock (getLock());
  10940. if (indexToInsertAt > numUsed)
  10941. indexToInsertAt = numUsed;
  10942. data.ensureAllocatedSize (numUsed + 1);
  10943. ObjectClass** const e = data.elements + indexToInsertAt;
  10944. const int numToMove = numUsed - indexToInsertAt;
  10945. if (numToMove > 0)
  10946. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  10947. *e = newObject;
  10948. if (newObject != nullptr)
  10949. newObject->incReferenceCount();
  10950. ++numUsed;
  10951. }
  10952. else
  10953. {
  10954. add (newObject);
  10955. }
  10956. }
  10957. /** Appends a new object at the end of the array as long as the array doesn't
  10958. already contain it.
  10959. If the array already contains a matching object, nothing will be done.
  10960. @param newObject the new object to add to the array
  10961. */
  10962. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  10963. {
  10964. const ScopedLockType lock (getLock());
  10965. if (! contains (newObject))
  10966. add (newObject);
  10967. }
  10968. /** Replaces an object in the array with a different one.
  10969. If the index is less than zero, this method does nothing.
  10970. If the index is beyond the end of the array, the new object is added to the end of the array.
  10971. The object being added has its reference count increased, and if it's replacing
  10972. another object, then that one has its reference count decreased, and may be deleted.
  10973. @param indexToChange the index whose value you want to change
  10974. @param newObject the new value to set for this index.
  10975. @see add, insert, remove
  10976. */
  10977. void set (const int indexToChange,
  10978. ObjectClass* const newObject)
  10979. {
  10980. if (indexToChange >= 0)
  10981. {
  10982. const ScopedLockType lock (getLock());
  10983. if (newObject != nullptr)
  10984. newObject->incReferenceCount();
  10985. if (indexToChange < numUsed)
  10986. {
  10987. if (data.elements [indexToChange] != nullptr)
  10988. data.elements [indexToChange]->decReferenceCount();
  10989. data.elements [indexToChange] = newObject;
  10990. }
  10991. else
  10992. {
  10993. data.ensureAllocatedSize (numUsed + 1);
  10994. data.elements [numUsed++] = newObject;
  10995. }
  10996. }
  10997. }
  10998. /** Adds elements from another array to the end of this array.
  10999. @param arrayToAddFrom the array from which to copy the elements
  11000. @param startIndex the first element of the other array to start copying from
  11001. @param numElementsToAdd how many elements to add from the other array. If this
  11002. value is negative or greater than the number of available elements,
  11003. all available elements will be copied.
  11004. @see add
  11005. */
  11006. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  11007. int startIndex = 0,
  11008. int numElementsToAdd = -1) noexcept
  11009. {
  11010. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  11011. {
  11012. const ScopedLockType lock2 (getLock());
  11013. if (startIndex < 0)
  11014. {
  11015. jassertfalse;
  11016. startIndex = 0;
  11017. }
  11018. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  11019. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  11020. if (numElementsToAdd > 0)
  11021. {
  11022. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  11023. while (--numElementsToAdd >= 0)
  11024. add (arrayToAddFrom.getUnchecked (startIndex++));
  11025. }
  11026. }
  11027. }
  11028. /** Inserts a new object into the array assuming that the array is sorted.
  11029. This will use a comparator to find the position at which the new object
  11030. should go. If the array isn't sorted, the behaviour of this
  11031. method will be unpredictable.
  11032. @param comparator the comparator object to use to compare the elements - see the
  11033. sort() method for details about this object's form
  11034. @param newObject the new object to insert to the array
  11035. @returns the index at which the new object was added
  11036. @see add, sort
  11037. */
  11038. template <class ElementComparator>
  11039. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  11040. {
  11041. const ScopedLockType lock (getLock());
  11042. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11043. insert (index, newObject);
  11044. return index;
  11045. }
  11046. /** Inserts or replaces an object in the array, assuming it is sorted.
  11047. This is similar to addSorted, but if a matching element already exists, then it will be
  11048. replaced by the new one, rather than the new one being added as well.
  11049. */
  11050. template <class ElementComparator>
  11051. void addOrReplaceSorted (ElementComparator& comparator,
  11052. ObjectClass* newObject) noexcept
  11053. {
  11054. const ScopedLockType lock (getLock());
  11055. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11056. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  11057. set (index - 1, newObject); // replace an existing object that matches
  11058. else
  11059. insert (index, newObject); // no match, so insert the new one
  11060. }
  11061. /** Removes an object from the array.
  11062. This will remove the object at a given index and move back all the
  11063. subsequent objects to close the gap.
  11064. If the index passed in is out-of-range, nothing will happen.
  11065. The object that is removed will have its reference count decreased,
  11066. and may be deleted if not referenced from elsewhere.
  11067. @param indexToRemove the index of the element to remove
  11068. @see removeObject, removeRange
  11069. */
  11070. void remove (const int indexToRemove)
  11071. {
  11072. const ScopedLockType lock (getLock());
  11073. if (isPositiveAndBelow (indexToRemove, numUsed))
  11074. {
  11075. ObjectClass** const e = data.elements + indexToRemove;
  11076. if (*e != nullptr)
  11077. (*e)->decReferenceCount();
  11078. --numUsed;
  11079. const int numberToShift = numUsed - indexToRemove;
  11080. if (numberToShift > 0)
  11081. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11082. if ((numUsed << 1) < data.numAllocated)
  11083. minimiseStorageOverheads();
  11084. }
  11085. }
  11086. /** Removes and returns an object from the array.
  11087. This will remove the object at a given index and return it, moving back all
  11088. the subsequent objects to close the gap. If the index passed in is out-of-range,
  11089. nothing will happen and a null pointer will be returned.
  11090. @param indexToRemove the index of the element to remove
  11091. @see remove, removeObject, removeRange
  11092. */
  11093. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  11094. {
  11095. ObjectClassPtr removedItem;
  11096. const ScopedLockType lock (getLock());
  11097. if (isPositiveAndBelow (indexToRemove, numUsed))
  11098. {
  11099. ObjectClass** const e = data.elements + indexToRemove;
  11100. if (*e != nullptr)
  11101. {
  11102. removedItem = *e;
  11103. (*e)->decReferenceCount();
  11104. }
  11105. --numUsed;
  11106. const int numberToShift = numUsed - indexToRemove;
  11107. if (numberToShift > 0)
  11108. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11109. if ((numUsed << 1) < data.numAllocated)
  11110. minimiseStorageOverheads();
  11111. }
  11112. return removedItem;
  11113. }
  11114. /** Removes the first occurrence of a specified object from the array.
  11115. If the item isn't found, no action is taken. If it is found, it is
  11116. removed and has its reference count decreased.
  11117. @param objectToRemove the object to try to remove
  11118. @see remove, removeRange
  11119. */
  11120. void removeObject (ObjectClass* const objectToRemove)
  11121. {
  11122. const ScopedLockType lock (getLock());
  11123. remove (indexOf (objectToRemove));
  11124. }
  11125. /** Removes a range of objects from the array.
  11126. This will remove a set of objects, starting from the given index,
  11127. and move any subsequent elements down to close the gap.
  11128. If the range extends beyond the bounds of the array, it will
  11129. be safely clipped to the size of the array.
  11130. The objects that are removed will have their reference counts decreased,
  11131. and may be deleted if not referenced from elsewhere.
  11132. @param startIndex the index of the first object to remove
  11133. @param numberToRemove how many objects should be removed
  11134. @see remove, removeObject
  11135. */
  11136. void removeRange (const int startIndex,
  11137. const int numberToRemove)
  11138. {
  11139. const ScopedLockType lock (getLock());
  11140. const int start = jlimit (0, numUsed, startIndex);
  11141. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  11142. if (end > start)
  11143. {
  11144. int i;
  11145. for (i = start; i < end; ++i)
  11146. {
  11147. if (data.elements[i] != nullptr)
  11148. {
  11149. data.elements[i]->decReferenceCount();
  11150. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  11151. }
  11152. }
  11153. const int rangeSize = end - start;
  11154. ObjectClass** e = data.elements + start;
  11155. i = numUsed - end;
  11156. numUsed -= rangeSize;
  11157. while (--i >= 0)
  11158. {
  11159. *e = e [rangeSize];
  11160. ++e;
  11161. }
  11162. if ((numUsed << 1) < data.numAllocated)
  11163. minimiseStorageOverheads();
  11164. }
  11165. }
  11166. /** Removes the last n objects from the array.
  11167. The objects that are removed will have their reference counts decreased,
  11168. and may be deleted if not referenced from elsewhere.
  11169. @param howManyToRemove how many objects to remove from the end of the array
  11170. @see remove, removeObject, removeRange
  11171. */
  11172. void removeLast (int howManyToRemove = 1)
  11173. {
  11174. const ScopedLockType lock (getLock());
  11175. if (howManyToRemove > numUsed)
  11176. howManyToRemove = numUsed;
  11177. while (--howManyToRemove >= 0)
  11178. remove (numUsed - 1);
  11179. }
  11180. /** Swaps a pair of objects in the array.
  11181. If either of the indexes passed in is out-of-range, nothing will happen,
  11182. otherwise the two objects at these positions will be exchanged.
  11183. */
  11184. void swap (const int index1,
  11185. const int index2) noexcept
  11186. {
  11187. const ScopedLockType lock (getLock());
  11188. if (isPositiveAndBelow (index1, numUsed)
  11189. && isPositiveAndBelow (index2, numUsed))
  11190. {
  11191. std::swap (data.elements [index1],
  11192. data.elements [index2]);
  11193. }
  11194. }
  11195. /** Moves one of the objects to a different position.
  11196. This will move the object to a specified index, shuffling along
  11197. any intervening elements as required.
  11198. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  11199. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  11200. @param currentIndex the index of the object to be moved. If this isn't a
  11201. valid index, then nothing will be done
  11202. @param newIndex the index at which you'd like this object to end up. If this
  11203. is less than zero, it will be moved to the end of the array
  11204. */
  11205. void move (const int currentIndex,
  11206. int newIndex) noexcept
  11207. {
  11208. if (currentIndex != newIndex)
  11209. {
  11210. const ScopedLockType lock (getLock());
  11211. if (isPositiveAndBelow (currentIndex, numUsed))
  11212. {
  11213. if (! isPositiveAndBelow (newIndex, numUsed))
  11214. newIndex = numUsed - 1;
  11215. ObjectClass* const value = data.elements [currentIndex];
  11216. if (newIndex > currentIndex)
  11217. {
  11218. memmove (data.elements + currentIndex,
  11219. data.elements + currentIndex + 1,
  11220. (newIndex - currentIndex) * sizeof (ObjectClass*));
  11221. }
  11222. else
  11223. {
  11224. memmove (data.elements + newIndex + 1,
  11225. data.elements + newIndex,
  11226. (currentIndex - newIndex) * sizeof (ObjectClass*));
  11227. }
  11228. data.elements [newIndex] = value;
  11229. }
  11230. }
  11231. }
  11232. /** This swaps the contents of this array with those of another array.
  11233. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  11234. because it just swaps their internal pointers.
  11235. */
  11236. void swapWithArray (ReferenceCountedArray& otherArray) noexcept
  11237. {
  11238. const ScopedLockType lock1 (getLock());
  11239. const ScopedLockType lock2 (otherArray.getLock());
  11240. data.swapWith (otherArray.data);
  11241. std::swap (numUsed, otherArray.numUsed);
  11242. }
  11243. /** Compares this array to another one.
  11244. @returns true only if the other array contains the same objects in the same order
  11245. */
  11246. bool operator== (const ReferenceCountedArray& other) const noexcept
  11247. {
  11248. const ScopedLockType lock2 (other.getLock());
  11249. const ScopedLockType lock1 (getLock());
  11250. if (numUsed != other.numUsed)
  11251. return false;
  11252. for (int i = numUsed; --i >= 0;)
  11253. if (data.elements [i] != other.data.elements [i])
  11254. return false;
  11255. return true;
  11256. }
  11257. /** Compares this array to another one.
  11258. @see operator==
  11259. */
  11260. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  11261. {
  11262. return ! operator== (other);
  11263. }
  11264. /** Sorts the elements in the array.
  11265. This will use a comparator object to sort the elements into order. The object
  11266. passed must have a method of the form:
  11267. @code
  11268. int compareElements (ElementType first, ElementType second);
  11269. @endcode
  11270. ..and this method must return:
  11271. - a value of < 0 if the first comes before the second
  11272. - a value of 0 if the two objects are equivalent
  11273. - a value of > 0 if the second comes before the first
  11274. To improve performance, the compareElements() method can be declared as static or const.
  11275. @param comparator the comparator to use for comparing elements.
  11276. @param retainOrderOfEquivalentItems if this is true, then items
  11277. which the comparator says are equivalent will be
  11278. kept in the order in which they currently appear
  11279. in the array. This is slower to perform, but may
  11280. be important in some cases. If it's false, a faster
  11281. algorithm is used, but equivalent elements may be
  11282. rearranged.
  11283. @see sortArray
  11284. */
  11285. template <class ElementComparator>
  11286. void sort (ElementComparator& comparator,
  11287. const bool retainOrderOfEquivalentItems = false) const noexcept
  11288. {
  11289. (void) comparator; // if you pass in an object with a static compareElements() method, this
  11290. // avoids getting warning messages about the parameter being unused
  11291. const ScopedLockType lock (getLock());
  11292. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  11293. }
  11294. /** Reduces the amount of storage being used by the array.
  11295. Arrays typically allocate slightly more storage than they need, and after
  11296. removing elements, they may have quite a lot of unused space allocated.
  11297. This method will reduce the amount of allocated storage to a minimum.
  11298. */
  11299. void minimiseStorageOverheads() noexcept
  11300. {
  11301. const ScopedLockType lock (getLock());
  11302. data.shrinkToNoMoreThan (numUsed);
  11303. }
  11304. /** Returns the CriticalSection that locks this array.
  11305. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11306. an object of ScopedLockType as an RAII lock for it.
  11307. */
  11308. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11309. /** Returns the type of scoped lock to use for locking this array */
  11310. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11311. private:
  11312. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  11313. int numUsed;
  11314. };
  11315. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  11316. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  11317. #endif
  11318. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11319. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  11320. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11321. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11322. /**
  11323. Helper class providing an RAII-based mechanism for temporarily setting and
  11324. then re-setting a value.
  11325. E.g. @code
  11326. int x = 1;
  11327. {
  11328. ScopedValueSetter setter (x, 2);
  11329. // x is now 2
  11330. }
  11331. // x is now 1 again
  11332. {
  11333. ScopedValueSetter setter (x, 3, 4);
  11334. // x is now 3
  11335. }
  11336. // x is now 4
  11337. @endcode
  11338. */
  11339. template <typename ValueType>
  11340. class ScopedValueSetter
  11341. {
  11342. public:
  11343. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11344. given new value, and will then reset it to its original value when this object is deleted.
  11345. */
  11346. ScopedValueSetter (ValueType& valueToSet,
  11347. const ValueType& newValue)
  11348. : value (valueToSet),
  11349. originalValue (valueToSet)
  11350. {
  11351. valueToSet = newValue;
  11352. }
  11353. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11354. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  11355. */
  11356. ScopedValueSetter (ValueType& valueToSet,
  11357. const ValueType& newValue,
  11358. const ValueType& valueWhenDeleted)
  11359. : value (valueToSet),
  11360. originalValue (valueWhenDeleted)
  11361. {
  11362. valueToSet = newValue;
  11363. }
  11364. ~ScopedValueSetter()
  11365. {
  11366. value = originalValue;
  11367. }
  11368. private:
  11369. ValueType& value;
  11370. const ValueType originalValue;
  11371. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  11372. };
  11373. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11374. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  11375. #endif
  11376. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11377. /*** Start of inlined file: juce_SortedSet.h ***/
  11378. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11379. #define __JUCE_SORTEDSET_JUCEHEADER__
  11380. #if JUCE_MSVC
  11381. #pragma warning (push)
  11382. #pragma warning (disable: 4512)
  11383. #endif
  11384. /**
  11385. Holds a set of unique primitive objects, such as ints or doubles.
  11386. A set can only hold one item with a given value, so if for example it's a
  11387. set of integers, attempting to add the same integer twice will do nothing
  11388. the second time.
  11389. Internally, the list of items is kept sorted (which means that whatever
  11390. kind of primitive type is used must support the ==, <, >, <= and >= operators
  11391. to determine the order), and searching the set for known values is very fast
  11392. because it uses a binary-chop method.
  11393. Note that if you're using a class or struct as the element type, it must be
  11394. capable of being copied or moved with a straightforward memcpy, rather than
  11395. needing construction and destruction code.
  11396. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  11397. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  11398. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  11399. */
  11400. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  11401. class SortedSet
  11402. {
  11403. public:
  11404. /** Creates an empty set. */
  11405. SortedSet() noexcept
  11406. : numUsed (0)
  11407. {
  11408. }
  11409. /** Creates a copy of another set.
  11410. @param other the set to copy
  11411. */
  11412. SortedSet (const SortedSet& other) noexcept
  11413. {
  11414. const ScopedLockType lock (other.getLock());
  11415. numUsed = other.numUsed;
  11416. data.setAllocatedSize (other.numUsed);
  11417. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11418. }
  11419. /** Destructor. */
  11420. ~SortedSet() noexcept
  11421. {
  11422. }
  11423. /** Copies another set over this one.
  11424. @param other the set to copy
  11425. */
  11426. SortedSet& operator= (const SortedSet& other) noexcept
  11427. {
  11428. if (this != &other)
  11429. {
  11430. const ScopedLockType lock1 (other.getLock());
  11431. const ScopedLockType lock2 (getLock());
  11432. data.ensureAllocatedSize (other.size());
  11433. numUsed = other.numUsed;
  11434. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11435. minimiseStorageOverheads();
  11436. }
  11437. return *this;
  11438. }
  11439. /** Compares this set to another one.
  11440. Two sets are considered equal if they both contain the same set of
  11441. elements.
  11442. @param other the other set to compare with
  11443. */
  11444. bool operator== (const SortedSet<ElementType>& other) const noexcept
  11445. {
  11446. const ScopedLockType lock (getLock());
  11447. if (numUsed != other.numUsed)
  11448. return false;
  11449. for (int i = numUsed; --i >= 0;)
  11450. if (data.elements[i] != other.data.elements[i])
  11451. return false;
  11452. return true;
  11453. }
  11454. /** Compares this set to another one.
  11455. Two sets are considered equal if they both contain the same set of
  11456. elements.
  11457. @param other the other set to compare with
  11458. */
  11459. bool operator!= (const SortedSet<ElementType>& other) const noexcept
  11460. {
  11461. return ! operator== (other);
  11462. }
  11463. /** Removes all elements from the set.
  11464. This will remove all the elements, and free any storage that the set is
  11465. using. To clear it without freeing the storage, use the clearQuick()
  11466. method instead.
  11467. @see clearQuick
  11468. */
  11469. void clear() noexcept
  11470. {
  11471. const ScopedLockType lock (getLock());
  11472. data.setAllocatedSize (0);
  11473. numUsed = 0;
  11474. }
  11475. /** Removes all elements from the set without freeing the array's allocated storage.
  11476. @see clear
  11477. */
  11478. void clearQuick() noexcept
  11479. {
  11480. const ScopedLockType lock (getLock());
  11481. numUsed = 0;
  11482. }
  11483. /** Returns the current number of elements in the set.
  11484. */
  11485. inline int size() const noexcept
  11486. {
  11487. return numUsed;
  11488. }
  11489. /** Returns one of the elements in the set.
  11490. If the index passed in is beyond the range of valid elements, this
  11491. will return zero.
  11492. If you're certain that the index will always be a valid element, you
  11493. can call getUnchecked() instead, which is faster.
  11494. @param index the index of the element being requested (0 is the first element in the set)
  11495. @see getUnchecked, getFirst, getLast
  11496. */
  11497. inline ElementType operator[] (const int index) const noexcept
  11498. {
  11499. const ScopedLockType lock (getLock());
  11500. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11501. : ElementType();
  11502. }
  11503. /** Returns one of the elements in the set, without checking the index passed in.
  11504. Unlike the operator[] method, this will try to return an element without
  11505. checking that the index is within the bounds of the set, so should only
  11506. be used when you're confident that it will always be a valid index.
  11507. @param index the index of the element being requested (0 is the first element in the set)
  11508. @see operator[], getFirst, getLast
  11509. */
  11510. inline ElementType getUnchecked (const int index) const noexcept
  11511. {
  11512. const ScopedLockType lock (getLock());
  11513. jassert (isPositiveAndBelow (index, numUsed));
  11514. return data.elements [index];
  11515. }
  11516. /** Returns the first element in the set, or 0 if the set is empty.
  11517. @see operator[], getUnchecked, getLast
  11518. */
  11519. inline ElementType getFirst() const noexcept
  11520. {
  11521. const ScopedLockType lock (getLock());
  11522. return numUsed > 0 ? data.elements [0] : ElementType();
  11523. }
  11524. /** Returns the last element in the set, or 0 if the set is empty.
  11525. @see operator[], getUnchecked, getFirst
  11526. */
  11527. inline ElementType getLast() const noexcept
  11528. {
  11529. const ScopedLockType lock (getLock());
  11530. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  11531. }
  11532. /** Returns a pointer to the first element in the set.
  11533. This method is provided for compatibility with standard C++ iteration mechanisms.
  11534. */
  11535. inline ElementType* begin() const noexcept
  11536. {
  11537. return data.elements;
  11538. }
  11539. /** Returns a pointer to the element which follows the last element in the set.
  11540. This method is provided for compatibility with standard C++ iteration mechanisms.
  11541. */
  11542. inline ElementType* end() const noexcept
  11543. {
  11544. return data.elements + numUsed;
  11545. }
  11546. /** Finds the index of the first element which matches the value passed in.
  11547. This will search the set for the given object, and return the index
  11548. of its first occurrence. If the object isn't found, the method will return -1.
  11549. @param elementToLookFor the value or object to look for
  11550. @returns the index of the object, or -1 if it's not found
  11551. */
  11552. int indexOf (const ElementType elementToLookFor) const noexcept
  11553. {
  11554. const ScopedLockType lock (getLock());
  11555. int start = 0;
  11556. int end = numUsed;
  11557. for (;;)
  11558. {
  11559. if (start >= end)
  11560. {
  11561. return -1;
  11562. }
  11563. else if (elementToLookFor == data.elements [start])
  11564. {
  11565. return start;
  11566. }
  11567. else
  11568. {
  11569. const int halfway = (start + end) >> 1;
  11570. if (halfway == start)
  11571. return -1;
  11572. else if (elementToLookFor >= data.elements [halfway])
  11573. start = halfway;
  11574. else
  11575. end = halfway;
  11576. }
  11577. }
  11578. }
  11579. /** Returns true if the set contains at least one occurrence of an object.
  11580. @param elementToLookFor the value or object to look for
  11581. @returns true if the item is found
  11582. */
  11583. bool contains (const ElementType elementToLookFor) const noexcept
  11584. {
  11585. const ScopedLockType lock (getLock());
  11586. int start = 0;
  11587. int end = numUsed;
  11588. for (;;)
  11589. {
  11590. if (start >= end)
  11591. {
  11592. return false;
  11593. }
  11594. else if (elementToLookFor == data.elements [start])
  11595. {
  11596. return true;
  11597. }
  11598. else
  11599. {
  11600. const int halfway = (start + end) >> 1;
  11601. if (halfway == start)
  11602. return false;
  11603. else if (elementToLookFor >= data.elements [halfway])
  11604. start = halfway;
  11605. else
  11606. end = halfway;
  11607. }
  11608. }
  11609. }
  11610. /** Adds a new element to the set, (as long as it's not already in there).
  11611. @param newElement the new object to add to the set
  11612. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  11613. */
  11614. void add (const ElementType newElement) noexcept
  11615. {
  11616. const ScopedLockType lock (getLock());
  11617. int start = 0;
  11618. int end = numUsed;
  11619. for (;;)
  11620. {
  11621. if (start >= end)
  11622. {
  11623. jassert (start <= end);
  11624. insertInternal (start, newElement);
  11625. break;
  11626. }
  11627. else if (newElement == data.elements [start])
  11628. {
  11629. break;
  11630. }
  11631. else
  11632. {
  11633. const int halfway = (start + end) >> 1;
  11634. if (halfway == start)
  11635. {
  11636. if (newElement >= data.elements [halfway])
  11637. insertInternal (start + 1, newElement);
  11638. else
  11639. insertInternal (start, newElement);
  11640. break;
  11641. }
  11642. else if (newElement >= data.elements [halfway])
  11643. start = halfway;
  11644. else
  11645. end = halfway;
  11646. }
  11647. }
  11648. }
  11649. /** Adds elements from an array to this set.
  11650. @param elementsToAdd the array of elements to add
  11651. @param numElementsToAdd how many elements are in this other array
  11652. @see add
  11653. */
  11654. void addArray (const ElementType* elementsToAdd,
  11655. int numElementsToAdd) noexcept
  11656. {
  11657. const ScopedLockType lock (getLock());
  11658. while (--numElementsToAdd >= 0)
  11659. add (*elementsToAdd++);
  11660. }
  11661. /** Adds elements from another set to this one.
  11662. @param setToAddFrom the set from which to copy the elements
  11663. @param startIndex the first element of the other set to start copying from
  11664. @param numElementsToAdd how many elements to add from the other set. If this
  11665. value is negative or greater than the number of available elements,
  11666. all available elements will be copied.
  11667. @see add
  11668. */
  11669. template <class OtherSetType>
  11670. void addSet (const OtherSetType& setToAddFrom,
  11671. int startIndex = 0,
  11672. int numElementsToAdd = -1) noexcept
  11673. {
  11674. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11675. {
  11676. const ScopedLockType lock2 (getLock());
  11677. jassert (this != &setToAddFrom);
  11678. if (this != &setToAddFrom)
  11679. {
  11680. if (startIndex < 0)
  11681. {
  11682. jassertfalse;
  11683. startIndex = 0;
  11684. }
  11685. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11686. numElementsToAdd = setToAddFrom.size() - startIndex;
  11687. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11688. }
  11689. }
  11690. }
  11691. /** Removes an element from the set.
  11692. This will remove the element at a given index.
  11693. If the index passed in is out-of-range, nothing will happen.
  11694. @param indexToRemove the index of the element to remove
  11695. @returns the element that has been removed
  11696. @see removeValue, removeRange
  11697. */
  11698. ElementType remove (const int indexToRemove) noexcept
  11699. {
  11700. const ScopedLockType lock (getLock());
  11701. if (isPositiveAndBelow (indexToRemove, numUsed))
  11702. {
  11703. --numUsed;
  11704. ElementType* const e = data.elements + indexToRemove;
  11705. ElementType const removed = *e;
  11706. const int numberToShift = numUsed - indexToRemove;
  11707. if (numberToShift > 0)
  11708. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11709. if ((numUsed << 1) < data.numAllocated)
  11710. minimiseStorageOverheads();
  11711. return removed;
  11712. }
  11713. return ElementType();
  11714. }
  11715. /** Removes an item from the set.
  11716. This will remove the given element from the set, if it's there.
  11717. @param valueToRemove the object to try to remove
  11718. @see remove, removeRange
  11719. */
  11720. void removeValue (const ElementType valueToRemove) noexcept
  11721. {
  11722. const ScopedLockType lock (getLock());
  11723. remove (indexOf (valueToRemove));
  11724. }
  11725. /** Removes any elements which are also in another set.
  11726. @param otherSet the other set in which to look for elements to remove
  11727. @see removeValuesNotIn, remove, removeValue, removeRange
  11728. */
  11729. template <class OtherSetType>
  11730. void removeValuesIn (const OtherSetType& otherSet) noexcept
  11731. {
  11732. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11733. const ScopedLockType lock2 (getLock());
  11734. if (this == &otherSet)
  11735. {
  11736. clear();
  11737. }
  11738. else
  11739. {
  11740. if (otherSet.size() > 0)
  11741. {
  11742. for (int i = numUsed; --i >= 0;)
  11743. if (otherSet.contains (data.elements [i]))
  11744. remove (i);
  11745. }
  11746. }
  11747. }
  11748. /** Removes any elements which are not found in another set.
  11749. Only elements which occur in this other set will be retained.
  11750. @param otherSet the set in which to look for elements NOT to remove
  11751. @see removeValuesIn, remove, removeValue, removeRange
  11752. */
  11753. template <class OtherSetType>
  11754. void removeValuesNotIn (const OtherSetType& otherSet) noexcept
  11755. {
  11756. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11757. const ScopedLockType lock2 (getLock());
  11758. if (this != &otherSet)
  11759. {
  11760. if (otherSet.size() <= 0)
  11761. {
  11762. clear();
  11763. }
  11764. else
  11765. {
  11766. for (int i = numUsed; --i >= 0;)
  11767. if (! otherSet.contains (data.elements [i]))
  11768. remove (i);
  11769. }
  11770. }
  11771. }
  11772. /** Reduces the amount of storage being used by the set.
  11773. Sets typically allocate slightly more storage than they need, and after
  11774. removing elements, they may have quite a lot of unused space allocated.
  11775. This method will reduce the amount of allocated storage to a minimum.
  11776. */
  11777. void minimiseStorageOverheads() noexcept
  11778. {
  11779. const ScopedLockType lock (getLock());
  11780. data.shrinkToNoMoreThan (numUsed);
  11781. }
  11782. /** Returns the CriticalSection that locks this array.
  11783. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11784. an object of ScopedLockType as an RAII lock for it.
  11785. */
  11786. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11787. /** Returns the type of scoped lock to use for locking this array */
  11788. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11789. private:
  11790. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11791. int numUsed;
  11792. void insertInternal (const int indexToInsertAt, const ElementType newElement) noexcept
  11793. {
  11794. data.ensureAllocatedSize (numUsed + 1);
  11795. ElementType* const insertPos = data.elements + indexToInsertAt;
  11796. const int numberToMove = numUsed - indexToInsertAt;
  11797. if (numberToMove > 0)
  11798. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11799. *insertPos = newElement;
  11800. ++numUsed;
  11801. }
  11802. };
  11803. #if JUCE_MSVC
  11804. #pragma warning (pop)
  11805. #endif
  11806. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11807. /*** End of inlined file: juce_SortedSet.h ***/
  11808. #endif
  11809. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11810. /*** Start of inlined file: juce_SparseSet.h ***/
  11811. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11812. #define __JUCE_SPARSESET_JUCEHEADER__
  11813. /*** Start of inlined file: juce_Range.h ***/
  11814. #ifndef __JUCE_RANGE_JUCEHEADER__
  11815. #define __JUCE_RANGE_JUCEHEADER__
  11816. /** A general-purpose range object, that simply represents any linear range with
  11817. a start and end point.
  11818. The templated parameter is expected to be a primitive integer or floating point
  11819. type, though class types could also be used if they behave in a number-like way.
  11820. */
  11821. template <typename ValueType>
  11822. class Range
  11823. {
  11824. public:
  11825. /** Constructs an empty range. */
  11826. Range() noexcept
  11827. : start (ValueType()), end (ValueType())
  11828. {
  11829. }
  11830. /** Constructs a range with given start and end values. */
  11831. Range (const ValueType start_, const ValueType end_) noexcept
  11832. : start (start_), end (jmax (start_, end_))
  11833. {
  11834. }
  11835. /** Constructs a copy of another range. */
  11836. Range (const Range& other) noexcept
  11837. : start (other.start), end (other.end)
  11838. {
  11839. }
  11840. /** Copies another range object. */
  11841. Range& operator= (const Range& other) noexcept
  11842. {
  11843. start = other.start;
  11844. end = other.end;
  11845. return *this;
  11846. }
  11847. /** Destructor. */
  11848. ~Range() noexcept
  11849. {
  11850. }
  11851. /** Returns the range that lies between two positions (in either order). */
  11852. static const Range between (const ValueType position1, const ValueType position2) noexcept
  11853. {
  11854. return (position1 < position2) ? Range (position1, position2)
  11855. : Range (position2, position1);
  11856. }
  11857. /** Returns a range with the specified start position and a length of zero. */
  11858. static const Range emptyRange (const ValueType start) noexcept
  11859. {
  11860. return Range (start, start);
  11861. }
  11862. /** Returns the start of the range. */
  11863. inline ValueType getStart() const noexcept { return start; }
  11864. /** Returns the length of the range. */
  11865. inline ValueType getLength() const noexcept { return end - start; }
  11866. /** Returns the end of the range. */
  11867. inline ValueType getEnd() const noexcept { return end; }
  11868. /** Returns true if the range has a length of zero. */
  11869. inline bool isEmpty() const noexcept { return start == end; }
  11870. /** Changes the start position of the range, leaving the end position unchanged.
  11871. If the new start position is higher than the current end of the range, the end point
  11872. will be pushed along to equal it, leaving an empty range at the new position.
  11873. */
  11874. void setStart (const ValueType newStart) noexcept
  11875. {
  11876. start = newStart;
  11877. if (end < newStart)
  11878. end = newStart;
  11879. }
  11880. /** Returns a range with the same end as this one, but a different start.
  11881. If the new start position is higher than the current end of the range, the end point
  11882. will be pushed along to equal it, returning an empty range at the new position.
  11883. */
  11884. const Range withStart (const ValueType newStart) const noexcept
  11885. {
  11886. return Range (newStart, jmax (newStart, end));
  11887. }
  11888. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11889. const Range movedToStartAt (const ValueType newStart) const noexcept
  11890. {
  11891. return Range (newStart, end + (newStart - start));
  11892. }
  11893. /** Changes the end position of the range, leaving the start unchanged.
  11894. If the new end position is below the current start of the range, the start point
  11895. will be pushed back to equal the new end point.
  11896. */
  11897. void setEnd (const ValueType newEnd) noexcept
  11898. {
  11899. end = newEnd;
  11900. if (newEnd < start)
  11901. start = newEnd;
  11902. }
  11903. /** Returns a range with the same start position as this one, but a different end.
  11904. If the new end position is below the current start of the range, the start point
  11905. will be pushed back to equal the new end point.
  11906. */
  11907. const Range withEnd (const ValueType newEnd) const noexcept
  11908. {
  11909. return Range (jmin (start, newEnd), newEnd);
  11910. }
  11911. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11912. const Range movedToEndAt (const ValueType newEnd) const noexcept
  11913. {
  11914. return Range (start + (newEnd - end), newEnd);
  11915. }
  11916. /** Changes the length of the range.
  11917. Lengths less than zero are treated as zero.
  11918. */
  11919. void setLength (const ValueType newLength) noexcept
  11920. {
  11921. end = start + jmax (ValueType(), newLength);
  11922. }
  11923. /** Returns a range with the same start as this one, but a different length.
  11924. Lengths less than zero are treated as zero.
  11925. */
  11926. const Range withLength (const ValueType newLength) const noexcept
  11927. {
  11928. return Range (start, start + newLength);
  11929. }
  11930. /** Adds an amount to the start and end of the range. */
  11931. inline const Range& operator+= (const ValueType amountToAdd) noexcept
  11932. {
  11933. start += amountToAdd;
  11934. end += amountToAdd;
  11935. return *this;
  11936. }
  11937. /** Subtracts an amount from the start and end of the range. */
  11938. inline const Range& operator-= (const ValueType amountToSubtract) noexcept
  11939. {
  11940. start -= amountToSubtract;
  11941. end -= amountToSubtract;
  11942. return *this;
  11943. }
  11944. /** Returns a range that is equal to this one with an amount added to its
  11945. start and end.
  11946. */
  11947. const Range operator+ (const ValueType amountToAdd) const noexcept
  11948. {
  11949. return Range (start + amountToAdd, end + amountToAdd);
  11950. }
  11951. /** Returns a range that is equal to this one with the specified amount
  11952. subtracted from its start and end. */
  11953. const Range operator- (const ValueType amountToSubtract) const noexcept
  11954. {
  11955. return Range (start - amountToSubtract, end - amountToSubtract);
  11956. }
  11957. bool operator== (const Range& other) const noexcept { return start == other.start && end == other.end; }
  11958. bool operator!= (const Range& other) const noexcept { return start != other.start || end != other.end; }
  11959. /** Returns true if the given position lies inside this range. */
  11960. bool contains (const ValueType position) const noexcept
  11961. {
  11962. return start <= position && position < end;
  11963. }
  11964. /** Returns the nearest value to the one supplied, which lies within the range. */
  11965. ValueType clipValue (const ValueType value) const noexcept
  11966. {
  11967. return jlimit (start, end, value);
  11968. }
  11969. /** Returns true if the given range lies entirely inside this range. */
  11970. bool contains (const Range& other) const noexcept
  11971. {
  11972. return start <= other.start && end >= other.end;
  11973. }
  11974. /** Returns true if the given range intersects this one. */
  11975. bool intersects (const Range& other) const noexcept
  11976. {
  11977. return other.start < end && start < other.end;
  11978. }
  11979. /** Returns the range that is the intersection of the two ranges, or an empty range
  11980. with an undefined start position if they don't overlap. */
  11981. const Range getIntersectionWith (const Range& other) const noexcept
  11982. {
  11983. return Range (jmax (start, other.start),
  11984. jmin (end, other.end));
  11985. }
  11986. /** Returns the smallest range that contains both this one and the other one. */
  11987. const Range getUnionWith (const Range& other) const noexcept
  11988. {
  11989. return Range (jmin (start, other.start),
  11990. jmax (end, other.end));
  11991. }
  11992. /** Returns a given range, after moving it forwards or backwards to fit it
  11993. within this range.
  11994. If the supplied range has a greater length than this one, the return value
  11995. will be this range.
  11996. Otherwise, if the supplied range is smaller than this one, the return value
  11997. will be the new range, shifted forwards or backwards so that it doesn't extend
  11998. beyond this one, but keeping its original length.
  11999. */
  12000. const Range constrainRange (const Range& rangeToConstrain) const noexcept
  12001. {
  12002. const ValueType otherLen = rangeToConstrain.getLength();
  12003. return getLength() <= otherLen
  12004. ? *this
  12005. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  12006. }
  12007. private:
  12008. ValueType start, end;
  12009. };
  12010. #endif // __JUCE_RANGE_JUCEHEADER__
  12011. /*** End of inlined file: juce_Range.h ***/
  12012. /**
  12013. Holds a set of primitive values, storing them as a set of ranges.
  12014. This container acts like an array, but can efficiently hold large continguous
  12015. ranges of values. It's quite a specialised class, mostly useful for things
  12016. like keeping the set of selected rows in a listbox.
  12017. The type used as a template paramter must be an integer type, such as int, short,
  12018. int64, etc.
  12019. */
  12020. template <class Type>
  12021. class SparseSet
  12022. {
  12023. public:
  12024. /** Creates a new empty set. */
  12025. SparseSet()
  12026. {
  12027. }
  12028. /** Creates a copy of another SparseSet. */
  12029. SparseSet (const SparseSet<Type>& other)
  12030. : values (other.values)
  12031. {
  12032. }
  12033. /** Clears the set. */
  12034. void clear()
  12035. {
  12036. values.clear();
  12037. }
  12038. /** Checks whether the set is empty.
  12039. This is much quicker than using (size() == 0).
  12040. */
  12041. bool isEmpty() const noexcept
  12042. {
  12043. return values.size() == 0;
  12044. }
  12045. /** Returns the number of values in the set.
  12046. Because of the way the data is stored, this method can take longer if there
  12047. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  12048. are any items.
  12049. */
  12050. Type size() const
  12051. {
  12052. Type total (0);
  12053. for (int i = 0; i < values.size(); i += 2)
  12054. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  12055. return total;
  12056. }
  12057. /** Returns one of the values in the set.
  12058. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  12059. @returns the value at this index, or 0 if it's out-of-range
  12060. */
  12061. Type operator[] (Type index) const
  12062. {
  12063. for (int i = 0; i < values.size(); i += 2)
  12064. {
  12065. const Type start (values.getUnchecked (i));
  12066. const Type len (values.getUnchecked (i + 1) - start);
  12067. if (index < len)
  12068. return start + index;
  12069. index -= len;
  12070. }
  12071. return Type();
  12072. }
  12073. /** Checks whether a particular value is in the set. */
  12074. bool contains (const Type valueToLookFor) const
  12075. {
  12076. for (int i = 0; i < values.size(); ++i)
  12077. if (valueToLookFor < values.getUnchecked(i))
  12078. return (i & 1) != 0;
  12079. return false;
  12080. }
  12081. /** Returns the number of contiguous blocks of values.
  12082. @see getRange
  12083. */
  12084. int getNumRanges() const noexcept
  12085. {
  12086. return values.size() >> 1;
  12087. }
  12088. /** Returns one of the contiguous ranges of values stored.
  12089. @param rangeIndex the index of the range to look up, between 0
  12090. and (getNumRanges() - 1)
  12091. @see getTotalRange
  12092. */
  12093. const Range<Type> getRange (const int rangeIndex) const
  12094. {
  12095. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  12096. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  12097. values.getUnchecked ((rangeIndex << 1) + 1));
  12098. else
  12099. return Range<Type>();
  12100. }
  12101. /** Returns the range between the lowest and highest values in the set.
  12102. @see getRange
  12103. */
  12104. const Range<Type> getTotalRange() const
  12105. {
  12106. if (values.size() > 0)
  12107. {
  12108. jassert ((values.size() & 1) == 0);
  12109. return Range<Type> (values.getUnchecked (0),
  12110. values.getUnchecked (values.size() - 1));
  12111. }
  12112. return Range<Type>();
  12113. }
  12114. /** Adds a range of contiguous values to the set.
  12115. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  12116. */
  12117. void addRange (const Range<Type>& range)
  12118. {
  12119. jassert (range.getLength() >= 0);
  12120. if (range.getLength() > 0)
  12121. {
  12122. removeRange (range);
  12123. values.addUsingDefaultSort (range.getStart());
  12124. values.addUsingDefaultSort (range.getEnd());
  12125. simplify();
  12126. }
  12127. }
  12128. /** Removes a range of values from the set.
  12129. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  12130. */
  12131. void removeRange (const Range<Type>& rangeToRemove)
  12132. {
  12133. jassert (rangeToRemove.getLength() >= 0);
  12134. if (rangeToRemove.getLength() > 0
  12135. && values.size() > 0
  12136. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  12137. && values.getUnchecked(0) < rangeToRemove.getEnd())
  12138. {
  12139. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  12140. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  12141. const bool onAtEnd = contains (lastValue);
  12142. for (int i = values.size(); --i >= 0;)
  12143. {
  12144. if (values.getUnchecked(i) <= lastValue)
  12145. {
  12146. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  12147. {
  12148. values.remove (i);
  12149. if (--i < 0)
  12150. break;
  12151. }
  12152. break;
  12153. }
  12154. }
  12155. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  12156. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  12157. simplify();
  12158. }
  12159. }
  12160. /** Does an XOR of the values in a given range. */
  12161. void invertRange (const Range<Type>& range)
  12162. {
  12163. SparseSet newItems;
  12164. newItems.addRange (range);
  12165. int i;
  12166. for (i = getNumRanges(); --i >= 0;)
  12167. newItems.removeRange (getRange (i));
  12168. removeRange (range);
  12169. for (i = newItems.getNumRanges(); --i >= 0;)
  12170. addRange (newItems.getRange(i));
  12171. }
  12172. /** Checks whether any part of a given range overlaps any part of this set. */
  12173. bool overlapsRange (const Range<Type>& range)
  12174. {
  12175. if (range.getLength() > 0)
  12176. {
  12177. for (int i = getNumRanges(); --i >= 0;)
  12178. {
  12179. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12180. return false;
  12181. if (values.getUnchecked (i << 1) < range.getEnd())
  12182. return true;
  12183. }
  12184. }
  12185. return false;
  12186. }
  12187. /** Checks whether the whole of a given range is contained within this one. */
  12188. bool containsRange (const Range<Type>& range)
  12189. {
  12190. if (range.getLength() > 0)
  12191. {
  12192. for (int i = getNumRanges(); --i >= 0;)
  12193. {
  12194. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12195. return false;
  12196. if (values.getUnchecked (i << 1) <= range.getStart()
  12197. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  12198. return true;
  12199. }
  12200. }
  12201. return false;
  12202. }
  12203. bool operator== (const SparseSet<Type>& other) noexcept
  12204. {
  12205. return values == other.values;
  12206. }
  12207. bool operator!= (const SparseSet<Type>& other) noexcept
  12208. {
  12209. return values != other.values;
  12210. }
  12211. private:
  12212. // alternating start/end values of ranges of values that are present.
  12213. Array<Type, DummyCriticalSection> values;
  12214. void simplify()
  12215. {
  12216. jassert ((values.size() & 1) == 0);
  12217. for (int i = values.size(); --i > 0;)
  12218. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  12219. values.removeRange (--i, 2);
  12220. }
  12221. };
  12222. #endif // __JUCE_SPARSESET_JUCEHEADER__
  12223. /*** End of inlined file: juce_SparseSet.h ***/
  12224. #endif
  12225. #ifndef __JUCE_VALUE_JUCEHEADER__
  12226. /*** Start of inlined file: juce_Value.h ***/
  12227. #ifndef __JUCE_VALUE_JUCEHEADER__
  12228. #define __JUCE_VALUE_JUCEHEADER__
  12229. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  12230. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  12231. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  12232. /*** Start of inlined file: juce_CallbackMessage.h ***/
  12233. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12234. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12235. /*** Start of inlined file: juce_Message.h ***/
  12236. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  12237. #define __JUCE_MESSAGE_JUCEHEADER__
  12238. class MessageListener;
  12239. class MessageManager;
  12240. /** The base class for objects that can be delivered to a MessageListener.
  12241. The simplest Message object contains a few integer and pointer parameters
  12242. that the user can set, and this is enough for a lot of purposes. For passing more
  12243. complex data, subclasses of Message can also be used.
  12244. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12245. */
  12246. class JUCE_API Message : public ReferenceCountedObject
  12247. {
  12248. public:
  12249. /** Creates an uninitialised message.
  12250. The class's variables will also be left uninitialised.
  12251. */
  12252. Message() noexcept;
  12253. /** Creates a message object, filling in the member variables.
  12254. The corresponding public member variables will be set from the parameters
  12255. passed in.
  12256. */
  12257. Message (int intParameter1,
  12258. int intParameter2,
  12259. int intParameter3,
  12260. void* pointerParameter) noexcept;
  12261. /** Destructor. */
  12262. virtual ~Message();
  12263. // These values can be used for carrying simple data that the application needs to
  12264. // pass around. For more complex messages, just create a subclass.
  12265. int intParameter1; /**< user-defined integer value. */
  12266. int intParameter2; /**< user-defined integer value. */
  12267. int intParameter3; /**< user-defined integer value. */
  12268. void* pointerParameter; /**< user-defined pointer value. */
  12269. /** A typedef for pointers to messages. */
  12270. typedef ReferenceCountedObjectPtr <Message> Ptr;
  12271. private:
  12272. friend class MessageListener;
  12273. friend class MessageManager;
  12274. MessageListener* messageRecipient;
  12275. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12276. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12277. JUCE_DECLARE_NON_COPYABLE (Message);
  12278. };
  12279. #endif // __JUCE_MESSAGE_JUCEHEADER__
  12280. /*** End of inlined file: juce_Message.h ***/
  12281. /**
  12282. A message that calls a custom function when it gets delivered.
  12283. You can use this class to fire off actions that you want to be performed later
  12284. on the message thread.
  12285. Unlike other Message objects, these don't get sent to a MessageListener, you
  12286. just call the post() method to send them, and when they arrive, your
  12287. messageCallback() method will automatically be invoked.
  12288. Always create an instance of a CallbackMessage on the heap, as it will be
  12289. deleted automatically after the message has been delivered.
  12290. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12291. */
  12292. class JUCE_API CallbackMessage : public Message
  12293. {
  12294. public:
  12295. CallbackMessage() noexcept;
  12296. /** Destructor. */
  12297. ~CallbackMessage();
  12298. /** Called when the message is delivered.
  12299. You should implement this method and make it do whatever action you want
  12300. to perform.
  12301. Note that like all other messages, this object will be deleted immediately
  12302. after this method has been invoked.
  12303. */
  12304. virtual void messageCallback() = 0;
  12305. /** Instead of sending this message to a MessageListener, just call this method
  12306. to post it to the event queue.
  12307. After you've called this, this object will belong to the MessageManager,
  12308. which will delete it later. So make sure you don't delete the object yourself,
  12309. call post() more than once, or call post() on a stack-based obect!
  12310. */
  12311. void post();
  12312. private:
  12313. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12314. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12315. JUCE_DECLARE_NON_COPYABLE (CallbackMessage);
  12316. };
  12317. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12318. /*** End of inlined file: juce_CallbackMessage.h ***/
  12319. /**
  12320. Has a callback method that is triggered asynchronously.
  12321. This object allows an asynchronous callback function to be triggered, for
  12322. tasks such as coalescing multiple updates into a single callback later on.
  12323. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  12324. message thread calling handleAsyncUpdate() as soon as it can.
  12325. */
  12326. class JUCE_API AsyncUpdater
  12327. {
  12328. public:
  12329. /** Creates an AsyncUpdater object. */
  12330. AsyncUpdater();
  12331. /** Destructor.
  12332. If there are any pending callbacks when the object is deleted, these are lost.
  12333. */
  12334. virtual ~AsyncUpdater();
  12335. /** Causes the callback to be triggered at a later time.
  12336. This method returns immediately, having made sure that a callback
  12337. to the handleAsyncUpdate() method will occur as soon as possible.
  12338. If an update callback is already pending but hasn't happened yet, calls
  12339. to this method will be ignored.
  12340. It's thread-safe to call this method from any number of threads without
  12341. needing to worry about locking.
  12342. */
  12343. void triggerAsyncUpdate();
  12344. /** This will stop any pending updates from happening.
  12345. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  12346. callback happens, this will cancel the handleAsyncUpdate() callback.
  12347. Note that this method simply cancels the next callback - if a callback is already
  12348. in progress on a different thread, this won't block until it finishes, so there's
  12349. no guarantee that the callback isn't still running when you return from
  12350. */
  12351. void cancelPendingUpdate() noexcept;
  12352. /** If an update has been triggered and is pending, this will invoke it
  12353. synchronously.
  12354. Use this as a kind of "flush" operation - if an update is pending, the
  12355. handleAsyncUpdate() method will be called immediately; if no update is
  12356. pending, then nothing will be done.
  12357. Because this may invoke the callback, this method must only be called on
  12358. the main event thread.
  12359. */
  12360. void handleUpdateNowIfNeeded();
  12361. /** Returns true if there's an update callback in the pipeline. */
  12362. bool isUpdatePending() const noexcept;
  12363. /** Called back to do whatever your class needs to do.
  12364. This method is called by the message thread at the next convenient time
  12365. after the triggerAsyncUpdate() method has been called.
  12366. */
  12367. virtual void handleAsyncUpdate() = 0;
  12368. private:
  12369. ReferenceCountedObjectPtr<CallbackMessage> message;
  12370. Atomic<int>& getDeliveryFlag() const noexcept;
  12371. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  12372. };
  12373. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  12374. /*** End of inlined file: juce_AsyncUpdater.h ***/
  12375. /*** Start of inlined file: juce_ListenerList.h ***/
  12376. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  12377. #define __JUCE_LISTENERLIST_JUCEHEADER__
  12378. /**
  12379. Holds a set of objects and can invoke a member function callback on each object
  12380. in the set with a single call.
  12381. Use a ListenerList to manage a set of objects which need a callback, and you
  12382. can invoke a member function by simply calling call() or callChecked().
  12383. E.g.
  12384. @code
  12385. class MyListenerType
  12386. {
  12387. public:
  12388. void myCallbackMethod (int foo, bool bar);
  12389. };
  12390. ListenerList <MyListenerType> listeners;
  12391. listeners.add (someCallbackObjects...);
  12392. // This will invoke myCallbackMethod (1234, true) on each of the objects
  12393. // in the list...
  12394. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  12395. @endcode
  12396. If you add or remove listeners from the list during one of the callbacks - i.e. while
  12397. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  12398. will be mistakenly called after they've been removed, but it may mean that some of the
  12399. listeners could be called more than once, or not at all, depending on the list's order.
  12400. Sometimes, there's a chance that invoking one of the callbacks might result in the
  12401. list itself being deleted while it's still iterating - to survive this situation, you can
  12402. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  12403. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  12404. the list will check this after each callback to determine whether it should abort the
  12405. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  12406. which can be used to check when a Component has been deleted. See also
  12407. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  12408. */
  12409. template <class ListenerClass,
  12410. class ArrayType = Array <ListenerClass*> >
  12411. class ListenerList
  12412. {
  12413. // Horrible macros required to support VC6/7..
  12414. #ifndef DOXYGEN
  12415. #if JUCE_VC8_OR_EARLIER
  12416. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  12417. #define LL_PARAM(a) Q##a& param##a
  12418. #else
  12419. #define LL_TEMPLATE(a) typename P##a
  12420. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  12421. #endif
  12422. #endif
  12423. public:
  12424. /** Creates an empty list. */
  12425. ListenerList()
  12426. {
  12427. }
  12428. /** Destructor. */
  12429. ~ListenerList()
  12430. {
  12431. }
  12432. /** Adds a listener to the list.
  12433. A listener can only be added once, so if the listener is already in the list,
  12434. this method has no effect.
  12435. @see remove
  12436. */
  12437. void add (ListenerClass* const listenerToAdd)
  12438. {
  12439. // Listeners can't be null pointers!
  12440. jassert (listenerToAdd != nullptr);
  12441. if (listenerToAdd != nullptr)
  12442. listeners.addIfNotAlreadyThere (listenerToAdd);
  12443. }
  12444. /** Removes a listener from the list.
  12445. If the listener wasn't in the list, this has no effect.
  12446. */
  12447. void remove (ListenerClass* const listenerToRemove)
  12448. {
  12449. // Listeners can't be null pointers!
  12450. jassert (listenerToRemove != nullptr);
  12451. listeners.removeValue (listenerToRemove);
  12452. }
  12453. /** Returns the number of registered listeners. */
  12454. int size() const noexcept
  12455. {
  12456. return listeners.size();
  12457. }
  12458. /** Returns true if any listeners are registered. */
  12459. bool isEmpty() const noexcept
  12460. {
  12461. return listeners.size() == 0;
  12462. }
  12463. /** Clears the list. */
  12464. void clear()
  12465. {
  12466. listeners.clear();
  12467. }
  12468. /** Returns true if the specified listener has been added to the list. */
  12469. bool contains (ListenerClass* const listener) const noexcept
  12470. {
  12471. return listeners.contains (listener);
  12472. }
  12473. /** Calls a member function on each listener in the list, with no parameters. */
  12474. void call (void (ListenerClass::*callbackFunction) ())
  12475. {
  12476. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  12477. }
  12478. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  12479. See the class description for info about writing a bail-out checker. */
  12480. template <class BailOutCheckerType>
  12481. void callChecked (const BailOutCheckerType& bailOutChecker,
  12482. void (ListenerClass::*callbackFunction) ())
  12483. {
  12484. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12485. (iter.getListener()->*callbackFunction) ();
  12486. }
  12487. /** Calls a member function on each listener in the list, with 1 parameter. */
  12488. template <LL_TEMPLATE(1)>
  12489. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  12490. {
  12491. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12492. (iter.getListener()->*callbackFunction) (param1);
  12493. }
  12494. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  12495. See the class description for info about writing a bail-out checker. */
  12496. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  12497. void callChecked (const BailOutCheckerType& bailOutChecker,
  12498. void (ListenerClass::*callbackFunction) (P1),
  12499. LL_PARAM(1))
  12500. {
  12501. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12502. (iter.getListener()->*callbackFunction) (param1);
  12503. }
  12504. /** Calls a member function on each listener in the list, with 2 parameters. */
  12505. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12506. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  12507. LL_PARAM(1), LL_PARAM(2))
  12508. {
  12509. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12510. (iter.getListener()->*callbackFunction) (param1, param2);
  12511. }
  12512. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  12513. See the class description for info about writing a bail-out checker. */
  12514. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12515. void callChecked (const BailOutCheckerType& bailOutChecker,
  12516. void (ListenerClass::*callbackFunction) (P1, P2),
  12517. LL_PARAM(1), LL_PARAM(2))
  12518. {
  12519. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12520. (iter.getListener()->*callbackFunction) (param1, param2);
  12521. }
  12522. /** Calls a member function on each listener in the list, with 3 parameters. */
  12523. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12524. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12525. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12526. {
  12527. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12528. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12529. }
  12530. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  12531. See the class description for info about writing a bail-out checker. */
  12532. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12533. void callChecked (const BailOutCheckerType& bailOutChecker,
  12534. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12535. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12536. {
  12537. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12538. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12539. }
  12540. /** Calls a member function on each listener in the list, with 4 parameters. */
  12541. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12542. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12543. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12544. {
  12545. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12546. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12547. }
  12548. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  12549. See the class description for info about writing a bail-out checker. */
  12550. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12551. void callChecked (const BailOutCheckerType& bailOutChecker,
  12552. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12553. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12554. {
  12555. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12556. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12557. }
  12558. /** Calls a member function on each listener in the list, with 5 parameters. */
  12559. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12560. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12561. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12562. {
  12563. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12564. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12565. }
  12566. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  12567. See the class description for info about writing a bail-out checker. */
  12568. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12569. void callChecked (const BailOutCheckerType& bailOutChecker,
  12570. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12571. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12572. {
  12573. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12574. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12575. }
  12576. /** A dummy bail-out checker that always returns false.
  12577. See the ListenerList notes for more info about bail-out checkers.
  12578. */
  12579. class DummyBailOutChecker
  12580. {
  12581. public:
  12582. inline bool shouldBailOut() const noexcept { return false; }
  12583. };
  12584. /** Iterates the listeners in a ListenerList. */
  12585. template <class BailOutCheckerType, class ListType>
  12586. class Iterator
  12587. {
  12588. public:
  12589. Iterator (const ListType& list_)
  12590. : list (list_), index (list_.size())
  12591. {}
  12592. ~Iterator() {}
  12593. bool next()
  12594. {
  12595. if (index <= 0)
  12596. return false;
  12597. const int listSize = list.size();
  12598. if (--index < listSize)
  12599. return true;
  12600. index = listSize - 1;
  12601. return index >= 0;
  12602. }
  12603. bool next (const BailOutCheckerType& bailOutChecker)
  12604. {
  12605. return (! bailOutChecker.shouldBailOut()) && next();
  12606. }
  12607. typename ListType::ListenerType* getListener() const noexcept
  12608. {
  12609. return list.getListeners().getUnchecked (index);
  12610. }
  12611. private:
  12612. const ListType& list;
  12613. int index;
  12614. JUCE_DECLARE_NON_COPYABLE (Iterator);
  12615. };
  12616. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  12617. typedef ListenerClass ListenerType;
  12618. const ArrayType& getListeners() const noexcept { return listeners; }
  12619. private:
  12620. ArrayType listeners;
  12621. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  12622. #undef LL_TEMPLATE
  12623. #undef LL_PARAM
  12624. };
  12625. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  12626. /*** End of inlined file: juce_ListenerList.h ***/
  12627. /**
  12628. Represents a shared variant value.
  12629. A Value object contains a reference to a var object, and can get and set its value.
  12630. Listeners can be attached to be told when the value is changed.
  12631. The Value class is a wrapper around a shared, reference-counted underlying data
  12632. object - this means that multiple Value objects can all refer to the same piece of
  12633. data, allowing all of them to be notified when any of them changes it.
  12634. When you create a Value with its default constructor, it acts as a wrapper around a
  12635. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12636. you can map the Value onto any kind of underlying data.
  12637. */
  12638. class JUCE_API Value
  12639. {
  12640. public:
  12641. /** Creates an empty Value, containing a void var. */
  12642. Value();
  12643. /** Creates a Value that refers to the same value as another one.
  12644. Note that this doesn't make a copy of the other value - both this and the other
  12645. Value will share the same underlying value, so that when either one alters it, both
  12646. will see it change.
  12647. */
  12648. Value (const Value& other);
  12649. /** Creates a Value that is set to the specified value. */
  12650. explicit Value (const var& initialValue);
  12651. /** Destructor. */
  12652. ~Value();
  12653. /** Returns the current value. */
  12654. const var getValue() const;
  12655. /** Returns the current value. */
  12656. operator const var() const;
  12657. /** Returns the value as a string.
  12658. This is alternative to writing things like "myValue.getValue().toString()".
  12659. */
  12660. const String toString() const;
  12661. /** Sets the current value.
  12662. You can also use operator= to set the value.
  12663. If there are any listeners registered, they will be notified of the
  12664. change asynchronously.
  12665. */
  12666. void setValue (const var& newValue);
  12667. /** Sets the current value.
  12668. This is the same as calling setValue().
  12669. If there are any listeners registered, they will be notified of the
  12670. change asynchronously.
  12671. */
  12672. Value& operator= (const var& newValue);
  12673. /** Makes this object refer to the same underlying ValueSource as another one.
  12674. Once this object has been connected to another one, changing either one
  12675. will update the other.
  12676. Existing listeners will still be registered after you call this method, and
  12677. they'll continue to receive messages when the new value changes.
  12678. */
  12679. void referTo (const Value& valueToReferTo);
  12680. /** Returns true if this value and the other one are references to the same value.
  12681. */
  12682. bool refersToSameSourceAs (const Value& other) const;
  12683. /** Compares two values.
  12684. This is a compare-by-value comparison, so is effectively the same as
  12685. saying (this->getValue() == other.getValue()).
  12686. */
  12687. bool operator== (const Value& other) const;
  12688. /** Compares two values.
  12689. This is a compare-by-value comparison, so is effectively the same as
  12690. saying (this->getValue() != other.getValue()).
  12691. */
  12692. bool operator!= (const Value& other) const;
  12693. /** Receives callbacks when a Value object changes.
  12694. @see Value::addListener
  12695. */
  12696. class JUCE_API Listener
  12697. {
  12698. public:
  12699. Listener() {}
  12700. virtual ~Listener() {}
  12701. /** Called when a Value object is changed.
  12702. Note that the Value object passed as a parameter may not be exactly the same
  12703. object that you registered the listener with - it might be a copy that refers
  12704. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12705. */
  12706. virtual void valueChanged (Value& value) = 0;
  12707. };
  12708. /** Adds a listener to receive callbacks when the value changes.
  12709. The listener is added to this specific Value object, and not to the shared
  12710. object that it refers to. When this object is deleted, all the listeners will
  12711. be lost, even if other references to the same Value still exist. So when you're
  12712. adding a listener, make sure that you add it to a ValueTree instance that will last
  12713. for as long as you need the listener. In general, you'd never want to add a listener
  12714. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12715. @see removeListener
  12716. */
  12717. void addListener (Listener* listener);
  12718. /** Removes a listener that was previously added with addListener(). */
  12719. void removeListener (Listener* listener);
  12720. /**
  12721. Used internally by the Value class as the base class for its shared value objects.
  12722. The Value class is essentially a reference-counted pointer to a shared instance
  12723. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12724. ValueSource classes to allow Value objects to represent your own custom data items.
  12725. */
  12726. class JUCE_API ValueSource : public ReferenceCountedObject,
  12727. public AsyncUpdater
  12728. {
  12729. public:
  12730. ValueSource();
  12731. virtual ~ValueSource();
  12732. /** Returns the current value of this object. */
  12733. virtual const var getValue() const = 0;
  12734. /** Changes the current value.
  12735. This must also trigger a change message if the value actually changes.
  12736. */
  12737. virtual void setValue (const var& newValue) = 0;
  12738. /** Delivers a change message to all the listeners that are registered with
  12739. this value.
  12740. If dispatchSynchronously is true, the method will call all the listeners
  12741. before returning; otherwise it'll dispatch a message and make the call later.
  12742. */
  12743. void sendChangeMessage (bool dispatchSynchronously);
  12744. protected:
  12745. friend class Value;
  12746. SortedSet <Value*> valuesWithListeners;
  12747. void handleAsyncUpdate();
  12748. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12749. };
  12750. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12751. explicit Value (ValueSource* valueSource);
  12752. /** Returns the ValueSource that this value is referring to. */
  12753. ValueSource& getValueSource() noexcept { return *value; }
  12754. private:
  12755. friend class ValueSource;
  12756. ReferenceCountedObjectPtr <ValueSource> value;
  12757. ListenerList <Listener> listeners;
  12758. void callListeners();
  12759. // This is disallowed to avoid confusion about whether it should
  12760. // do a by-value or by-reference copy.
  12761. Value& operator= (const Value& other);
  12762. };
  12763. /** Writes a Value to an OutputStream as a UTF8 string. */
  12764. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12765. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12766. typedef Value::Listener ValueListener;
  12767. #endif // __JUCE_VALUE_JUCEHEADER__
  12768. /*** End of inlined file: juce_Value.h ***/
  12769. #endif
  12770. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12771. /*** Start of inlined file: juce_ValueTree.h ***/
  12772. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12773. #define __JUCE_VALUETREE_JUCEHEADER__
  12774. /*** Start of inlined file: juce_UndoManager.h ***/
  12775. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12776. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12777. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12778. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12779. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12780. /*** Start of inlined file: juce_ChangeListener.h ***/
  12781. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12782. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12783. class ChangeBroadcaster;
  12784. /**
  12785. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12786. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12787. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12788. ChangeListener is used to receive these callbacks.
  12789. Note that the major difference between an ActionListener and a ChangeListener
  12790. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12791. callbacks, but ActionListeners perform one callback for every event posted.
  12792. @see ChangeBroadcaster, ActionListener
  12793. */
  12794. class JUCE_API ChangeListener
  12795. {
  12796. public:
  12797. /** Destructor. */
  12798. virtual ~ChangeListener() {}
  12799. /** Your subclass should implement this method to receive the callback.
  12800. @param source the ChangeBroadcaster that triggered the callback.
  12801. */
  12802. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12803. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12804. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12805. private: virtual int changeListenerCallback (void*) { return 0; }
  12806. #endif
  12807. };
  12808. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12809. /*** End of inlined file: juce_ChangeListener.h ***/
  12810. /**
  12811. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12812. @see ChangeListener
  12813. */
  12814. class JUCE_API ChangeBroadcaster
  12815. {
  12816. public:
  12817. /** Creates an ChangeBroadcaster. */
  12818. ChangeBroadcaster() noexcept;
  12819. /** Destructor. */
  12820. virtual ~ChangeBroadcaster();
  12821. /** Registers a listener to receive change callbacks from this broadcaster.
  12822. Trying to add a listener that's already on the list will have no effect.
  12823. */
  12824. void addChangeListener (ChangeListener* listener);
  12825. /** Unregisters a listener from the list.
  12826. If the listener isn't on the list, this won't have any effect.
  12827. */
  12828. void removeChangeListener (ChangeListener* listener);
  12829. /** Removes all listeners from the list. */
  12830. void removeAllChangeListeners();
  12831. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12832. The message will be delivered asynchronously by the main message thread, so this
  12833. method will return immediately. To call the listeners synchronously use
  12834. sendSynchronousChangeMessage().
  12835. */
  12836. void sendChangeMessage();
  12837. /** Sends a synchronous change message to all the registered listeners.
  12838. This will immediately call all the listeners that are registered. For thread-safety
  12839. reasons, you must only call this method on the main message thread.
  12840. @see dispatchPendingMessages
  12841. */
  12842. void sendSynchronousChangeMessage();
  12843. /** If a change message has been sent but not yet dispatched, this will call
  12844. sendSynchronousChangeMessage() to make the callback immediately.
  12845. For thread-safety reasons, you must only call this method on the main message thread.
  12846. */
  12847. void dispatchPendingMessages();
  12848. private:
  12849. class ChangeBroadcasterCallback : public AsyncUpdater
  12850. {
  12851. public:
  12852. ChangeBroadcasterCallback();
  12853. void handleAsyncUpdate();
  12854. ChangeBroadcaster* owner;
  12855. };
  12856. friend class ChangeBroadcasterCallback;
  12857. ChangeBroadcasterCallback callback;
  12858. ListenerList <ChangeListener> changeListeners;
  12859. void callListeners();
  12860. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  12861. };
  12862. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12863. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  12864. /*** Start of inlined file: juce_UndoableAction.h ***/
  12865. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  12866. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  12867. /**
  12868. Used by the UndoManager class to store an action which can be done
  12869. and undone.
  12870. @see UndoManager
  12871. */
  12872. class JUCE_API UndoableAction
  12873. {
  12874. protected:
  12875. /** Creates an action. */
  12876. UndoableAction() noexcept {}
  12877. public:
  12878. /** Destructor. */
  12879. virtual ~UndoableAction() {}
  12880. /** Overridden by a subclass to perform the action.
  12881. This method is called by the UndoManager, and shouldn't be used directly by
  12882. applications.
  12883. Be careful not to make any calls in a perform() method that could call
  12884. recursively back into the UndoManager::perform() method
  12885. @returns true if the action could be performed.
  12886. @see UndoManager::perform
  12887. */
  12888. virtual bool perform() = 0;
  12889. /** Overridden by a subclass to undo the action.
  12890. This method is called by the UndoManager, and shouldn't be used directly by
  12891. applications.
  12892. Be careful not to make any calls in an undo() method that could call
  12893. recursively back into the UndoManager::perform() method
  12894. @returns true if the action could be undone without any errors.
  12895. @see UndoManager::perform
  12896. */
  12897. virtual bool undo() = 0;
  12898. /** Returns a value to indicate how much memory this object takes up.
  12899. Because the UndoManager keeps a list of UndoableActions, this is used
  12900. to work out how much space each one will take up, so that the UndoManager
  12901. can work out how many to keep.
  12902. The default value returned here is 10 - units are arbitrary and
  12903. don't have to be accurate.
  12904. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  12905. UndoManager::setMaxNumberOfStoredUnits
  12906. */
  12907. virtual int getSizeInUnits() { return 10; }
  12908. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  12909. If possible, this method should create and return a single action that does the same job as
  12910. this one followed by the supplied action.
  12911. If it's not possible to merge the two actions, the method should return zero.
  12912. */
  12913. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return nullptr; }
  12914. };
  12915. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  12916. /*** End of inlined file: juce_UndoableAction.h ***/
  12917. /**
  12918. Manages a list of undo/redo commands.
  12919. An UndoManager object keeps a list of past actions and can use these actions
  12920. to move backwards and forwards through an undo history.
  12921. To use it, create subclasses of UndoableAction which perform all the
  12922. actions you need, then when you need to actually perform an action, create one
  12923. and pass it to the UndoManager's perform() method.
  12924. The manager also uses the concept of 'transactions' to group the actions
  12925. together - all actions performed between calls to beginNewTransaction() are
  12926. grouped together and are all undone/redone as a group.
  12927. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  12928. when actions are performed or undone.
  12929. @see UndoableAction
  12930. */
  12931. class JUCE_API UndoManager : public ChangeBroadcaster
  12932. {
  12933. public:
  12934. /** Creates an UndoManager.
  12935. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12936. to indicate how much storage it takes up
  12937. (UndoableAction::getSizeInUnits()), so this
  12938. lets you specify the maximum total number of
  12939. units that the undomanager is allowed to
  12940. keep in memory before letting the older actions
  12941. drop off the end of the list.
  12942. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12943. that will be kept, even if this involves exceeding
  12944. the amount of space specified in maxNumberOfUnitsToKeep
  12945. */
  12946. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  12947. int minimumTransactionsToKeep = 30);
  12948. /** Destructor. */
  12949. ~UndoManager();
  12950. /** Deletes all stored actions in the list. */
  12951. void clearUndoHistory();
  12952. /** Returns the current amount of space to use for storing UndoableAction objects.
  12953. @see setMaxNumberOfStoredUnits
  12954. */
  12955. int getNumberOfUnitsTakenUpByStoredCommands() const;
  12956. /** Sets the amount of space that can be used for storing UndoableAction objects.
  12957. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12958. to indicate how much storage it takes up
  12959. (UndoableAction::getSizeInUnits()), so this
  12960. lets you specify the maximum total number of
  12961. units that the undomanager is allowed to
  12962. keep in memory before letting the older actions
  12963. drop off the end of the list.
  12964. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12965. that will be kept, even if this involves exceeding
  12966. the amount of space specified in maxNumberOfUnitsToKeep
  12967. @see getNumberOfUnitsTakenUpByStoredCommands
  12968. */
  12969. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  12970. int minimumTransactionsToKeep);
  12971. /** Performs an action and adds it to the undo history list.
  12972. @param action the action to perform - this will be deleted by the UndoManager
  12973. when no longer needed
  12974. @param actionName if this string is non-empty, the current transaction will be
  12975. given this name; if it's empty, the current transaction name will
  12976. be left unchanged. See setCurrentTransactionName()
  12977. @returns true if the command succeeds - see UndoableAction::perform
  12978. @see beginNewTransaction
  12979. */
  12980. bool perform (UndoableAction* action,
  12981. const String& actionName = String::empty);
  12982. /** Starts a new group of actions that together will be treated as a single transaction.
  12983. All actions that are passed to the perform() method between calls to this
  12984. method are grouped together and undone/redone together by a single call to
  12985. undo() or redo().
  12986. @param actionName a description of the transaction that is about to be
  12987. performed
  12988. */
  12989. void beginNewTransaction (const String& actionName = String::empty);
  12990. /** Changes the name stored for the current transaction.
  12991. Each transaction is given a name when the beginNewTransaction() method is
  12992. called, but this can be used to change that name without starting a new
  12993. transaction.
  12994. */
  12995. void setCurrentTransactionName (const String& newName);
  12996. /** Returns true if there's at least one action in the list to undo.
  12997. @see getUndoDescription, undo, canRedo
  12998. */
  12999. bool canUndo() const;
  13000. /** Returns the description of the transaction that would be next to get undone.
  13001. The description returned is the one that was passed into beginNewTransaction
  13002. before the set of actions was performed.
  13003. @see undo
  13004. */
  13005. const String getUndoDescription() const;
  13006. /** Tries to roll-back the last transaction.
  13007. @returns true if the transaction can be undone, and false if it fails, or
  13008. if there aren't any transactions to undo
  13009. */
  13010. bool undo();
  13011. /** Tries to roll-back any actions that were added to the current transaction.
  13012. This will perform an undo() only if there are some actions in the undo list
  13013. that were added after the last call to beginNewTransaction().
  13014. This is useful because it lets you call beginNewTransaction(), then
  13015. perform an operation which may or may not actually perform some actions, and
  13016. then call this method to get rid of any actions that might have been done
  13017. without it rolling back the previous transaction if nothing was actually
  13018. done.
  13019. @returns true if any actions were undone.
  13020. */
  13021. bool undoCurrentTransactionOnly();
  13022. /** Returns a list of the UndoableAction objects that have been performed during the
  13023. transaction that is currently open.
  13024. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  13025. were to be called now.
  13026. The first item in the list is the earliest action performed.
  13027. */
  13028. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  13029. /** Returns the number of UndoableAction objects that have been performed during the
  13030. transaction that is currently open.
  13031. @see getActionsInCurrentTransaction
  13032. */
  13033. int getNumActionsInCurrentTransaction() const;
  13034. /** Returns true if there's at least one action in the list to redo.
  13035. @see getRedoDescription, redo, canUndo
  13036. */
  13037. bool canRedo() const;
  13038. /** Returns the description of the transaction that would be next to get redone.
  13039. The description returned is the one that was passed into beginNewTransaction
  13040. before the set of actions was performed.
  13041. @see redo
  13042. */
  13043. const String getRedoDescription() const;
  13044. /** Tries to redo the last transaction that was undone.
  13045. @returns true if the transaction can be redone, and false if it fails, or
  13046. if there aren't any transactions to redo
  13047. */
  13048. bool redo();
  13049. private:
  13050. OwnedArray <OwnedArray <UndoableAction> > transactions;
  13051. StringArray transactionNames;
  13052. String currentTransactionName;
  13053. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  13054. bool newTransaction, reentrancyCheck;
  13055. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  13056. };
  13057. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  13058. /*** End of inlined file: juce_UndoManager.h ***/
  13059. /**
  13060. A powerful tree structure that can be used to hold free-form data, and which can
  13061. handle its own undo and redo behaviour.
  13062. A ValueTree contains a list of named properties as var objects, and also holds
  13063. any number of sub-trees.
  13064. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  13065. they're simply a lightweight reference to a shared data container. Creating a copy
  13066. of another ValueTree simply creates a new reference to the same underlying object - to
  13067. make a separate, deep copy of a tree you should explicitly call createCopy().
  13068. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  13069. and much of the structure of a ValueTree is similar to an XmlElement tree.
  13070. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  13071. contain text elements, the conversion works well and makes a good serialisation
  13072. format. They can also be serialised to a binary format, which is very fast and compact.
  13073. All the methods that change data take an optional UndoManager, which will be used
  13074. to track any changes to the object. For this to work, you have to be careful to
  13075. consistently always use the same UndoManager for all operations to any node inside
  13076. the tree.
  13077. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  13078. one tree to another, be careful to always remove it first, before adding it. This
  13079. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  13080. assertions if you try to do anything dangerous, but there are still plenty of ways it
  13081. could go wrong.
  13082. Listeners can be added to a ValueTree to be told when properies change and when
  13083. nodes are added or removed.
  13084. @see var, XmlElement
  13085. */
  13086. class JUCE_API ValueTree
  13087. {
  13088. public:
  13089. /** Creates an empty, invalid ValueTree.
  13090. A ValueTree that is created with this constructor can't actually be used for anything,
  13091. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  13092. To create a real one, use the constructor that takes a string.
  13093. @see ValueTree::invalid
  13094. */
  13095. ValueTree() noexcept;
  13096. /** Creates an empty ValueTree with the given type name.
  13097. Like an XmlElement, each ValueTree node has a type, which you can access with
  13098. getType() and hasType().
  13099. */
  13100. explicit ValueTree (const Identifier& type);
  13101. /** Creates a reference to another ValueTree. */
  13102. ValueTree (const ValueTree& other);
  13103. /** Makes this object reference another node. */
  13104. ValueTree& operator= (const ValueTree& other);
  13105. /** Destructor. */
  13106. ~ValueTree();
  13107. /** Returns true if both this and the other tree node refer to the same underlying structure.
  13108. Note that this isn't a value comparison - two independently-created trees which
  13109. contain identical data are not considered equal.
  13110. */
  13111. bool operator== (const ValueTree& other) const noexcept;
  13112. /** Returns true if this and the other node refer to different underlying structures.
  13113. Note that this isn't a value comparison - two independently-created trees which
  13114. contain identical data are not considered equal.
  13115. */
  13116. bool operator!= (const ValueTree& other) const noexcept;
  13117. /** Performs a deep comparison between the properties and children of two trees.
  13118. If all the properties and children of the two trees are the same (recursively), this
  13119. returns true.
  13120. The normal operator==() only checks whether two trees refer to the same shared data
  13121. structure, so use this method if you need to do a proper value comparison.
  13122. */
  13123. bool isEquivalentTo (const ValueTree& other) const;
  13124. /** Returns true if this node refers to some valid data.
  13125. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  13126. call to getChild().
  13127. */
  13128. bool isValid() const { return object != nullptr; }
  13129. /** Returns a deep copy of this tree and all its sub-nodes. */
  13130. ValueTree createCopy() const;
  13131. /** Returns the type of this node.
  13132. The type is specified when the ValueTree is created.
  13133. @see hasType
  13134. */
  13135. const Identifier getType() const;
  13136. /** Returns true if the node has this type.
  13137. The comparison is case-sensitive.
  13138. */
  13139. bool hasType (const Identifier& typeName) const;
  13140. /** Returns the value of a named property.
  13141. If no such property has been set, this will return a void variant.
  13142. You can also use operator[] to get a property.
  13143. @see var, setProperty, hasProperty
  13144. */
  13145. const var& getProperty (const Identifier& name) const;
  13146. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  13147. If no such property has been set, this will return the value of defaultReturnValue.
  13148. You can also use operator[] and getProperty to get a property.
  13149. @see var, getProperty, setProperty, hasProperty
  13150. */
  13151. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13152. /** Returns the value of a named property.
  13153. If no such property has been set, this will return a void variant. This is the same as
  13154. calling getProperty().
  13155. @see getProperty
  13156. */
  13157. const var& operator[] (const Identifier& name) const;
  13158. /** Changes a named property of the node.
  13159. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13160. so that this change can be undone.
  13161. @see var, getProperty, removeProperty
  13162. */
  13163. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  13164. /** Returns true if the node contains a named property. */
  13165. bool hasProperty (const Identifier& name) const;
  13166. /** Removes a property from the node.
  13167. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13168. so that this change can be undone.
  13169. */
  13170. void removeProperty (const Identifier& name, UndoManager* undoManager);
  13171. /** Removes all properties from the node.
  13172. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13173. so that this change can be undone.
  13174. */
  13175. void removeAllProperties (UndoManager* undoManager);
  13176. /** Returns the total number of properties that the node contains.
  13177. @see getProperty.
  13178. */
  13179. int getNumProperties() const;
  13180. /** Returns the identifier of the property with a given index.
  13181. @see getNumProperties
  13182. */
  13183. const Identifier getPropertyName (int index) const;
  13184. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  13185. The Value object will maintain a reference to this tree, and will use the undo manager when
  13186. it needs to change the value. Attaching a Value::Listener to the value object will provide
  13187. callbacks whenever the property changes.
  13188. */
  13189. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  13190. /** Returns the number of child nodes belonging to this one.
  13191. @see getChild
  13192. */
  13193. int getNumChildren() const;
  13194. /** Returns one of this node's child nodes.
  13195. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  13196. whether a node is valid).
  13197. */
  13198. ValueTree getChild (int index) const;
  13199. /** Returns the first child node with the speficied type name.
  13200. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13201. whether a node is valid).
  13202. @see getOrCreateChildWithName
  13203. */
  13204. ValueTree getChildWithName (const Identifier& type) const;
  13205. /** Returns the first child node with the speficied type name, creating and adding
  13206. a child with this name if there wasn't already one there.
  13207. The only time this will return an invalid object is when the object that you're calling
  13208. the method on is itself invalid.
  13209. @see getChildWithName
  13210. */
  13211. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13212. /** Looks for the first child node that has the speficied property value.
  13213. This will scan the child nodes in order, until it finds one that has property that matches
  13214. the specified value.
  13215. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13216. whether a node is valid).
  13217. */
  13218. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13219. /** Adds a child to this node.
  13220. Make sure that the child is removed from any former parent node before calling this, or
  13221. you'll hit an assertion.
  13222. If the index is < 0 or greater than the current number of child nodes, the new node will
  13223. be added at the end of the list.
  13224. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13225. so that this change can be undone.
  13226. */
  13227. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  13228. /** Removes the specified child from this node's child-list.
  13229. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13230. so that this change can be undone.
  13231. */
  13232. void removeChild (const ValueTree& child, UndoManager* undoManager);
  13233. /** Removes a child from this node's child-list.
  13234. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13235. so that this change can be undone.
  13236. */
  13237. void removeChild (int childIndex, UndoManager* undoManager);
  13238. /** Removes all child-nodes from this node.
  13239. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13240. so that this change can be undone.
  13241. */
  13242. void removeAllChildren (UndoManager* undoManager);
  13243. /** Moves one of the children to a different index.
  13244. This will move the child to a specified index, shuffling along any intervening
  13245. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  13246. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  13247. @param currentIndex the index of the item to be moved. If this isn't a
  13248. valid index, then nothing will be done
  13249. @param newIndex the index at which you'd like this item to end up. If this
  13250. is less than zero, the value will be moved to the end
  13251. of the list
  13252. @param undoManager the optional UndoManager to use to store this transaction
  13253. */
  13254. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  13255. /** Returns true if this node is anywhere below the specified parent node.
  13256. This returns true if the node is a child-of-a-child, as well as a direct child.
  13257. */
  13258. bool isAChildOf (const ValueTree& possibleParent) const;
  13259. /** Returns the index of a child item in this parent.
  13260. If the child isn't found, this returns -1.
  13261. */
  13262. int indexOf (const ValueTree& child) const;
  13263. /** Returns the parent node that contains this one.
  13264. If the node has no parent, this will return an invalid node. (See isValid() to find out
  13265. whether a node is valid).
  13266. */
  13267. ValueTree getParent() const;
  13268. /** Returns one of this node's siblings in its parent's child list.
  13269. The delta specifies how far to move through the list, so a value of 1 would return the node
  13270. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  13271. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  13272. */
  13273. ValueTree getSibling (int delta) const;
  13274. /** Creates an XmlElement that holds a complete image of this node and all its children.
  13275. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  13276. be used to recreate a similar node by calling fromXml()
  13277. @see fromXml
  13278. */
  13279. XmlElement* createXml() const;
  13280. /** Tries to recreate a node from its XML representation.
  13281. This isn't designed to cope with random XML data - for a sensible result, it should only
  13282. be fed XML that was created by the createXml() method.
  13283. */
  13284. static ValueTree fromXml (const XmlElement& xml);
  13285. /** Stores this tree (and all its children) in a binary format.
  13286. Once written, the data can be read back with readFromStream().
  13287. It's much faster to load/save your tree in binary form than as XML, but
  13288. obviously isn't human-readable.
  13289. */
  13290. void writeToStream (OutputStream& output);
  13291. /** Reloads a tree from a stream that was written with writeToStream(). */
  13292. static ValueTree readFromStream (InputStream& input);
  13293. /** Reloads a tree from a data block that was written with writeToStream(). */
  13294. static ValueTree readFromData (const void* data, size_t numBytes);
  13295. /** Listener class for events that happen to a ValueTree.
  13296. To get events from a ValueTree, make your class implement this interface, and use
  13297. ValueTree::addListener() and ValueTree::removeListener() to register it.
  13298. */
  13299. class JUCE_API Listener
  13300. {
  13301. public:
  13302. /** Destructor. */
  13303. virtual ~Listener() {}
  13304. /** This method is called when a property of this node (or of one of its sub-nodes) has
  13305. changed.
  13306. The tree parameter indicates which tree has had its property changed, and the property
  13307. parameter indicates the property.
  13308. Note that when you register a listener to a tree, it will receive this callback for
  13309. property changes in that tree, and also for any of its children, (recursively, at any depth).
  13310. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13311. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  13312. */
  13313. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  13314. const Identifier& property) = 0;
  13315. /** This method is called when a child sub-tree is added.
  13316. Note that when you register a listener to a tree, it will receive this callback for
  13317. child changes in both that tree and any of its children, (recursively, at any depth).
  13318. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13319. just check the parentTree parameter to make sure it's the one that you're interested in.
  13320. */
  13321. virtual void valueTreeChildAdded (ValueTree& parentTree,
  13322. ValueTree& childWhichHasBeenAdded) = 0;
  13323. /** This method is called when a child sub-tree is removed.
  13324. Note that when you register a listener to a tree, it will receive this callback for
  13325. child changes in both that tree and any of its children, (recursively, at any depth).
  13326. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13327. just check the parentTree parameter to make sure it's the one that you're interested in.
  13328. */
  13329. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  13330. ValueTree& childWhichHasBeenRemoved) = 0;
  13331. /** This method is called when a tree's children have been re-shuffled.
  13332. Note that when you register a listener to a tree, it will receive this callback for
  13333. child changes in both that tree and any of its children, (recursively, at any depth).
  13334. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13335. just check the parameter to make sure it's the tree that you're interested in.
  13336. */
  13337. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  13338. /** This method is called when a tree has been added or removed from a parent node.
  13339. This callback happens when the tree to which the listener was registered is added or
  13340. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  13341. the listener is registered, and not to any of its children.
  13342. */
  13343. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  13344. };
  13345. /** Adds a listener to receive callbacks when this node is changed.
  13346. The listener is added to this specific ValueTree object, and not to the shared
  13347. object that it refers to. When this object is deleted, all the listeners will
  13348. be lost, even if other references to the same ValueTree still exist. And if you
  13349. use the operator= to make this refer to a different ValueTree, any listeners will
  13350. begin listening to changes to the new tree instead of the old one.
  13351. When you're adding a listener, make sure that you add it to a ValueTree instance that
  13352. will last for as long as you need the listener. In general, you'd never want to add a
  13353. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  13354. @see removeListener
  13355. */
  13356. void addListener (Listener* listener);
  13357. /** Removes a listener that was previously added with addListener(). */
  13358. void removeListener (Listener* listener);
  13359. /** This method uses a comparator object to sort the tree's children into order.
  13360. The object provided must have a method of the form:
  13361. @code
  13362. int compareElements (const ValueTree& first, const ValueTree& second);
  13363. @endcode
  13364. ..and this method must return:
  13365. - a value of < 0 if the first comes before the second
  13366. - a value of 0 if the two objects are equivalent
  13367. - a value of > 0 if the second comes before the first
  13368. To improve performance, the compareElements() method can be declared as static or const.
  13369. @param comparator the comparator to use for comparing elements.
  13370. @param undoManager optional UndoManager for storing the changes
  13371. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  13372. equivalent will be kept in the order in which they currently appear in the array.
  13373. This is slower to perform, but may be important in some cases. If it's false, a
  13374. faster algorithm is used, but equivalent elements may be rearranged.
  13375. */
  13376. template <typename ElementComparator>
  13377. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  13378. {
  13379. if (object != nullptr)
  13380. {
  13381. ReferenceCountedArray <SharedObject> sortedList (object->children);
  13382. ComparatorAdapter <ElementComparator> adapter (comparator);
  13383. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  13384. object->reorderChildren (sortedList, undoManager);
  13385. }
  13386. }
  13387. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  13388. This invalid object is equivalent to ValueTree created with its default constructor.
  13389. */
  13390. static const ValueTree invalid;
  13391. private:
  13392. class SetPropertyAction;
  13393. friend class SetPropertyAction;
  13394. class AddOrRemoveChildAction;
  13395. friend class AddOrRemoveChildAction;
  13396. class MoveChildAction;
  13397. friend class MoveChildAction;
  13398. class JUCE_API SharedObject : public ReferenceCountedObject
  13399. {
  13400. public:
  13401. explicit SharedObject (const Identifier& type);
  13402. SharedObject (const SharedObject& other);
  13403. ~SharedObject();
  13404. const Identifier type;
  13405. NamedValueSet properties;
  13406. ReferenceCountedArray <SharedObject> children;
  13407. SortedSet <ValueTree*> valueTreesWithListeners;
  13408. SharedObject* parent;
  13409. void sendPropertyChangeMessage (const Identifier& property);
  13410. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  13411. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  13412. void sendChildAddedMessage (ValueTree child);
  13413. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  13414. void sendChildRemovedMessage (ValueTree child);
  13415. void sendChildOrderChangedMessage (ValueTree& parent);
  13416. void sendChildOrderChangedMessage();
  13417. void sendParentChangeMessage();
  13418. const var& getProperty (const Identifier& name) const;
  13419. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13420. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  13421. bool hasProperty (const Identifier& name) const;
  13422. void removeProperty (const Identifier& name, UndoManager*);
  13423. void removeAllProperties (UndoManager*);
  13424. bool isAChildOf (const SharedObject* possibleParent) const;
  13425. int indexOf (const ValueTree& child) const;
  13426. ValueTree getChildWithName (const Identifier& type) const;
  13427. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13428. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13429. void addChild (SharedObject* child, int index, UndoManager*);
  13430. void removeChild (int childIndex, UndoManager*);
  13431. void removeAllChildren (UndoManager*);
  13432. void moveChild (int currentIndex, int newIndex, UndoManager*);
  13433. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  13434. bool isEquivalentTo (const SharedObject& other) const;
  13435. XmlElement* createXml() const;
  13436. private:
  13437. SharedObject& operator= (const SharedObject&);
  13438. JUCE_LEAK_DETECTOR (SharedObject);
  13439. };
  13440. template <typename ElementComparator>
  13441. class ComparatorAdapter
  13442. {
  13443. public:
  13444. ComparatorAdapter (ElementComparator& comparator_) noexcept : comparator (comparator_) {}
  13445. int compareElements (SharedObject* const first, SharedObject* const second)
  13446. {
  13447. return comparator.compareElements (ValueTree (first), ValueTree (second));
  13448. }
  13449. private:
  13450. ElementComparator& comparator;
  13451. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  13452. };
  13453. friend class SharedObject;
  13454. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  13455. SharedObjectPtr object;
  13456. ListenerList <Listener> listeners;
  13457. #if JUCE_MSVC && ! DOXYGEN
  13458. public: // (workaround for VC6)
  13459. #endif
  13460. explicit ValueTree (SharedObject*);
  13461. };
  13462. #endif // __JUCE_VALUETREE_JUCEHEADER__
  13463. /*** End of inlined file: juce_ValueTree.h ***/
  13464. #endif
  13465. #ifndef __JUCE_VARIANT_JUCEHEADER__
  13466. #endif
  13467. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13468. /*** Start of inlined file: juce_FileLogger.h ***/
  13469. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13470. #define __JUCE_FILELOGGER_JUCEHEADER__
  13471. /**
  13472. A simple implemenation of a Logger that writes to a file.
  13473. @see Logger
  13474. */
  13475. class JUCE_API FileLogger : public Logger
  13476. {
  13477. public:
  13478. /** Creates a FileLogger for a given file.
  13479. @param fileToWriteTo the file that to use - new messages will be appended
  13480. to the file. If the file doesn't exist, it will be created,
  13481. along with any parent directories that are needed.
  13482. @param welcomeMessage when opened, the logger will write a header to the log, along
  13483. with the current date and time, and this welcome message
  13484. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  13485. but is larger than this number of bytes, then the start of the
  13486. file will be truncated to keep the size down. This prevents a log
  13487. file getting ridiculously large over time. The file will be truncated
  13488. at a new-line boundary. If this value is less than zero, no size limit
  13489. will be imposed; if it's zero, the file will always be deleted. Note that
  13490. the size is only checked once when this object is created - any logging
  13491. that is done later will be appended without any checking
  13492. */
  13493. FileLogger (const File& fileToWriteTo,
  13494. const String& welcomeMessage,
  13495. const int maxInitialFileSizeBytes = 128 * 1024);
  13496. /** Destructor. */
  13497. ~FileLogger();
  13498. void logMessage (const String& message);
  13499. const File getLogFile() const { return logFile; }
  13500. /** Helper function to create a log file in the correct place for this platform.
  13501. On Windows this will return a logger with a path such as:
  13502. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  13503. On the Mac it'll create something like:
  13504. ~/Library/Logs/[logFileName]
  13505. The method might return 0 if the file can't be created for some reason.
  13506. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  13507. it's best to use the something like the name of your application here.
  13508. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  13509. call it "log.txt" because if it goes in a directory with logs
  13510. from other applications (as it will do on the Mac) then no-one
  13511. will know which one is yours!
  13512. @param welcomeMessage a message that will be written to the log when it's opened.
  13513. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  13514. */
  13515. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  13516. const String& logFileName,
  13517. const String& welcomeMessage,
  13518. const int maxInitialFileSizeBytes = 128 * 1024);
  13519. private:
  13520. File logFile;
  13521. CriticalSection logLock;
  13522. void trimFileSize (int maxFileSizeBytes) const;
  13523. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  13524. };
  13525. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  13526. /*** End of inlined file: juce_FileLogger.h ***/
  13527. #endif
  13528. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13529. /*** Start of inlined file: juce_Initialisation.h ***/
  13530. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13531. #define __JUCE_INITIALISATION_JUCEHEADER__
  13532. /** Initialises Juce's GUI classes.
  13533. If you're embedding Juce into an application that uses its own event-loop rather
  13534. than using the START_JUCE_APPLICATION macro, call this function before making any
  13535. Juce calls, to make sure things are initialised correctly.
  13536. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13537. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13538. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  13539. */
  13540. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  13541. /** Clears up any static data being used by Juce's GUI classes.
  13542. If you're embedding Juce into an application that uses its own event-loop rather
  13543. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  13544. code to clean up any juce objects that might be lying around.
  13545. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  13546. */
  13547. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  13548. /** Initialises the core parts of Juce.
  13549. If you're embedding Juce into either a command-line program, call this function
  13550. at the start of your main() function to make sure that Juce is initialised correctly.
  13551. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13552. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13553. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  13554. */
  13555. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  13556. /** Clears up any static data being used by Juce's non-gui core classes.
  13557. If you're embedding Juce into either a command-line program, call this function
  13558. at the end of your main() function if you want to make sure any Juce objects are
  13559. cleaned up correctly.
  13560. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  13561. */
  13562. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  13563. /** A utility object that helps you initialise and shutdown Juce correctly
  13564. using an RAII pattern.
  13565. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  13566. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  13567. make sure that these functions are matched correctly.
  13568. This class is particularly handy to use at the beginning of a console app's
  13569. main() function, because it'll take care of shutting down whenever you return
  13570. from the main() call.
  13571. @see ScopedJuceInitialiser_GUI
  13572. */
  13573. class ScopedJuceInitialiser_NonGUI
  13574. {
  13575. public:
  13576. /** The constructor simply calls initialiseJuce_NonGUI(). */
  13577. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  13578. /** The destructor simply calls shutdownJuce_NonGUI(). */
  13579. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  13580. };
  13581. /** A utility object that helps you initialise and shutdown Juce correctly
  13582. using an RAII pattern.
  13583. When an instance of this class is created, it calls initialiseJuce_GUI(),
  13584. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  13585. make sure that these functions are matched correctly.
  13586. This class is particularly handy to use at the beginning of a console app's
  13587. main() function, because it'll take care of shutting down whenever you return
  13588. from the main() call.
  13589. @see ScopedJuceInitialiser_NonGUI
  13590. */
  13591. class ScopedJuceInitialiser_GUI
  13592. {
  13593. public:
  13594. /** The constructor simply calls initialiseJuce_GUI(). */
  13595. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  13596. /** The destructor simply calls shutdownJuce_GUI(). */
  13597. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  13598. };
  13599. /*
  13600. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  13601. AppSubClass is the name of a class derived from JUCEApplication.
  13602. See the JUCEApplication class documentation (juce_Application.h) for more details.
  13603. */
  13604. #if JUCE_ANDROID
  13605. #define START_JUCE_APPLICATION(AppClass) \
  13606. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  13607. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  13608. #define START_JUCE_APPLICATION(AppClass) \
  13609. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13610. int main (int argc, char* argv[]) \
  13611. { \
  13612. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13613. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  13614. }
  13615. #elif JUCE_WINDOWS
  13616. #ifdef _CONSOLE
  13617. #define START_JUCE_APPLICATION(AppClass) \
  13618. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13619. int main (int, char* argv[]) \
  13620. { \
  13621. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13622. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13623. }
  13624. #elif ! defined (_AFXDLL)
  13625. #ifdef _WINDOWS_
  13626. #define START_JUCE_APPLICATION(AppClass) \
  13627. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13628. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  13629. { \
  13630. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13631. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13632. }
  13633. #else
  13634. #define START_JUCE_APPLICATION(AppClass) \
  13635. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13636. int __stdcall WinMain (int, int, const char*, int) \
  13637. { \
  13638. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13639. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13640. }
  13641. #endif
  13642. #endif
  13643. #endif
  13644. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13645. /*** End of inlined file: juce_Initialisation.h ***/
  13646. #endif
  13647. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13648. #endif
  13649. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13650. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13651. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13652. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13653. /** A timer for measuring performance of code and dumping the results to a file.
  13654. e.g. @code
  13655. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13656. for (;;)
  13657. {
  13658. pc.start();
  13659. doSomethingFishy();
  13660. pc.stop();
  13661. }
  13662. @endcode
  13663. In this example, the time of each period between calling start/stop will be
  13664. measured and averaged over 50 runs, and the results printed to a file
  13665. every 50 times round the loop.
  13666. */
  13667. class JUCE_API PerformanceCounter
  13668. {
  13669. public:
  13670. /** Creates a PerformanceCounter object.
  13671. @param counterName the name used when printing out the statistics
  13672. @param runsPerPrintout the number of start/stop iterations before calling
  13673. printStatistics()
  13674. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13675. the results are just written to the debugger output
  13676. */
  13677. PerformanceCounter (const String& counterName,
  13678. int runsPerPrintout = 100,
  13679. const File& loggingFile = File::nonexistent);
  13680. /** Destructor. */
  13681. ~PerformanceCounter();
  13682. /** Starts timing.
  13683. @see stop
  13684. */
  13685. void start();
  13686. /** Stops timing and prints out the results.
  13687. The number of iterations before doing a printout of the
  13688. results is set in the constructor.
  13689. @see start
  13690. */
  13691. void stop();
  13692. /** Dumps the current metrics to the debugger output and to a file.
  13693. As well as using Logger::outputDebugString to print the results,
  13694. this will write then to the file specified in the constructor (if
  13695. this was valid).
  13696. */
  13697. void printStatistics();
  13698. private:
  13699. String name;
  13700. int numRuns, runsPerPrint;
  13701. double totalTime;
  13702. int64 started;
  13703. File outputFile;
  13704. };
  13705. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13706. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13707. #endif
  13708. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13709. #endif
  13710. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13711. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13712. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13713. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13714. /**
  13715. A collection of miscellaneous platform-specific utilities.
  13716. */
  13717. class JUCE_API PlatformUtilities
  13718. {
  13719. public:
  13720. /** Plays the operating system's default alert 'beep' sound. */
  13721. static void beep();
  13722. /** Tries to launch the system's default reader for a given file or URL. */
  13723. static bool openDocument (const String& documentURL, const String& parameters);
  13724. /** Tries to launch the system's default email app to let the user create an email.
  13725. */
  13726. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13727. const String& emailSubject,
  13728. const String& bodyText,
  13729. const StringArray& filesToAttach);
  13730. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13731. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13732. static const String cfStringToJuceString (CFStringRef cfString);
  13733. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13734. static CFStringRef juceStringToCFString (const String& s);
  13735. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13736. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13737. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13738. static const String makePathFromFSRef (FSRef* file);
  13739. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13740. their precomposed equivalents.
  13741. */
  13742. static const String convertToPrecomposedUnicode (const String& s);
  13743. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13744. static OSType getTypeOfFile (const String& filename);
  13745. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13746. static bool isBundle (const String& filename);
  13747. /** MAC ONLY - Adds an item to the dock */
  13748. static void addItemToDock (const File& file);
  13749. /** MAC ONLY - Returns the current OS version number.
  13750. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13751. */
  13752. static int getOSXMinorVersionNumber();
  13753. #endif
  13754. #if JUCE_WINDOWS || DOXYGEN
  13755. // Some registry helper functions:
  13756. /** WIN32 ONLY - Returns a string from the registry.
  13757. The path is a string for the entire path of a value in the registry,
  13758. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13759. */
  13760. static const String getRegistryValue (const String& regValuePath,
  13761. const String& defaultValue = String::empty);
  13762. /** WIN32 ONLY - Sets a registry value as a string.
  13763. This will take care of creating any groups needed to get to the given
  13764. registry value.
  13765. */
  13766. static void setRegistryValue (const String& regValuePath,
  13767. const String& value);
  13768. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13769. static bool registryValueExists (const String& regValuePath);
  13770. /** WIN32 ONLY - Deletes a registry value. */
  13771. static void deleteRegistryValue (const String& regValuePath);
  13772. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13773. static void deleteRegistryKey (const String& regKeyPath);
  13774. /** WIN32 ONLY - Creates a file association in the registry.
  13775. This lets you set the exe that should be launched by a given file extension.
  13776. @param fileExtension the file extension to associate, including the
  13777. initial dot, e.g. ".txt"
  13778. @param symbolicDescription a space-free short token to identify the file type
  13779. @param fullDescription a human-readable description of the file type
  13780. @param targetExecutable the executable that should be launched
  13781. @param iconResourceNumber the icon that gets displayed for the file type will be
  13782. found by looking up this resource number in the
  13783. executable. Pass 0 here to not use an icon
  13784. */
  13785. static void registerFileAssociation (const String& fileExtension,
  13786. const String& symbolicDescription,
  13787. const String& fullDescription,
  13788. const File& targetExecutable,
  13789. int iconResourceNumber);
  13790. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13791. In a normal Juce application this will be set to the module handle
  13792. of the application executable.
  13793. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13794. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13795. to set the correct module handle in your DllMain() function, because
  13796. the win32 system relies on the correct instance handle when opening windows.
  13797. */
  13798. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() noexcept;
  13799. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13800. @see getCurrentModuleInstanceHandle()
  13801. */
  13802. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) noexcept;
  13803. /** WIN32 ONLY - Gets the command-line params as a string.
  13804. This is needed to avoid unicode problems with the argc type params.
  13805. */
  13806. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13807. #endif
  13808. /** Clears the floating point unit's flags.
  13809. Only has an effect under win32, currently.
  13810. */
  13811. static void fpuReset();
  13812. #if JUCE_LINUX || JUCE_WINDOWS
  13813. /** Loads a dynamically-linked library into the process's address space.
  13814. @param pathOrFilename the platform-dependent name and search path
  13815. @returns a handle which can be used by getProcedureEntryPoint(), or
  13816. zero if it fails.
  13817. @see freeDynamicLibrary, getProcedureEntryPoint
  13818. */
  13819. static void* loadDynamicLibrary (const String& pathOrFilename);
  13820. /** Frees a dynamically-linked library.
  13821. @param libraryHandle a handle created by loadDynamicLibrary
  13822. @see loadDynamicLibrary, getProcedureEntryPoint
  13823. */
  13824. static void freeDynamicLibrary (void* libraryHandle);
  13825. /** Finds a procedure call in a dynamically-linked library.
  13826. @param libraryHandle a library handle returned by loadDynamicLibrary
  13827. @param procedureName the name of the procedure call to try to load
  13828. @returns a pointer to the function if found, or 0 if it fails
  13829. @see loadDynamicLibrary
  13830. */
  13831. static void* getProcedureEntryPoint (void* libraryHandle,
  13832. const String& procedureName);
  13833. #endif
  13834. private:
  13835. PlatformUtilities();
  13836. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13837. };
  13838. #if JUCE_MAC || JUCE_IOS
  13839. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII.
  13840. */
  13841. class JUCE_API ScopedAutoReleasePool
  13842. {
  13843. public:
  13844. ScopedAutoReleasePool();
  13845. ~ScopedAutoReleasePool();
  13846. private:
  13847. void* pool;
  13848. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13849. };
  13850. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  13851. #else
  13852. #define JUCE_AUTORELEASEPOOL
  13853. #endif
  13854. #if JUCE_LINUX
  13855. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13856. using an RAII approach.
  13857. */
  13858. class ScopedXLock
  13859. {
  13860. public:
  13861. /** Creating a ScopedXLock object locks the X display.
  13862. This uses XLockDisplay() to grab the display that Juce is using.
  13863. */
  13864. ScopedXLock();
  13865. /** Deleting a ScopedXLock object unlocks the X display.
  13866. This calls XUnlockDisplay() to release the lock.
  13867. */
  13868. ~ScopedXLock();
  13869. };
  13870. #endif
  13871. #if JUCE_MAC
  13872. /**
  13873. A wrapper class for picking up events from an Apple IR remote control device.
  13874. To use it, just create a subclass of this class, implementing the buttonPressed()
  13875. callback, then call start() and stop() to start or stop receiving events.
  13876. */
  13877. class JUCE_API AppleRemoteDevice
  13878. {
  13879. public:
  13880. AppleRemoteDevice();
  13881. virtual ~AppleRemoteDevice();
  13882. /** The set of buttons that may be pressed.
  13883. @see buttonPressed
  13884. */
  13885. enum ButtonType
  13886. {
  13887. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13888. playButton, /**< The play button. */
  13889. plusButton, /**< The plus or volume-up button. */
  13890. minusButton, /**< The minus or volume-down button. */
  13891. rightButton, /**< The right button (if it's held for a short time). */
  13892. leftButton, /**< The left button (if it's held for a short time). */
  13893. rightButton_Long, /**< The right button (if it's held for a long time). */
  13894. leftButton_Long, /**< The menu button (if it's held for a long time). */
  13895. menuButton_Long, /**< The menu button (if it's held for a long time). */
  13896. playButtonSleepMode,
  13897. switched
  13898. };
  13899. /** Override this method to receive the callback about a button press.
  13900. The callback will happen on the application's message thread.
  13901. Some buttons trigger matching up and down events, in which the isDown parameter
  13902. will be true and then false. Others only send a single event when the
  13903. button is pressed.
  13904. */
  13905. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  13906. /** Starts the device running and responding to events.
  13907. Returns true if it managed to open the device.
  13908. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  13909. and will not be available to any other part of the system. If
  13910. false, it will be shared with other apps.
  13911. @see stop
  13912. */
  13913. bool start (bool inExclusiveMode);
  13914. /** Stops the device running.
  13915. @see start
  13916. */
  13917. void stop();
  13918. /** Returns true if the device has been started successfully.
  13919. */
  13920. bool isActive() const;
  13921. /** Returns the ID number of the remote, if it has sent one.
  13922. */
  13923. int getRemoteId() const { return remoteId; }
  13924. /** @internal */
  13925. void handleCallbackInternal();
  13926. private:
  13927. void* device;
  13928. void* queue;
  13929. int remoteId;
  13930. bool open (bool openInExclusiveMode);
  13931. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  13932. };
  13933. #endif
  13934. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13935. /*** End of inlined file: juce_PlatformUtilities.h ***/
  13936. #endif
  13937. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  13938. #endif
  13939. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13940. /*** Start of inlined file: juce_Singleton.h ***/
  13941. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13942. #define __JUCE_SINGLETON_JUCEHEADER__
  13943. /**
  13944. Macro to declare member variables and methods for a singleton class.
  13945. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  13946. to the class's definition.
  13947. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  13948. implementation code.
  13949. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  13950. destructor, in case it is deleted by other means than deleteInstance()
  13951. Clients can then call the static method MyClass::getInstance() to get a pointer
  13952. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  13953. no instance currently exists.
  13954. e.g. @code
  13955. class MySingleton
  13956. {
  13957. public:
  13958. MySingleton()
  13959. {
  13960. }
  13961. ~MySingleton()
  13962. {
  13963. // this ensures that no dangling pointers are left when the
  13964. // singleton is deleted.
  13965. clearSingletonInstance();
  13966. }
  13967. juce_DeclareSingleton (MySingleton, false)
  13968. };
  13969. juce_ImplementSingleton (MySingleton)
  13970. // example of usage:
  13971. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  13972. ...
  13973. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  13974. @endcode
  13975. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13976. than once during the process's lifetime - i.e. after you've created and deleted the
  13977. object, getInstance() will refuse to create another one. This can be useful to stop
  13978. objects being accidentally re-created during your app's shutdown code.
  13979. If you know that your object will only be created and deleted by a single thread, you
  13980. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  13981. of this one.
  13982. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  13983. */
  13984. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  13985. \
  13986. static classname* _singletonInstance; \
  13987. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  13988. \
  13989. static classname* JUCE_CALLTYPE getInstance() \
  13990. { \
  13991. if (_singletonInstance == nullptr) \
  13992. {\
  13993. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13994. \
  13995. if (_singletonInstance == nullptr) \
  13996. { \
  13997. static bool alreadyInside = false; \
  13998. static bool createdOnceAlready = false; \
  13999. \
  14000. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14001. jassert (! problem); \
  14002. if (! problem) \
  14003. { \
  14004. createdOnceAlready = true; \
  14005. alreadyInside = true; \
  14006. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14007. alreadyInside = false; \
  14008. \
  14009. _singletonInstance = newObject; \
  14010. } \
  14011. } \
  14012. } \
  14013. \
  14014. return _singletonInstance; \
  14015. } \
  14016. \
  14017. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() noexcept\
  14018. { \
  14019. return _singletonInstance; \
  14020. } \
  14021. \
  14022. static void JUCE_CALLTYPE deleteInstance() \
  14023. { \
  14024. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14025. if (_singletonInstance != nullptr) \
  14026. { \
  14027. classname* const old = _singletonInstance; \
  14028. _singletonInstance = nullptr; \
  14029. delete old; \
  14030. } \
  14031. } \
  14032. \
  14033. void clearSingletonInstance() noexcept\
  14034. { \
  14035. if (_singletonInstance == this) \
  14036. _singletonInstance = nullptr; \
  14037. }
  14038. /** This is a counterpart to the juce_DeclareSingleton macro.
  14039. After adding the juce_DeclareSingleton to the class definition, this macro has
  14040. to be used in the cpp file.
  14041. */
  14042. #define juce_ImplementSingleton(classname) \
  14043. \
  14044. classname* classname::_singletonInstance = nullptr; \
  14045. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  14046. /**
  14047. Macro to declare member variables and methods for a singleton class.
  14048. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  14049. section to make access to it thread-safe. If you know that your object will
  14050. only ever be created or deleted by a single thread, then this is a
  14051. more efficient version to use.
  14052. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14053. than once during the process's lifetime - i.e. after you've created and deleted the
  14054. object, getInstance() will refuse to create another one. This can be useful to stop
  14055. objects being accidentally re-created during your app's shutdown code.
  14056. See the documentation for juce_DeclareSingleton for more information about
  14057. how to use it, the only difference being that you have to use
  14058. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14059. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  14060. */
  14061. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  14062. \
  14063. static classname* _singletonInstance; \
  14064. \
  14065. static classname* getInstance() \
  14066. { \
  14067. if (_singletonInstance == nullptr) \
  14068. { \
  14069. static bool alreadyInside = false; \
  14070. static bool createdOnceAlready = false; \
  14071. \
  14072. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14073. jassert (! problem); \
  14074. if (! problem) \
  14075. { \
  14076. createdOnceAlready = true; \
  14077. alreadyInside = true; \
  14078. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14079. alreadyInside = false; \
  14080. \
  14081. _singletonInstance = newObject; \
  14082. } \
  14083. } \
  14084. \
  14085. return _singletonInstance; \
  14086. } \
  14087. \
  14088. static inline classname* getInstanceWithoutCreating() noexcept\
  14089. { \
  14090. return _singletonInstance; \
  14091. } \
  14092. \
  14093. static void deleteInstance() \
  14094. { \
  14095. if (_singletonInstance != nullptr) \
  14096. { \
  14097. classname* const old = _singletonInstance; \
  14098. _singletonInstance = nullptr; \
  14099. delete old; \
  14100. } \
  14101. } \
  14102. \
  14103. void clearSingletonInstance() noexcept\
  14104. { \
  14105. if (_singletonInstance == this) \
  14106. _singletonInstance = nullptr; \
  14107. }
  14108. /**
  14109. Macro to declare member variables and methods for a singleton class.
  14110. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  14111. for recursion or repeated instantiation. It's intended for use as a lightweight
  14112. version of a singleton, where you're using it in very straightforward
  14113. circumstances and don't need the extra checking.
  14114. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  14115. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  14116. See the documentation for juce_DeclareSingleton for more information about
  14117. how to use it, the only difference being that you have to use
  14118. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14119. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  14120. */
  14121. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  14122. \
  14123. static classname* _singletonInstance; \
  14124. \
  14125. static classname* getInstance() \
  14126. { \
  14127. if (_singletonInstance == nullptr) \
  14128. _singletonInstance = new classname(); \
  14129. \
  14130. return _singletonInstance; \
  14131. } \
  14132. \
  14133. static inline classname* getInstanceWithoutCreating() noexcept\
  14134. { \
  14135. return _singletonInstance; \
  14136. } \
  14137. \
  14138. static void deleteInstance() \
  14139. { \
  14140. if (_singletonInstance != nullptr) \
  14141. { \
  14142. classname* const old = _singletonInstance; \
  14143. _singletonInstance = nullptr; \
  14144. delete old; \
  14145. } \
  14146. } \
  14147. \
  14148. void clearSingletonInstance() noexcept\
  14149. { \
  14150. if (_singletonInstance == this) \
  14151. _singletonInstance = nullptr; \
  14152. }
  14153. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  14154. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  14155. to the class definition, this macro has to be used somewhere in the cpp file.
  14156. */
  14157. #define juce_ImplementSingleton_SingleThreaded(classname) \
  14158. \
  14159. classname* classname::_singletonInstance = nullptr;
  14160. #endif // __JUCE_SINGLETON_JUCEHEADER__
  14161. /*** End of inlined file: juce_Singleton.h ***/
  14162. #endif
  14163. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  14164. #endif
  14165. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14166. /*** Start of inlined file: juce_SystemStats.h ***/
  14167. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14168. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  14169. /**
  14170. Contains methods for finding out about the current hardware and OS configuration.
  14171. */
  14172. class JUCE_API SystemStats
  14173. {
  14174. public:
  14175. /** Returns the current version of JUCE,
  14176. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  14177. */
  14178. static const String getJUCEVersion();
  14179. /** The set of possible results of the getOperatingSystemType() method.
  14180. */
  14181. enum OperatingSystemType
  14182. {
  14183. UnknownOS = 0,
  14184. MacOSX = 0x1000,
  14185. Linux = 0x2000,
  14186. Android = 0x3000,
  14187. Win95 = 0x4001,
  14188. Win98 = 0x4002,
  14189. WinNT351 = 0x4103,
  14190. WinNT40 = 0x4104,
  14191. Win2000 = 0x4105,
  14192. WinXP = 0x4106,
  14193. WinVista = 0x4107,
  14194. Windows7 = 0x4108,
  14195. Windows = 0x4000, /**< To test whether any version of Windows is running,
  14196. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  14197. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  14198. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  14199. };
  14200. /** Returns the type of operating system we're running on.
  14201. @returns one of the values from the OperatingSystemType enum.
  14202. @see getOperatingSystemName
  14203. */
  14204. static OperatingSystemType getOperatingSystemType();
  14205. /** Returns the name of the type of operating system we're running on.
  14206. @returns a string describing the OS type.
  14207. @see getOperatingSystemType
  14208. */
  14209. static const String getOperatingSystemName();
  14210. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  14211. */
  14212. static bool isOperatingSystem64Bit();
  14213. /** Returns the current user's name, if available.
  14214. @see getFullUserName()
  14215. */
  14216. static const String getLogonName();
  14217. /** Returns the current user's full name, if available.
  14218. On some OSes, this may just return the same value as getLogonName().
  14219. @see getLogonName()
  14220. */
  14221. static const String getFullUserName();
  14222. /** Returns the host-name of the computer. */
  14223. static const String getComputerName();
  14224. // CPU and memory information..
  14225. /** Returns the approximate CPU speed.
  14226. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  14227. what year you're reading this...)
  14228. */
  14229. static int getCpuSpeedInMegaherz();
  14230. /** Returns a string to indicate the CPU vendor.
  14231. Might not be known on some systems.
  14232. */
  14233. static const String getCpuVendor();
  14234. /** Checks whether Intel MMX instructions are available. */
  14235. static bool hasMMX() noexcept { return cpuFlags.hasMMX; }
  14236. /** Checks whether Intel SSE instructions are available. */
  14237. static bool hasSSE() noexcept { return cpuFlags.hasSSE; }
  14238. /** Checks whether Intel SSE2 instructions are available. */
  14239. static bool hasSSE2() noexcept { return cpuFlags.hasSSE2; }
  14240. /** Checks whether AMD 3DNOW instructions are available. */
  14241. static bool has3DNow() noexcept { return cpuFlags.has3DNow; }
  14242. /** Returns the number of CPUs. */
  14243. static int getNumCpus() noexcept { return cpuFlags.numCpus; }
  14244. /** Finds out how much RAM is in the machine.
  14245. @returns the approximate number of megabytes of memory, or zero if
  14246. something goes wrong when finding out.
  14247. */
  14248. static int getMemorySizeInMegabytes();
  14249. /** Returns the system page-size.
  14250. This is only used by programmers with beards.
  14251. */
  14252. static int getPageSize();
  14253. // not-for-public-use platform-specific method gets called at startup to initialise things.
  14254. static void initialiseStats();
  14255. private:
  14256. struct CPUFlags
  14257. {
  14258. int numCpus;
  14259. bool hasMMX : 1;
  14260. bool hasSSE : 1;
  14261. bool hasSSE2 : 1;
  14262. bool has3DNow : 1;
  14263. };
  14264. static CPUFlags cpuFlags;
  14265. SystemStats();
  14266. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  14267. };
  14268. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  14269. /*** End of inlined file: juce_SystemStats.h ***/
  14270. #endif
  14271. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  14272. #endif
  14273. #ifndef __JUCE_TIME_JUCEHEADER__
  14274. #endif
  14275. #ifndef __JUCE_UUID_JUCEHEADER__
  14276. /*** Start of inlined file: juce_Uuid.h ***/
  14277. #ifndef __JUCE_UUID_JUCEHEADER__
  14278. #define __JUCE_UUID_JUCEHEADER__
  14279. /**
  14280. A universally unique 128-bit identifier.
  14281. This class generates very random unique numbers based on the system time
  14282. and MAC addresses if any are available. It's extremely unlikely that two identical
  14283. UUIDs would ever be created by chance.
  14284. The class includes methods for saving the ID as a string or as raw binary data.
  14285. */
  14286. class JUCE_API Uuid
  14287. {
  14288. public:
  14289. /** Creates a new unique ID. */
  14290. Uuid();
  14291. /** Destructor. */
  14292. ~Uuid() noexcept;
  14293. /** Creates a copy of another UUID. */
  14294. Uuid (const Uuid& other);
  14295. /** Copies another UUID. */
  14296. Uuid& operator= (const Uuid& other);
  14297. /** Returns true if the ID is zero. */
  14298. bool isNull() const noexcept;
  14299. /** Compares two UUIDs. */
  14300. bool operator== (const Uuid& other) const;
  14301. /** Compares two UUIDs. */
  14302. bool operator!= (const Uuid& other) const;
  14303. /** Returns a stringified version of this UUID.
  14304. A Uuid object can later be reconstructed from this string using operator= or
  14305. the constructor that takes a string parameter.
  14306. @returns a 32 character hex string.
  14307. */
  14308. const String toString() const;
  14309. /** Creates an ID from an encoded string version.
  14310. @see toString
  14311. */
  14312. Uuid (const String& uuidString);
  14313. /** Copies from a stringified UUID.
  14314. The string passed in should be one that was created with the toString() method.
  14315. */
  14316. Uuid& operator= (const String& uuidString);
  14317. /** Returns a pointer to the internal binary representation of the ID.
  14318. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  14319. the constructor or operator= method that takes an array of uint8s.
  14320. */
  14321. const uint8* getRawData() const noexcept { return value.asBytes; }
  14322. /** Creates a UUID from a 16-byte array.
  14323. @see getRawData
  14324. */
  14325. Uuid (const uint8* rawData);
  14326. /** Sets this UUID from 16-bytes of raw data. */
  14327. Uuid& operator= (const uint8* rawData);
  14328. private:
  14329. #ifndef DOXYGEN
  14330. union
  14331. {
  14332. uint8 asBytes [16];
  14333. int asInt[4];
  14334. int64 asInt64[2];
  14335. } value;
  14336. #endif
  14337. JUCE_LEAK_DETECTOR (Uuid);
  14338. };
  14339. #endif // __JUCE_UUID_JUCEHEADER__
  14340. /*** End of inlined file: juce_Uuid.h ***/
  14341. #endif
  14342. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14343. /*** Start of inlined file: juce_BlowFish.h ***/
  14344. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14345. #define __JUCE_BLOWFISH_JUCEHEADER__
  14346. /**
  14347. BlowFish encryption class.
  14348. */
  14349. class JUCE_API BlowFish
  14350. {
  14351. public:
  14352. /** Creates an object that can encode/decode based on the specified key.
  14353. The key data can be up to 72 bytes long.
  14354. */
  14355. BlowFish (const void* keyData, int keyBytes);
  14356. /** Creates a copy of another blowfish object. */
  14357. BlowFish (const BlowFish& other);
  14358. /** Copies another blowfish object. */
  14359. BlowFish& operator= (const BlowFish& other);
  14360. /** Destructor. */
  14361. ~BlowFish();
  14362. /** Encrypts a pair of 32-bit integers. */
  14363. void encrypt (uint32& data1, uint32& data2) const noexcept;
  14364. /** Decrypts a pair of 32-bit integers. */
  14365. void decrypt (uint32& data1, uint32& data2) const noexcept;
  14366. private:
  14367. uint32 p[18];
  14368. HeapBlock <uint32> s[4];
  14369. uint32 F (uint32 x) const noexcept;
  14370. JUCE_LEAK_DETECTOR (BlowFish);
  14371. };
  14372. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  14373. /*** End of inlined file: juce_BlowFish.h ***/
  14374. #endif
  14375. #ifndef __JUCE_MD5_JUCEHEADER__
  14376. /*** Start of inlined file: juce_MD5.h ***/
  14377. #ifndef __JUCE_MD5_JUCEHEADER__
  14378. #define __JUCE_MD5_JUCEHEADER__
  14379. /**
  14380. MD5 checksum class.
  14381. Create one of these with a block of source data or a string, and it calculates the
  14382. MD5 checksum of that data.
  14383. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  14384. */
  14385. class JUCE_API MD5
  14386. {
  14387. public:
  14388. /** Creates a null MD5 object. */
  14389. MD5();
  14390. /** Creates a copy of another MD5. */
  14391. MD5 (const MD5& other);
  14392. /** Copies another MD5. */
  14393. MD5& operator= (const MD5& other);
  14394. /** Creates a checksum for a block of binary data. */
  14395. explicit MD5 (const MemoryBlock& data);
  14396. /** Creates a checksum for a block of binary data. */
  14397. MD5 (const void* data, size_t numBytes);
  14398. /** Creates a checksum for a string.
  14399. Note that this operates on the string as a block of unicode characters, so the
  14400. result you get will differ from the value you'd get if the string was treated
  14401. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  14402. of this method with a checksum created by a different framework, which may have
  14403. used a different encoding.
  14404. */
  14405. explicit MD5 (const String& text);
  14406. /** Creates a checksum for the input from a stream.
  14407. This will read up to the given number of bytes from the stream, and produce the
  14408. checksum of that. If the number of bytes to read is negative, it'll read
  14409. until the stream is exhausted.
  14410. */
  14411. MD5 (InputStream& input, int64 numBytesToRead = -1);
  14412. /** Creates a checksum for a file. */
  14413. explicit MD5 (const File& file);
  14414. /** Destructor. */
  14415. ~MD5();
  14416. /** Returns the checksum as a 16-byte block of data. */
  14417. const MemoryBlock getRawChecksumData() const;
  14418. /** Returns the checksum as a 32-digit hex string. */
  14419. const String toHexString() const;
  14420. /** Compares this to another MD5. */
  14421. bool operator== (const MD5& other) const;
  14422. /** Compares this to another MD5. */
  14423. bool operator!= (const MD5& other) const;
  14424. private:
  14425. uint8 result [16];
  14426. struct ProcessContext
  14427. {
  14428. uint8 buffer [64];
  14429. uint32 state [4];
  14430. uint32 count [2];
  14431. ProcessContext();
  14432. void processBlock (const void* data, size_t dataSize);
  14433. void transform (const void* buffer);
  14434. void finish (void* result);
  14435. };
  14436. void processStream (InputStream& input, int64 numBytesToRead);
  14437. JUCE_LEAK_DETECTOR (MD5);
  14438. };
  14439. #endif // __JUCE_MD5_JUCEHEADER__
  14440. /*** End of inlined file: juce_MD5.h ***/
  14441. #endif
  14442. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14443. /*** Start of inlined file: juce_Primes.h ***/
  14444. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14445. #define __JUCE_PRIMES_JUCEHEADER__
  14446. /*** Start of inlined file: juce_BigInteger.h ***/
  14447. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  14448. #define __JUCE_BIGINTEGER_JUCEHEADER__
  14449. class MemoryBlock;
  14450. /**
  14451. An arbitrarily large integer class.
  14452. A BigInteger can be used in a similar way to a normal integer, but has no size
  14453. limit (except for memory and performance constraints).
  14454. Negative values are possible, but the value isn't stored as 2s-complement, so
  14455. be careful if you use negative values and look at the values of individual bits.
  14456. */
  14457. class JUCE_API BigInteger
  14458. {
  14459. public:
  14460. /** Creates an empty BigInteger */
  14461. BigInteger();
  14462. /** Creates a BigInteger containing an integer value in its low bits.
  14463. The low 32 bits of the number are initialised with this value.
  14464. */
  14465. BigInteger (uint32 value);
  14466. /** Creates a BigInteger containing an integer value in its low bits.
  14467. The low 32 bits of the number are initialised with the absolute value
  14468. passed in, and its sign is set to reflect the sign of the number.
  14469. */
  14470. BigInteger (int32 value);
  14471. /** Creates a BigInteger containing an integer value in its low bits.
  14472. The low 64 bits of the number are initialised with the absolute value
  14473. passed in, and its sign is set to reflect the sign of the number.
  14474. */
  14475. BigInteger (int64 value);
  14476. /** Creates a copy of another BigInteger. */
  14477. BigInteger (const BigInteger& other);
  14478. /** Destructor. */
  14479. ~BigInteger();
  14480. /** Copies another BigInteger onto this one. */
  14481. BigInteger& operator= (const BigInteger& other);
  14482. /** Swaps the internal contents of this with another object. */
  14483. void swapWith (BigInteger& other) noexcept;
  14484. /** Returns the value of a specified bit in the number.
  14485. If the index is out-of-range, the result will be false.
  14486. */
  14487. bool operator[] (int bit) const noexcept;
  14488. /** Returns true if no bits are set. */
  14489. bool isZero() const noexcept;
  14490. /** Returns true if the value is 1. */
  14491. bool isOne() const noexcept;
  14492. /** Attempts to get the lowest bits of the value as an integer.
  14493. If the value is bigger than the integer limits, this will return only the lower bits.
  14494. */
  14495. int toInteger() const noexcept;
  14496. /** Resets the value to 0. */
  14497. void clear();
  14498. /** Clears a particular bit in the number. */
  14499. void clearBit (int bitNumber) noexcept;
  14500. /** Sets a specified bit to 1. */
  14501. void setBit (int bitNumber);
  14502. /** Sets or clears a specified bit. */
  14503. void setBit (int bitNumber, bool shouldBeSet);
  14504. /** Sets a range of bits to be either on or off.
  14505. @param startBit the first bit to change
  14506. @param numBits the number of bits to change
  14507. @param shouldBeSet whether to turn these bits on or off
  14508. */
  14509. void setRange (int startBit, int numBits, bool shouldBeSet);
  14510. /** Inserts a bit an a given position, shifting up any bits above it. */
  14511. void insertBit (int bitNumber, bool shouldBeSet);
  14512. /** Returns a range of bits as a new BigInteger.
  14513. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  14514. @see getBitRangeAsInt
  14515. */
  14516. const BigInteger getBitRange (int startBit, int numBits) const;
  14517. /** Returns a range of bits as an integer value.
  14518. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  14519. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  14520. getBitRange().
  14521. */
  14522. int getBitRangeAsInt (int startBit, int numBits) const noexcept;
  14523. /** Sets a range of bits to an integer value.
  14524. Copies the given integer onto a range of bits, starting at startBit,
  14525. and using up to numBits of the available bits.
  14526. */
  14527. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  14528. /** Shifts a section of bits left or right.
  14529. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  14530. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  14531. */
  14532. void shiftBits (int howManyBitsLeft, int startBit);
  14533. /** Returns the total number of set bits in the value. */
  14534. int countNumberOfSetBits() const noexcept;
  14535. /** Looks for the index of the next set bit after a given starting point.
  14536. This searches from startIndex (inclusive) upwards for the first set bit,
  14537. and returns its index. If no set bits are found, it returns -1.
  14538. */
  14539. int findNextSetBit (int startIndex = 0) const noexcept;
  14540. /** Looks for the index of the next clear bit after a given starting point.
  14541. This searches from startIndex (inclusive) upwards for the first clear bit,
  14542. and returns its index.
  14543. */
  14544. int findNextClearBit (int startIndex = 0) const noexcept;
  14545. /** Returns the index of the highest set bit in the number.
  14546. If the value is zero, this will return -1.
  14547. */
  14548. int getHighestBit() const noexcept;
  14549. // All the standard arithmetic ops...
  14550. BigInteger& operator+= (const BigInteger& other);
  14551. BigInteger& operator-= (const BigInteger& other);
  14552. BigInteger& operator*= (const BigInteger& other);
  14553. BigInteger& operator/= (const BigInteger& other);
  14554. BigInteger& operator|= (const BigInteger& other);
  14555. BigInteger& operator&= (const BigInteger& other);
  14556. BigInteger& operator^= (const BigInteger& other);
  14557. BigInteger& operator%= (const BigInteger& other);
  14558. BigInteger& operator<<= (int numBitsToShift);
  14559. BigInteger& operator>>= (int numBitsToShift);
  14560. BigInteger& operator++();
  14561. BigInteger& operator--();
  14562. const BigInteger operator++ (int);
  14563. const BigInteger operator-- (int);
  14564. const BigInteger operator-() const;
  14565. const BigInteger operator+ (const BigInteger& other) const;
  14566. const BigInteger operator- (const BigInteger& other) const;
  14567. const BigInteger operator* (const BigInteger& other) const;
  14568. const BigInteger operator/ (const BigInteger& other) const;
  14569. const BigInteger operator| (const BigInteger& other) const;
  14570. const BigInteger operator& (const BigInteger& other) const;
  14571. const BigInteger operator^ (const BigInteger& other) const;
  14572. const BigInteger operator% (const BigInteger& other) const;
  14573. const BigInteger operator<< (int numBitsToShift) const;
  14574. const BigInteger operator>> (int numBitsToShift) const;
  14575. bool operator== (const BigInteger& other) const noexcept;
  14576. bool operator!= (const BigInteger& other) const noexcept;
  14577. bool operator< (const BigInteger& other) const noexcept;
  14578. bool operator<= (const BigInteger& other) const noexcept;
  14579. bool operator> (const BigInteger& other) const noexcept;
  14580. bool operator>= (const BigInteger& other) const noexcept;
  14581. /** Does a signed comparison of two BigIntegers.
  14582. Return values are:
  14583. - 0 if the numbers are the same
  14584. - < 0 if this number is smaller than the other
  14585. - > 0 if this number is bigger than the other
  14586. */
  14587. int compare (const BigInteger& other) const noexcept;
  14588. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14589. Return values are:
  14590. - 0 if the numbers are the same
  14591. - < 0 if this number is smaller than the other
  14592. - > 0 if this number is bigger than the other
  14593. */
  14594. int compareAbsolute (const BigInteger& other) const noexcept;
  14595. /** Divides this value by another one and returns the remainder.
  14596. This number is divided by other, leaving the quotient in this number,
  14597. with the remainder being copied to the other BigInteger passed in.
  14598. */
  14599. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14600. /** Returns the largest value that will divide both this value and the one passed-in.
  14601. */
  14602. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14603. /** Performs a combined exponent and modulo operation.
  14604. This BigInteger's value becomes (this ^ exponent) % modulus.
  14605. */
  14606. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14607. /** Performs an inverse modulo on the value.
  14608. i.e. the result is (this ^ -1) mod (modulus).
  14609. */
  14610. void inverseModulo (const BigInteger& modulus);
  14611. /** Returns true if the value is less than zero.
  14612. @see setNegative, negate
  14613. */
  14614. bool isNegative() const noexcept;
  14615. /** Changes the sign of the number to be positive or negative.
  14616. @see isNegative, negate
  14617. */
  14618. void setNegative (bool shouldBeNegative) noexcept;
  14619. /** Inverts the sign of the number.
  14620. @see isNegative, setNegative
  14621. */
  14622. void negate() noexcept;
  14623. /** Converts the number to a string.
  14624. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14625. If minimumNumCharacters is greater than 0, the returned string will be
  14626. padded with leading zeros to reach at least that length.
  14627. */
  14628. const String toString (int base, int minimumNumCharacters = 1) const;
  14629. /** Reads the numeric value from a string.
  14630. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14631. Any invalid characters will be ignored.
  14632. */
  14633. void parseString (const String& text, int base);
  14634. /** Turns the number into a block of binary data.
  14635. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14636. of the number, and so on.
  14637. @see loadFromMemoryBlock
  14638. */
  14639. const MemoryBlock toMemoryBlock() const;
  14640. /** Converts a block of raw data into a number.
  14641. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14642. of the number, and so on.
  14643. @see toMemoryBlock
  14644. */
  14645. void loadFromMemoryBlock (const MemoryBlock& data);
  14646. private:
  14647. HeapBlock <uint32> values;
  14648. int numValues, highestBit;
  14649. bool negative;
  14650. void ensureSize (int numVals);
  14651. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14652. static inline int bitToIndex (const int bit) noexcept { return bit >> 5; }
  14653. static inline uint32 bitToMask (const int bit) noexcept { return 1 << (bit & 31); }
  14654. JUCE_LEAK_DETECTOR (BigInteger);
  14655. };
  14656. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14657. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14658. #ifndef DOXYGEN
  14659. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14660. typedef BigInteger BitArray;
  14661. #endif
  14662. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14663. /*** End of inlined file: juce_BigInteger.h ***/
  14664. /**
  14665. Prime number creation class.
  14666. This class contains static methods for generating and testing prime numbers.
  14667. @see BigInteger
  14668. */
  14669. class JUCE_API Primes
  14670. {
  14671. public:
  14672. /** Creates a random prime number with a given bit-length.
  14673. The certainty parameter specifies how many iterations to use when testing
  14674. for primality. A safe value might be anything over about 20-30.
  14675. The randomSeeds parameter lets you optionally pass it a set of values with
  14676. which to seed the random number generation, improving the security of the
  14677. keys generated.
  14678. */
  14679. static const BigInteger createProbablePrime (int bitLength,
  14680. int certainty,
  14681. const int* randomSeeds = 0,
  14682. int numRandomSeeds = 0);
  14683. /** Tests a number to see if it's prime.
  14684. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14685. whether the number is prime.
  14686. The certainty parameter specifies how many iterations to use when testing - a
  14687. safe value might be anything over about 20-30.
  14688. */
  14689. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14690. private:
  14691. Primes();
  14692. JUCE_DECLARE_NON_COPYABLE (Primes);
  14693. };
  14694. #endif // __JUCE_PRIMES_JUCEHEADER__
  14695. /*** End of inlined file: juce_Primes.h ***/
  14696. #endif
  14697. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14698. /*** Start of inlined file: juce_RSAKey.h ***/
  14699. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14700. #define __JUCE_RSAKEY_JUCEHEADER__
  14701. /**
  14702. RSA public/private key-pair encryption class.
  14703. An object of this type makes up one half of a public/private RSA key pair. Use the
  14704. createKeyPair() method to create a matching pair for encoding/decoding.
  14705. */
  14706. class JUCE_API RSAKey
  14707. {
  14708. public:
  14709. /** Creates a null key object.
  14710. Initialise a pair of objects for use with the createKeyPair() method.
  14711. */
  14712. RSAKey();
  14713. /** Loads a key from an encoded string representation.
  14714. This reloads a key from a string created by the toString() method.
  14715. */
  14716. explicit RSAKey (const String& stringRepresentation);
  14717. /** Destructor. */
  14718. ~RSAKey();
  14719. bool operator== (const RSAKey& other) const noexcept;
  14720. bool operator!= (const RSAKey& other) const noexcept;
  14721. /** Turns the key into a string representation.
  14722. This can be reloaded using the constructor that takes a string.
  14723. */
  14724. const String toString() const;
  14725. /** Encodes or decodes a value.
  14726. Call this on the public key object to encode some data, then use the matching
  14727. private key object to decode it.
  14728. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14729. initialised correctly.
  14730. NOTE: This method dumbly applies this key to this data. If you encode some data
  14731. and then try to decode it with a key that doesn't match, this method will still
  14732. happily do its job and return true, but the result won't be what you were expecting.
  14733. It's your responsibility to check that the result is what you wanted.
  14734. */
  14735. bool applyToValue (BigInteger& value) const;
  14736. /** Creates a public/private key-pair.
  14737. Each key will perform one-way encryption that can only be reversed by
  14738. using the other key.
  14739. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14740. sizes are more secure, but this method will take longer to execute.
  14741. The randomSeeds parameter lets you optionally pass it a set of values with
  14742. which to seed the random number generation, improving the security of the
  14743. keys generated. If you supply these, make sure you provide more than 2 values,
  14744. and the more your provide, the better the security.
  14745. */
  14746. static void createKeyPair (RSAKey& publicKey,
  14747. RSAKey& privateKey,
  14748. int numBits,
  14749. const int* randomSeeds = nullptr,
  14750. int numRandomSeeds = 0);
  14751. protected:
  14752. BigInteger part1, part2;
  14753. private:
  14754. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14755. JUCE_LEAK_DETECTOR (RSAKey);
  14756. };
  14757. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14758. /*** End of inlined file: juce_RSAKey.h ***/
  14759. #endif
  14760. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14761. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14762. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14763. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14764. /**
  14765. Searches through a the files in a directory, returning each file that is found.
  14766. A DirectoryIterator will search through a directory and its subdirectories using
  14767. a wildcard filepattern match.
  14768. If you may be finding a large number of files, this is better than
  14769. using File::findChildFiles() because it doesn't block while it finds them
  14770. all, and this is more memory-efficient.
  14771. It can also guess how far it's got using a wildly inaccurate algorithm.
  14772. */
  14773. class JUCE_API DirectoryIterator
  14774. {
  14775. public:
  14776. /** Creates a DirectoryIterator for a given directory.
  14777. After creating one of these, call its next() method to get the
  14778. first file - e.g. @code
  14779. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14780. while (iter.next())
  14781. {
  14782. File theFileItFound (iter.getFile());
  14783. ... etc
  14784. }
  14785. @endcode
  14786. @param directory the directory to search in
  14787. @param isRecursive whether all the subdirectories should also be searched
  14788. @param wildCard the file pattern to match
  14789. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14790. whether to look for files, directories, or both.
  14791. */
  14792. DirectoryIterator (const File& directory,
  14793. bool isRecursive,
  14794. const String& wildCard = "*",
  14795. int whatToLookFor = File::findFiles);
  14796. /** Destructor. */
  14797. ~DirectoryIterator();
  14798. /** Moves the iterator along to the next file.
  14799. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14800. false if there are no more matching files.
  14801. */
  14802. bool next();
  14803. /** Moves the iterator along to the next file, and returns various properties of that file.
  14804. If you need to find out details about the file, it's more efficient to call this method than
  14805. to call the normal next() method and then find out the details afterwards.
  14806. All the parameters are optional, so pass null pointers for any items that you're not
  14807. interested in.
  14808. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14809. false if there are no more matching files. If it returns false, then none of the
  14810. parameters will be filled-in.
  14811. */
  14812. bool next (bool* isDirectory,
  14813. bool* isHidden,
  14814. int64* fileSize,
  14815. Time* modTime,
  14816. Time* creationTime,
  14817. bool* isReadOnly);
  14818. /** Returns the file that the iterator is currently pointing at.
  14819. The result of this call is only valid after a call to next() has returned true.
  14820. */
  14821. const File getFile() const;
  14822. /** Returns a guess of how far through the search the iterator has got.
  14823. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14824. very accurate.
  14825. */
  14826. float getEstimatedProgress() const;
  14827. private:
  14828. class NativeIterator
  14829. {
  14830. public:
  14831. NativeIterator (const File& directory, const String& wildCard);
  14832. ~NativeIterator();
  14833. bool next (String& filenameFound,
  14834. bool* isDirectory, bool* isHidden, int64* fileSize,
  14835. Time* modTime, Time* creationTime, bool* isReadOnly);
  14836. class Pimpl;
  14837. private:
  14838. friend class DirectoryIterator;
  14839. friend class ScopedPointer<Pimpl>;
  14840. ScopedPointer<Pimpl> pimpl;
  14841. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14842. };
  14843. friend class ScopedPointer<NativeIterator::Pimpl>;
  14844. NativeIterator fileFinder;
  14845. String wildCard, path;
  14846. int index;
  14847. mutable int totalNumFiles;
  14848. const int whatToLookFor;
  14849. const bool isRecursive;
  14850. bool hasBeenAdvanced;
  14851. ScopedPointer <DirectoryIterator> subIterator;
  14852. File currentFile;
  14853. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14854. };
  14855. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14856. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14857. #endif
  14858. #ifndef __JUCE_FILE_JUCEHEADER__
  14859. #endif
  14860. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14861. /*** Start of inlined file: juce_FileInputStream.h ***/
  14862. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14863. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14864. /**
  14865. An input stream that reads from a local file.
  14866. @see InputStream, FileOutputStream, File::createInputStream
  14867. */
  14868. class JUCE_API FileInputStream : public InputStream
  14869. {
  14870. public:
  14871. /** Creates a FileInputStream.
  14872. @param fileToRead the file to read from - if the file can't be accessed for some
  14873. reason, then the stream will just contain no data
  14874. */
  14875. explicit FileInputStream (const File& fileToRead);
  14876. /** Destructor. */
  14877. ~FileInputStream();
  14878. const File& getFile() const noexcept { return file; }
  14879. int64 getTotalLength();
  14880. int read (void* destBuffer, int maxBytesToRead);
  14881. bool isExhausted();
  14882. int64 getPosition();
  14883. bool setPosition (int64 pos);
  14884. private:
  14885. File file;
  14886. void* fileHandle;
  14887. int64 currentPosition, totalSize;
  14888. bool needToSeek;
  14889. void openHandle();
  14890. void closeHandle();
  14891. size_t readInternal (void* buffer, size_t numBytes);
  14892. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14893. };
  14894. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14895. /*** End of inlined file: juce_FileInputStream.h ***/
  14896. #endif
  14897. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14898. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14899. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14900. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14901. /**
  14902. An output stream that writes into a local file.
  14903. @see OutputStream, FileInputStream, File::createOutputStream
  14904. */
  14905. class JUCE_API FileOutputStream : public OutputStream
  14906. {
  14907. public:
  14908. /** Creates a FileOutputStream.
  14909. If the file doesn't exist, it will first be created. If the file can't be
  14910. created or opened, the failedToOpen() method will return
  14911. true.
  14912. If the file already exists when opened, the stream's write-postion will
  14913. be set to the end of the file. To overwrite an existing file,
  14914. use File::deleteFile() before opening the stream, or use setPosition(0)
  14915. after it's opened (although this won't truncate the file).
  14916. It's better to use File::createOutputStream() to create one of these, rather
  14917. than using the class directly.
  14918. @see TemporaryFile
  14919. */
  14920. FileOutputStream (const File& fileToWriteTo,
  14921. int bufferSizeToUse = 16384);
  14922. /** Destructor. */
  14923. ~FileOutputStream();
  14924. /** Returns the file that this stream is writing to.
  14925. */
  14926. const File& getFile() const { return file; }
  14927. /** Returns true if the stream couldn't be opened for some reason.
  14928. */
  14929. bool failedToOpen() const { return fileHandle == 0; }
  14930. void flush();
  14931. int64 getPosition();
  14932. bool setPosition (int64 pos);
  14933. bool write (const void* data, int numBytes);
  14934. private:
  14935. File file;
  14936. void* fileHandle;
  14937. int64 currentPosition;
  14938. int bufferSize, bytesInBuffer;
  14939. HeapBlock <char> buffer;
  14940. void openHandle();
  14941. void closeHandle();
  14942. void flushInternal();
  14943. int64 setPositionInternal (int64 newPosition);
  14944. int writeInternal (const void* data, int numBytes);
  14945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  14946. };
  14947. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14948. /*** End of inlined file: juce_FileOutputStream.h ***/
  14949. #endif
  14950. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14951. /*** Start of inlined file: juce_FileSearchPath.h ***/
  14952. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14953. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  14954. /**
  14955. Encapsulates a set of folders that make up a search path.
  14956. @see File
  14957. */
  14958. class JUCE_API FileSearchPath
  14959. {
  14960. public:
  14961. /** Creates an empty search path. */
  14962. FileSearchPath();
  14963. /** Creates a search path from a string of pathnames.
  14964. The path can be semicolon- or comma-separated, e.g.
  14965. "/foo/bar;/foo/moose;/fish/moose"
  14966. The separate folders are tokenised and added to the search path.
  14967. */
  14968. FileSearchPath (const String& path);
  14969. /** Creates a copy of another search path. */
  14970. FileSearchPath (const FileSearchPath& other);
  14971. /** Destructor. */
  14972. ~FileSearchPath();
  14973. /** Uses a string containing a list of pathnames to re-initialise this list.
  14974. This search path is cleared and the semicolon- or comma-separated folders
  14975. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  14976. */
  14977. FileSearchPath& operator= (const String& path);
  14978. /** Returns the number of folders in this search path.
  14979. @see operator[]
  14980. */
  14981. int getNumPaths() const;
  14982. /** Returns one of the folders in this search path.
  14983. The file returned isn't guaranteed to actually be a valid directory.
  14984. @see getNumPaths
  14985. */
  14986. const File operator[] (int index) const;
  14987. /** Returns the search path as a semicolon-separated list of directories. */
  14988. const String toString() const;
  14989. /** Adds a new directory to the search path.
  14990. The new directory is added to the end of the list if the insertIndex parameter is
  14991. less than zero, otherwise it is inserted at the given index.
  14992. */
  14993. void add (const File& directoryToAdd,
  14994. int insertIndex = -1);
  14995. /** Adds a new directory to the search path if it's not already in there. */
  14996. void addIfNotAlreadyThere (const File& directoryToAdd);
  14997. /** Removes a directory from the search path. */
  14998. void remove (int indexToRemove);
  14999. /** Merges another search path into this one.
  15000. This will remove any duplicate directories.
  15001. */
  15002. void addPath (const FileSearchPath& other);
  15003. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  15004. If the search is intended to be recursive, there's no point having nested folders in the search
  15005. path, because they'll just get searched twice and you'll get duplicate results.
  15006. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  15007. */
  15008. void removeRedundantPaths();
  15009. /** Removes any directories that don't actually exist. */
  15010. void removeNonExistentPaths();
  15011. /** Searches the path for a wildcard.
  15012. This will search all the directories in the search path in order, adding any
  15013. matching files to the results array.
  15014. @param results an array to append the results to
  15015. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  15016. return files, directories, or both.
  15017. @param searchRecursively whether to recursively search the subdirectories too
  15018. @param wildCardPattern a pattern to match against the filenames
  15019. @returns the number of files added to the array
  15020. @see File::findChildFiles
  15021. */
  15022. int findChildFiles (Array<File>& results,
  15023. int whatToLookFor,
  15024. bool searchRecursively,
  15025. const String& wildCardPattern = "*") const;
  15026. /** Finds out whether a file is inside one of the path's directories.
  15027. This will return true if the specified file is a child of one of the
  15028. directories specified by this path. Note that this doesn't actually do any
  15029. searching or check that the files exist - it just looks at the pathnames
  15030. to work out whether the file would be inside a directory.
  15031. @param fileToCheck the file to look for
  15032. @param checkRecursively if true, then this will return true if the file is inside a
  15033. subfolder of one of the path's directories (at any depth). If false
  15034. it will only return true if the file is actually a direct child
  15035. of one of the directories.
  15036. @see File::isAChildOf
  15037. */
  15038. bool isFileInPath (const File& fileToCheck,
  15039. bool checkRecursively) const;
  15040. private:
  15041. StringArray directories;
  15042. void init (const String& path);
  15043. JUCE_LEAK_DETECTOR (FileSearchPath);
  15044. };
  15045. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  15046. /*** End of inlined file: juce_FileSearchPath.h ***/
  15047. #endif
  15048. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15049. /*** Start of inlined file: juce_NamedPipe.h ***/
  15050. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15051. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  15052. /**
  15053. A cross-process pipe that can have data written to and read from it.
  15054. Two or more processes can use these for inter-process communication.
  15055. @see InterprocessConnection
  15056. */
  15057. class JUCE_API NamedPipe
  15058. {
  15059. public:
  15060. /** Creates a NamedPipe. */
  15061. NamedPipe();
  15062. /** Destructor. */
  15063. ~NamedPipe();
  15064. /** Tries to open a pipe that already exists.
  15065. Returns true if it succeeds.
  15066. */
  15067. bool openExisting (const String& pipeName);
  15068. /** Tries to create a new pipe.
  15069. Returns true if it succeeds.
  15070. */
  15071. bool createNewPipe (const String& pipeName);
  15072. /** Closes the pipe, if it's open. */
  15073. void close();
  15074. /** True if the pipe is currently open. */
  15075. bool isOpen() const;
  15076. /** Returns the last name that was used to try to open this pipe. */
  15077. const String getName() const;
  15078. /** Reads data from the pipe.
  15079. This will block until another thread has written enough data into the pipe to fill
  15080. the number of bytes specified, or until another thread calls the cancelPendingReads()
  15081. method.
  15082. If the operation fails, it returns -1, otherwise, it will return the number of
  15083. bytes read.
  15084. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  15085. this is a maximum timeout for reading from the pipe.
  15086. */
  15087. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  15088. /** Writes some data to the pipe.
  15089. If the operation fails, it returns -1, otherwise, it will return the number of
  15090. bytes written.
  15091. */
  15092. int write (const void* sourceBuffer, int numBytesToWrite,
  15093. int timeOutMilliseconds = 2000);
  15094. /** If any threads are currently blocked on a read operation, this tells them to abort.
  15095. */
  15096. void cancelPendingReads();
  15097. private:
  15098. void* internal;
  15099. String currentPipeName;
  15100. CriticalSection lock;
  15101. bool openInternal (const String& pipeName, const bool createPipe);
  15102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  15103. };
  15104. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  15105. /*** End of inlined file: juce_NamedPipe.h ***/
  15106. #endif
  15107. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15108. /*** Start of inlined file: juce_TemporaryFile.h ***/
  15109. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15110. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  15111. /**
  15112. Manages a temporary file, which will be deleted when this object is deleted.
  15113. This object is intended to be used as a stack based object, using its scope
  15114. to make sure the temporary file isn't left lying around.
  15115. For example:
  15116. @code
  15117. {
  15118. File myTargetFile ("~/myfile.txt");
  15119. // this will choose a file called something like "~/myfile_temp239348.txt"
  15120. // which definitely doesn't exist at the time the constructor is called.
  15121. TemporaryFile temp (myTargetFile);
  15122. // create a stream to the temporary file, and write some data to it...
  15123. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  15124. if (out != nullptr)
  15125. {
  15126. out->write ( ...etc )
  15127. out->flush();
  15128. out = nullptr; // (deletes the stream)
  15129. // ..now we've finished writing, this will rename the temp file to
  15130. // make it replace the target file we specified above.
  15131. bool succeeded = temp.overwriteTargetFileWithTemporary();
  15132. }
  15133. // ..and even if something went wrong and our overwrite failed,
  15134. // as the TemporaryFile object goes out of scope here, it'll make sure
  15135. // that the temp file gets deleted.
  15136. }
  15137. @endcode
  15138. @see File, FileOutputStream
  15139. */
  15140. class JUCE_API TemporaryFile
  15141. {
  15142. public:
  15143. enum OptionFlags
  15144. {
  15145. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  15146. i.e. its name should start with a dot. */
  15147. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  15148. the file is unique, they should go in brackets rather
  15149. than just being appended (see File::getNonexistentSibling() )*/
  15150. };
  15151. /** Creates a randomly-named temporary file in the default temp directory.
  15152. @param suffix a file suffix to use for the file
  15153. @param optionFlags a combination of the values listed in the OptionFlags enum
  15154. The file will not be created until you write to it. And remember that when
  15155. this object is deleted, the file will also be deleted!
  15156. */
  15157. TemporaryFile (const String& suffix = String::empty,
  15158. int optionFlags = 0);
  15159. /** Creates a temporary file in the same directory as a specified file.
  15160. This is useful if you have a file that you want to overwrite, but don't
  15161. want to harm the original file if the write operation fails. You can
  15162. use this to create a temporary file next to the target file, then
  15163. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  15164. to replace the target file with the one you've just written.
  15165. This class won't create any files until you actually write to them. And remember
  15166. that when this object is deleted, the temporary file will also be deleted!
  15167. @param targetFile the file that you intend to overwrite - the temporary
  15168. file will be created in the same directory as this
  15169. @param optionFlags a combination of the values listed in the OptionFlags enum
  15170. */
  15171. TemporaryFile (const File& targetFile,
  15172. int optionFlags = 0);
  15173. /** Destructor.
  15174. When this object is deleted it will make sure that its temporary file is
  15175. also deleted! If the operation fails, it'll throw an assertion in debug
  15176. mode.
  15177. */
  15178. ~TemporaryFile();
  15179. /** Returns the temporary file. */
  15180. const File getFile() const { return temporaryFile; }
  15181. /** Returns the target file that was specified in the constructor. */
  15182. const File getTargetFile() const { return targetFile; }
  15183. /** Tries to move the temporary file to overwrite the target file that was
  15184. specified in the constructor.
  15185. If you used the constructor that specified a target file, this will attempt
  15186. to replace that file with the temporary one.
  15187. Before calling this, make sure:
  15188. - that you've actually written to the temporary file
  15189. - that you've closed any open streams that you were using to write to it
  15190. - and that you don't have any streams open to the target file, which would
  15191. prevent it being overwritten
  15192. If the file move succeeds, this returns false, and the temporary file will
  15193. have disappeared. If it fails, the temporary file will probably still exist,
  15194. but will be deleted when this object is destroyed.
  15195. */
  15196. bool overwriteTargetFileWithTemporary() const;
  15197. /** Attempts to delete the temporary file, if it exists.
  15198. @returns true if the file is successfully deleted (or if it didn't exist).
  15199. */
  15200. bool deleteTemporaryFile() const;
  15201. private:
  15202. File temporaryFile, targetFile;
  15203. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  15204. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  15205. };
  15206. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  15207. /*** End of inlined file: juce_TemporaryFile.h ***/
  15208. #endif
  15209. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15210. /*** Start of inlined file: juce_ZipFile.h ***/
  15211. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15212. #define __JUCE_ZIPFILE_JUCEHEADER__
  15213. /*** Start of inlined file: juce_InputSource.h ***/
  15214. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15215. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  15216. /**
  15217. A lightweight object that can create a stream to read some kind of resource.
  15218. This may be used to refer to a file, or some other kind of source, allowing a
  15219. caller to create an input stream that can read from it when required.
  15220. @see FileInputSource
  15221. */
  15222. class JUCE_API InputSource
  15223. {
  15224. public:
  15225. InputSource() noexcept {}
  15226. /** Destructor. */
  15227. virtual ~InputSource() {}
  15228. /** Returns a new InputStream to read this item.
  15229. @returns an inputstream that the caller will delete, or 0 if
  15230. the filename isn't found.
  15231. */
  15232. virtual InputStream* createInputStream() = 0;
  15233. /** Returns a new InputStream to read an item, relative.
  15234. @param relatedItemPath the relative pathname of the resource that is required
  15235. @returns an inputstream that the caller will delete, or 0 if
  15236. the item isn't found.
  15237. */
  15238. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  15239. /** Returns a hash code that uniquely represents this item.
  15240. */
  15241. virtual int64 hashCode() const = 0;
  15242. private:
  15243. JUCE_LEAK_DETECTOR (InputSource);
  15244. };
  15245. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  15246. /*** End of inlined file: juce_InputSource.h ***/
  15247. /**
  15248. Decodes a ZIP file from a stream.
  15249. This can enumerate the items in a ZIP file and can create suitable stream objects
  15250. to read each one.
  15251. */
  15252. class JUCE_API ZipFile
  15253. {
  15254. public:
  15255. /** Creates a ZipFile for a given stream.
  15256. @param inputStream the stream to read from
  15257. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  15258. will be deleted when this ZipFile object is deleted
  15259. */
  15260. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  15261. /** Creates a ZipFile based for a file. */
  15262. ZipFile (const File& file);
  15263. /** Creates a ZipFile for an input source.
  15264. The inputSource object will be owned by the zip file, which will delete
  15265. it later when not needed.
  15266. */
  15267. ZipFile (InputSource* inputSource);
  15268. /** Destructor. */
  15269. ~ZipFile();
  15270. /**
  15271. Contains information about one of the entries in a ZipFile.
  15272. @see ZipFile::getEntry
  15273. */
  15274. struct ZipEntry
  15275. {
  15276. /** The name of the file, which may also include a partial pathname. */
  15277. String filename;
  15278. /** The file's original size. */
  15279. unsigned int uncompressedSize;
  15280. /** The last time the file was modified. */
  15281. Time fileTime;
  15282. };
  15283. /** Returns the number of items in the zip file. */
  15284. int getNumEntries() const noexcept;
  15285. /** Returns a structure that describes one of the entries in the zip file.
  15286. This may return zero if the index is out of range.
  15287. @see ZipFile::ZipEntry
  15288. */
  15289. const ZipEntry* getEntry (int index) const noexcept;
  15290. /** Returns the index of the first entry with a given filename.
  15291. This uses a case-sensitive comparison to look for a filename in the
  15292. list of entries. It might return -1 if no match is found.
  15293. @see ZipFile::ZipEntry
  15294. */
  15295. int getIndexOfFileName (const String& fileName) const noexcept;
  15296. /** Returns a structure that describes one of the entries in the zip file.
  15297. This uses a case-sensitive comparison to look for a filename in the
  15298. list of entries. It might return 0 if no match is found.
  15299. @see ZipFile::ZipEntry
  15300. */
  15301. const ZipEntry* getEntry (const String& fileName) const noexcept;
  15302. /** Sorts the list of entries, based on the filename.
  15303. */
  15304. void sortEntriesByFilename();
  15305. /** Creates a stream that can read from one of the zip file's entries.
  15306. The stream that is returned must be deleted by the caller (and
  15307. zero might be returned if a stream can't be opened for some reason).
  15308. The stream must not be used after the ZipFile object that created
  15309. has been deleted.
  15310. */
  15311. InputStream* createStreamForEntry (int index);
  15312. /** Creates a stream that can read from one of the zip file's entries.
  15313. The stream that is returned must be deleted by the caller (and
  15314. zero might be returned if a stream can't be opened for some reason).
  15315. The stream must not be used after the ZipFile object that created
  15316. has been deleted.
  15317. */
  15318. InputStream* createStreamForEntry (ZipEntry& entry);
  15319. /** Uncompresses all of the files in the zip file.
  15320. This will expand all the entries into a target directory. The relative
  15321. paths of the entries are used.
  15322. @param targetDirectory the root folder to uncompress to
  15323. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15324. @returns true if all the files are successfully unzipped
  15325. */
  15326. bool uncompressTo (const File& targetDirectory,
  15327. bool shouldOverwriteFiles = true);
  15328. /** Uncompresses one of the entries from the zip file.
  15329. This will expand the entry and write it in a target directory. The entry's path is used to
  15330. determine which subfolder of the target should contain the new file.
  15331. @param index the index of the entry to uncompress
  15332. @param targetDirectory the root folder to uncompress into
  15333. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15334. @returns true if the files is successfully unzipped
  15335. */
  15336. bool uncompressEntry (int index,
  15337. const File& targetDirectory,
  15338. bool shouldOverwriteFiles = true);
  15339. /** Used to create a new zip file.
  15340. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  15341. then you can write it to a stream with write().
  15342. Currently this just stores the files with no compression.. That will be added
  15343. soon!
  15344. */
  15345. class Builder
  15346. {
  15347. public:
  15348. Builder();
  15349. ~Builder();
  15350. /** Adds a file while should be added to the archive.
  15351. The file isn't read immediately, all the files will be read later when the writeToStream()
  15352. method is called.
  15353. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  15354. If the storedPathName parameter is specified, you can customise the partial pathname that
  15355. will be stored for this file.
  15356. */
  15357. void addFile (const File& fileToAdd, int compressionLevel,
  15358. const String& storedPathName = String::empty);
  15359. /** Generates the zip file, writing it to the specified stream. */
  15360. bool writeToStream (OutputStream& target) const;
  15361. private:
  15362. class Item;
  15363. friend class OwnedArray<Item>;
  15364. OwnedArray<Item> items;
  15365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  15366. };
  15367. private:
  15368. class ZipInputStream;
  15369. class ZipFilenameComparator;
  15370. class ZipEntryInfo;
  15371. friend class ZipInputStream;
  15372. friend class ZipFilenameComparator;
  15373. friend class ZipEntryInfo;
  15374. OwnedArray <ZipEntryInfo> entries;
  15375. CriticalSection lock;
  15376. InputStream* inputStream;
  15377. ScopedPointer <InputStream> streamToDelete;
  15378. ScopedPointer <InputSource> inputSource;
  15379. #if JUCE_DEBUG
  15380. int numOpenStreams;
  15381. #endif
  15382. void init();
  15383. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  15384. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  15385. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  15386. };
  15387. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  15388. /*** End of inlined file: juce_ZipFile.h ***/
  15389. #endif
  15390. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15391. /*** Start of inlined file: juce_MACAddress.h ***/
  15392. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15393. #define __JUCE_MACADDRESS_JUCEHEADER__
  15394. /**
  15395. A wrapper for a streaming (TCP) socket.
  15396. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15397. sockets, you could also try the InterprocessConnection class.
  15398. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15399. */
  15400. class JUCE_API MACAddress
  15401. {
  15402. public:
  15403. /** Populates a list of the MAC addresses of all the available network cards. */
  15404. static void findAllAddresses (Array<MACAddress>& results);
  15405. /** Creates a null address (00-00-00-00-00-00). */
  15406. MACAddress();
  15407. /** Creates a copy of another address. */
  15408. MACAddress (const MACAddress& other);
  15409. /** Creates a copy of another address. */
  15410. MACAddress& operator= (const MACAddress& other);
  15411. /** Creates an address from 6 bytes. */
  15412. explicit MACAddress (const uint8 bytes[6]);
  15413. /** Returns a pointer to the 6 bytes that make up this address. */
  15414. const uint8* getBytes() const noexcept { return asBytes; }
  15415. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  15416. const String toString() const;
  15417. /** Returns the address in the lower 6 bytes of an int64.
  15418. This uses a little-endian arrangement, with the first byte of the address being
  15419. stored in the least-significant byte of the result value.
  15420. */
  15421. int64 toInt64() const noexcept;
  15422. /** Returns true if this address is null (00-00-00-00-00-00). */
  15423. bool isNull() const noexcept;
  15424. bool operator== (const MACAddress& other) const noexcept;
  15425. bool operator!= (const MACAddress& other) const noexcept;
  15426. private:
  15427. #ifndef DOXYGEN
  15428. union
  15429. {
  15430. uint64 asInt64;
  15431. uint8 asBytes[6];
  15432. };
  15433. #endif
  15434. };
  15435. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  15436. /*** End of inlined file: juce_MACAddress.h ***/
  15437. #endif
  15438. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15439. /*** Start of inlined file: juce_Socket.h ***/
  15440. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15441. #define __JUCE_SOCKET_JUCEHEADER__
  15442. /**
  15443. A wrapper for a streaming (TCP) socket.
  15444. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15445. sockets, you could also try the InterprocessConnection class.
  15446. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15447. */
  15448. class JUCE_API StreamingSocket
  15449. {
  15450. public:
  15451. /** Creates an uninitialised socket.
  15452. To connect it, use the connect() method, after which you can read() or write()
  15453. to it.
  15454. To wait for other sockets to connect to this one, the createListener() method
  15455. enters "listener" mode, and can be used to spawn new sockets for each connection
  15456. that comes along.
  15457. */
  15458. StreamingSocket();
  15459. /** Destructor. */
  15460. ~StreamingSocket();
  15461. /** Binds the socket to the specified local port.
  15462. @returns true on success; false may indicate that another socket is already bound
  15463. on the same port
  15464. */
  15465. bool bindToPort (int localPortNumber);
  15466. /** Tries to connect the socket to hostname:port.
  15467. If timeOutMillisecs is 0, then this method will block until the operating system
  15468. rejects the connection (which could take a long time).
  15469. @returns true if it succeeds.
  15470. @see isConnected
  15471. */
  15472. bool connect (const String& remoteHostname,
  15473. int remotePortNumber,
  15474. int timeOutMillisecs = 3000);
  15475. /** True if the socket is currently connected. */
  15476. bool isConnected() const noexcept { return connected; }
  15477. /** Closes the connection. */
  15478. void close();
  15479. /** Returns the name of the currently connected host. */
  15480. const String& getHostName() const noexcept { return hostName; }
  15481. /** Returns the port number that's currently open. */
  15482. int getPort() const noexcept { return portNumber; }
  15483. /** True if the socket is connected to this machine rather than over the network. */
  15484. bool isLocal() const noexcept;
  15485. /** Waits until the socket is ready for reading or writing.
  15486. If readyForReading is true, it will wait until the socket is ready for
  15487. reading; if false, it will wait until it's ready for writing.
  15488. If the timeout is < 0, it will wait forever, or else will give up after
  15489. the specified time.
  15490. If the socket is ready on return, this returns 1. If it times-out before
  15491. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15492. */
  15493. int waitUntilReady (bool readyForReading,
  15494. int timeoutMsecs) const;
  15495. /** Reads bytes from the socket.
  15496. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15497. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15498. flag is false, the method will return as much data as is currently available
  15499. without blocking.
  15500. @returns the number of bytes read, or -1 if there was an error.
  15501. @see waitUntilReady
  15502. */
  15503. int read (void* destBuffer, int maxBytesToRead,
  15504. bool blockUntilSpecifiedAmountHasArrived);
  15505. /** Writes bytes to the socket from a buffer.
  15506. Note that this method will block unless you have checked the socket is ready
  15507. for writing before calling it (see the waitUntilReady() method).
  15508. @returns the number of bytes written, or -1 if there was an error.
  15509. */
  15510. int write (const void* sourceBuffer, int numBytesToWrite);
  15511. /** Puts this socket into "listener" mode.
  15512. When in this mode, your thread can call waitForNextConnection() repeatedly,
  15513. which will spawn new sockets for each new connection, so that these can
  15514. be handled in parallel by other threads.
  15515. @param portNumber the port number to listen on
  15516. @param localHostName the interface address to listen on - pass an empty
  15517. string to listen on all addresses
  15518. @returns true if it manages to open the socket successfully.
  15519. @see waitForNextConnection
  15520. */
  15521. bool createListener (int portNumber, const String& localHostName = String::empty);
  15522. /** When in "listener" mode, this waits for a connection and spawns it as a new
  15523. socket.
  15524. The object that gets returned will be owned by the caller.
  15525. This method can only be called after using createListener().
  15526. @see createListener
  15527. */
  15528. StreamingSocket* waitForNextConnection() const;
  15529. private:
  15530. String hostName;
  15531. int volatile portNumber, handle;
  15532. bool connected, isListener;
  15533. StreamingSocket (const String& hostname, int portNumber, int handle);
  15534. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  15535. };
  15536. /**
  15537. A wrapper for a datagram (UDP) socket.
  15538. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15539. sockets, you could also try the InterprocessConnection class.
  15540. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  15541. */
  15542. class JUCE_API DatagramSocket
  15543. {
  15544. public:
  15545. /**
  15546. Creates an (uninitialised) datagram socket.
  15547. The localPortNumber is the port on which to bind this socket. If this value is 0,
  15548. the port number is assigned by the operating system.
  15549. To use the socket for sending, call the connect() method. This will not immediately
  15550. make a connection, but will save the destination you've provided. After this, you can
  15551. call read() or write().
  15552. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15553. (may require extra privileges on linux)
  15554. To wait for other sockets to connect to this one, call waitForNextConnection().
  15555. */
  15556. DatagramSocket (int localPortNumber,
  15557. bool enableBroadcasting = false);
  15558. /** Destructor. */
  15559. ~DatagramSocket();
  15560. /** Binds the socket to the specified local port.
  15561. @returns true on success; false may indicate that another socket is already bound
  15562. on the same port
  15563. */
  15564. bool bindToPort (int localPortNumber);
  15565. /** Tries to connect the socket to hostname:port.
  15566. If timeOutMillisecs is 0, then this method will block until the operating system
  15567. rejects the connection (which could take a long time).
  15568. @returns true if it succeeds.
  15569. @see isConnected
  15570. */
  15571. bool connect (const String& remoteHostname,
  15572. int remotePortNumber,
  15573. int timeOutMillisecs = 3000);
  15574. /** True if the socket is currently connected. */
  15575. bool isConnected() const noexcept { return connected; }
  15576. /** Closes the connection. */
  15577. void close();
  15578. /** Returns the name of the currently connected host. */
  15579. const String& getHostName() const noexcept { return hostName; }
  15580. /** Returns the port number that's currently open. */
  15581. int getPort() const noexcept { return portNumber; }
  15582. /** True if the socket is connected to this machine rather than over the network. */
  15583. bool isLocal() const noexcept;
  15584. /** Waits until the socket is ready for reading or writing.
  15585. If readyForReading is true, it will wait until the socket is ready for
  15586. reading; if false, it will wait until it's ready for writing.
  15587. If the timeout is < 0, it will wait forever, or else will give up after
  15588. the specified time.
  15589. If the socket is ready on return, this returns 1. If it times-out before
  15590. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15591. */
  15592. int waitUntilReady (bool readyForReading,
  15593. int timeoutMsecs) const;
  15594. /** Reads bytes from the socket.
  15595. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15596. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15597. flag is false, the method will return as much data as is currently available
  15598. without blocking.
  15599. @returns the number of bytes read, or -1 if there was an error.
  15600. @see waitUntilReady
  15601. */
  15602. int read (void* destBuffer, int maxBytesToRead,
  15603. bool blockUntilSpecifiedAmountHasArrived);
  15604. /** Writes bytes to the socket from a buffer.
  15605. Note that this method will block unless you have checked the socket is ready
  15606. for writing before calling it (see the waitUntilReady() method).
  15607. @returns the number of bytes written, or -1 if there was an error.
  15608. */
  15609. int write (const void* sourceBuffer, int numBytesToWrite);
  15610. /** This waits for incoming data to be sent, and returns a socket that can be used
  15611. to read it.
  15612. The object that gets returned is owned by the caller, and can't be used for
  15613. sending, but can be used to read the data.
  15614. */
  15615. DatagramSocket* waitForNextConnection() const;
  15616. private:
  15617. String hostName;
  15618. int volatile portNumber, handle;
  15619. bool connected, allowBroadcast;
  15620. void* serverAddress;
  15621. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15623. };
  15624. #endif // __JUCE_SOCKET_JUCEHEADER__
  15625. /*** End of inlined file: juce_Socket.h ***/
  15626. #endif
  15627. #ifndef __JUCE_URL_JUCEHEADER__
  15628. /*** Start of inlined file: juce_URL.h ***/
  15629. #ifndef __JUCE_URL_JUCEHEADER__
  15630. #define __JUCE_URL_JUCEHEADER__
  15631. /**
  15632. Represents a URL and has a bunch of useful functions to manipulate it.
  15633. This class can be used to launch URLs in browsers, and also to create
  15634. InputStreams that can read from remote http or ftp sources.
  15635. */
  15636. class JUCE_API URL
  15637. {
  15638. public:
  15639. /** Creates an empty URL. */
  15640. URL();
  15641. /** Creates a URL from a string. */
  15642. URL (const String& url);
  15643. /** Creates a copy of another URL. */
  15644. URL (const URL& other);
  15645. /** Destructor. */
  15646. ~URL();
  15647. /** Copies this URL from another one. */
  15648. URL& operator= (const URL& other);
  15649. /** Returns a string version of the URL.
  15650. If includeGetParameters is true and any parameters have been set with the
  15651. withParameter() method, then the string will have these appended on the
  15652. end and url-encoded.
  15653. */
  15654. const String toString (bool includeGetParameters) const;
  15655. /** True if it seems to be valid. */
  15656. bool isWellFormed() const;
  15657. /** Returns just the domain part of the URL.
  15658. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15659. */
  15660. const String getDomain() const;
  15661. /** Returns the path part of the URL.
  15662. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15663. */
  15664. const String getSubPath() const;
  15665. /** Returns the scheme of the URL.
  15666. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15667. include the colon).
  15668. */
  15669. const String getScheme() const;
  15670. /** Returns a new version of this URL that uses a different sub-path.
  15671. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15672. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15673. */
  15674. const URL withNewSubPath (const String& newPath) const;
  15675. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15676. Any control characters in the value will be encoded.
  15677. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15678. would produce a new url whose toString(true) method would return
  15679. "www.fish.com?amount=some+fish".
  15680. */
  15681. const URL withParameter (const String& parameterName,
  15682. const String& parameterValue) const;
  15683. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15684. When performing a POST where one of your parameters is a binary file, this
  15685. lets you specify the file.
  15686. Note that the filename is stored, but the file itself won't actually be read
  15687. until this URL is later used to create a network input stream.
  15688. */
  15689. const URL withFileToUpload (const String& parameterName,
  15690. const File& fileToUpload,
  15691. const String& mimeType) const;
  15692. /** Returns a set of all the parameters encoded into the url.
  15693. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15694. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15695. The values returned will have been cleaned up to remove any escape characters.
  15696. @see getNamedParameter, withParameter
  15697. */
  15698. const StringPairArray& getParameters() const;
  15699. /** Returns the set of files that should be uploaded as part of a POST operation.
  15700. This is the set of files that were added to the URL with the withFileToUpload()
  15701. method.
  15702. */
  15703. const StringPairArray& getFilesToUpload() const;
  15704. /** Returns the set of mime types associated with each of the upload files.
  15705. */
  15706. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15707. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15708. If you're setting the POST data, be careful not to have any parameters set
  15709. as well, otherwise it'll all get thrown in together, and might not have the
  15710. desired effect.
  15711. If the URL already contains some POST data, this will replace it, rather
  15712. than being appended to it.
  15713. This data will only be used if you specify a post operation when you call
  15714. createInputStream().
  15715. */
  15716. const URL withPOSTData (const String& postData) const;
  15717. /** Returns the data that was set using withPOSTData().
  15718. */
  15719. const String getPostData() const { return postData; }
  15720. /** Tries to launch the system's default browser to open the URL.
  15721. Returns true if this seems to have worked.
  15722. */
  15723. bool launchInDefaultBrowser() const;
  15724. /** Takes a guess as to whether a string might be a valid website address.
  15725. This isn't foolproof!
  15726. */
  15727. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15728. /** Takes a guess as to whether a string might be a valid email address.
  15729. This isn't foolproof!
  15730. */
  15731. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15732. /** This callback function can be used by the createInputStream() method.
  15733. It allows your app to receive progress updates during a lengthy POST operation. If you
  15734. want to continue the operation, this should return true, or false to abort.
  15735. */
  15736. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15737. /** Attempts to open a stream that can read from this URL.
  15738. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15739. the paramters, otherwise it'll encode them into the
  15740. URL and do a 'GET'.
  15741. @param progressCallback if this is non-zero, it lets you supply a callback function
  15742. to keep track of the operation's progress. This can be useful
  15743. for lengthy POST operations, so that you can provide user feedback.
  15744. @param progressCallbackContext if a callback is specified, this value will be passed to
  15745. the function
  15746. @param extraHeaders if not empty, this string is appended onto the headers that
  15747. are used for the request. It must therefore be a valid set of HTML
  15748. header directives, separated by newlines.
  15749. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15750. a negative number, it will be infinite. Otherwise it specifies a
  15751. time in milliseconds.
  15752. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15753. in the response will be stored in this array
  15754. @returns an input stream that the caller must delete, or a null pointer if there was an
  15755. error trying to open it.
  15756. */
  15757. InputStream* createInputStream (bool usePostCommand,
  15758. OpenStreamProgressCallback* progressCallback = nullptr,
  15759. void* progressCallbackContext = nullptr,
  15760. const String& extraHeaders = String::empty,
  15761. int connectionTimeOutMs = 0,
  15762. StringPairArray* responseHeaders = nullptr) const;
  15763. /** Tries to download the entire contents of this URL into a binary data block.
  15764. If it succeeds, this will return true and append the data it read onto the end
  15765. of the memory block.
  15766. @param destData the memory block to append the new data to
  15767. @param usePostCommand whether to use a POST command to get the data (uses
  15768. a GET command if this is false)
  15769. @see readEntireTextStream, readEntireXmlStream
  15770. */
  15771. bool readEntireBinaryStream (MemoryBlock& destData,
  15772. bool usePostCommand = false) const;
  15773. /** Tries to download the entire contents of this URL as a string.
  15774. If it fails, this will return an empty string, otherwise it will return the
  15775. contents of the downloaded file. If you need to distinguish between a read
  15776. operation that fails and one that returns an empty string, you'll need to use
  15777. a different method, such as readEntireBinaryStream().
  15778. @param usePostCommand whether to use a POST command to get the data (uses
  15779. a GET command if this is false)
  15780. @see readEntireBinaryStream, readEntireXmlStream
  15781. */
  15782. const String readEntireTextStream (bool usePostCommand = false) const;
  15783. /** Tries to download the entire contents of this URL and parse it as XML.
  15784. If it fails, or if the text that it reads can't be parsed as XML, this will
  15785. return 0.
  15786. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15787. this object when no longer needed.
  15788. @param usePostCommand whether to use a POST command to get the data (uses
  15789. a GET command if this is false)
  15790. @see readEntireBinaryStream, readEntireTextStream
  15791. */
  15792. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15793. /** Adds escape sequences to a string to encode any characters that aren't
  15794. legal in a URL.
  15795. E.g. any spaces will be replaced with "%20".
  15796. This is the opposite of removeEscapeChars().
  15797. If isParameter is true, it means that the string is going to be used
  15798. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15799. be legal in a URL.
  15800. @see removeEscapeChars
  15801. */
  15802. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15803. bool isParameter);
  15804. /** Replaces any escape character sequences in a string with their original
  15805. character codes.
  15806. E.g. any instances of "%20" will be replaced by a space.
  15807. This is the opposite of addEscapeChars().
  15808. @see addEscapeChars
  15809. */
  15810. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15811. private:
  15812. String url, postData;
  15813. StringPairArray parameters, filesToUpload, mimeTypes;
  15814. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15815. OpenStreamProgressCallback* progressCallback,
  15816. void* progressCallbackContext, const String& headers,
  15817. const int timeOutMs, StringPairArray* responseHeaders);
  15818. JUCE_LEAK_DETECTOR (URL);
  15819. };
  15820. #endif // __JUCE_URL_JUCEHEADER__
  15821. /*** End of inlined file: juce_URL.h ***/
  15822. #endif
  15823. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15824. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15825. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15826. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15827. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  15828. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15829. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15830. /**
  15831. Holds a pointer to an object which can optionally be deleted when this pointer
  15832. goes out of scope.
  15833. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  15834. not the object is deleted.
  15835. @see ScopedPointer
  15836. */
  15837. template <class ObjectType>
  15838. class OptionalScopedPointer
  15839. {
  15840. public:
  15841. /** Creates an empty OptionalScopedPointer. */
  15842. OptionalScopedPointer() : shouldDelete (false) {}
  15843. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  15844. the OptionalScopedPointer will delete it.
  15845. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  15846. deleting the object when it is itself deleted. If this parameter is false, then the
  15847. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  15848. */
  15849. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  15850. : object (objectToHold), shouldDelete (takeOwnership)
  15851. {
  15852. }
  15853. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15854. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15855. as ownership of the managed object is transferred to this object.
  15856. The flag to indicate whether or not to delete the managed object is also
  15857. copied from the source object.
  15858. */
  15859. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  15860. : object (objectToTransferFrom.release()),
  15861. shouldDelete (objectToTransferFrom.shouldDelete)
  15862. {
  15863. }
  15864. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15865. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15866. as ownership of the managed object is transferred to this object.
  15867. The ownership flag that says whether or not to delete the managed object is also
  15868. copied from the source object.
  15869. */
  15870. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  15871. {
  15872. if (object != objectToTransferFrom.object)
  15873. {
  15874. clear();
  15875. object = objectToTransferFrom.object;
  15876. }
  15877. shouldDelete = objectToTransferFrom.shouldDelete;
  15878. return *this;
  15879. }
  15880. /** The destructor may or may not delete the object that is being held, depending on the
  15881. takeOwnership flag that was specified when the object was first passed into an
  15882. OptionalScopedPointer constructor.
  15883. */
  15884. ~OptionalScopedPointer()
  15885. {
  15886. clear();
  15887. }
  15888. /** Returns the object that this pointer is managing. */
  15889. inline operator ObjectType*() const noexcept { return object; }
  15890. /** Returns the object that this pointer is managing. */
  15891. inline ObjectType& operator*() const noexcept { return *object; }
  15892. /** Lets you access methods and properties of the object that this pointer is holding. */
  15893. inline ObjectType* operator->() const noexcept { return object; }
  15894. /** Removes the current object from this OptionalScopedPointer without deleting it.
  15895. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  15896. */
  15897. ObjectType* release() noexcept { return object.release(); }
  15898. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  15899. ownership of it.
  15900. */
  15901. void clear()
  15902. {
  15903. if (! shouldDelete)
  15904. object.release();
  15905. }
  15906. /** Swaps this object with another OptionalScopedPointer.
  15907. The two objects simply exchange their states.
  15908. */
  15909. void swapWith (OptionalScopedPointer<ObjectType>& other) noexcept
  15910. {
  15911. object.swapWith (other.object);
  15912. std::swap (shouldDelete, other.shouldDelete);
  15913. }
  15914. private:
  15915. ScopedPointer<ObjectType> object;
  15916. bool shouldDelete;
  15917. };
  15918. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15919. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  15920. /** Wraps another input stream, and reads from it using an intermediate buffer
  15921. If you're using an input stream such as a file input stream, and making lots of
  15922. small read accesses to it, it's probably sensible to wrap it in one of these,
  15923. so that the source stream gets accessed in larger chunk sizes, meaning less
  15924. work for the underlying stream.
  15925. */
  15926. class JUCE_API BufferedInputStream : public InputStream
  15927. {
  15928. public:
  15929. /** Creates a BufferedInputStream from an input source.
  15930. @param sourceStream the source stream to read from
  15931. @param bufferSize the size of reservoir to use to buffer the source
  15932. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15933. deleted by this object when it is itself deleted.
  15934. */
  15935. BufferedInputStream (InputStream* sourceStream,
  15936. int bufferSize,
  15937. bool deleteSourceWhenDestroyed);
  15938. /** Creates a BufferedInputStream from an input source.
  15939. @param sourceStream the source stream to read from - the source stream must not
  15940. be deleted until this object has been destroyed.
  15941. @param bufferSize the size of reservoir to use to buffer the source
  15942. */
  15943. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  15944. /** Destructor.
  15945. This may also delete the source stream, if that option was chosen when the
  15946. buffered stream was created.
  15947. */
  15948. ~BufferedInputStream();
  15949. int64 getTotalLength();
  15950. int64 getPosition();
  15951. bool setPosition (int64 newPosition);
  15952. int read (void* destBuffer, int maxBytesToRead);
  15953. const String readString();
  15954. bool isExhausted();
  15955. private:
  15956. OptionalScopedPointer<InputStream> source;
  15957. int bufferSize;
  15958. int64 position, lastReadPos, bufferStart, bufferOverlap;
  15959. HeapBlock <char> buffer;
  15960. void ensureBuffered();
  15961. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  15962. };
  15963. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15964. /*** End of inlined file: juce_BufferedInputStream.h ***/
  15965. #endif
  15966. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15967. /*** Start of inlined file: juce_FileInputSource.h ***/
  15968. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15969. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15970. /**
  15971. A type of InputSource that represents a normal file.
  15972. @see InputSource
  15973. */
  15974. class JUCE_API FileInputSource : public InputSource
  15975. {
  15976. public:
  15977. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  15978. ~FileInputSource();
  15979. InputStream* createInputStream();
  15980. InputStream* createInputStreamFor (const String& relatedItemPath);
  15981. int64 hashCode() const;
  15982. private:
  15983. const File file;
  15984. bool useFileTimeInHashGeneration;
  15985. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  15986. };
  15987. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15988. /*** End of inlined file: juce_FileInputSource.h ***/
  15989. #endif
  15990. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15991. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15992. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15993. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15994. /**
  15995. A stream which uses zlib to compress the data written into it.
  15996. @see GZIPDecompressorInputStream
  15997. */
  15998. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  15999. {
  16000. public:
  16001. /** Creates a compression stream.
  16002. @param destStream the stream into which the compressed data should
  16003. be written
  16004. @param compressionLevel how much to compress the data, between 1 and 9, where
  16005. 1 is the fastest/lowest compression, and 9 is the
  16006. slowest/highest compression. Any value outside this range
  16007. indicates that a default compression level should be used.
  16008. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  16009. this stream is destroyed
  16010. @param windowBits this is used internally to change the window size used
  16011. by zlib - leave it as 0 unless you specifically need to set
  16012. its value for some reason
  16013. */
  16014. GZIPCompressorOutputStream (OutputStream* destStream,
  16015. int compressionLevel = 0,
  16016. bool deleteDestStreamWhenDestroyed = false,
  16017. int windowBits = 0);
  16018. /** Destructor. */
  16019. ~GZIPCompressorOutputStream();
  16020. void flush();
  16021. int64 getPosition();
  16022. bool setPosition (int64 newPosition);
  16023. bool write (const void* destBuffer, int howMany);
  16024. /** These are preset values that can be used for the constructor's windowBits paramter.
  16025. For more info about this, see the zlib documentation for its windowBits parameter.
  16026. */
  16027. enum WindowBitsValues
  16028. {
  16029. windowBitsRaw = -15,
  16030. windowBitsGZIP = 15 + 16
  16031. };
  16032. private:
  16033. OptionalScopedPointer<OutputStream> destStream;
  16034. HeapBlock <uint8> buffer;
  16035. class GZIPCompressorHelper;
  16036. friend class ScopedPointer <GZIPCompressorHelper>;
  16037. ScopedPointer <GZIPCompressorHelper> helper;
  16038. bool doNextBlock();
  16039. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  16040. };
  16041. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16042. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16043. #endif
  16044. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16045. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16046. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16047. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16048. /**
  16049. This stream will decompress a source-stream using zlib.
  16050. Tip: if you're reading lots of small items from one of these streams, you
  16051. can increase the performance enormously by passing it through a
  16052. BufferedInputStream, so that it has to read larger blocks less often.
  16053. @see GZIPCompressorOutputStream
  16054. */
  16055. class JUCE_API GZIPDecompressorInputStream : public InputStream
  16056. {
  16057. public:
  16058. /** Creates a decompressor stream.
  16059. @param sourceStream the stream to read from
  16060. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  16061. when this object is destroyed
  16062. @param noWrap this is used internally by the ZipFile class
  16063. and should be ignored by user applications
  16064. @param uncompressedStreamLength if the creator knows the length that the
  16065. uncompressed stream will be, then it can supply this
  16066. value, which will be returned by getTotalLength()
  16067. */
  16068. GZIPDecompressorInputStream (InputStream* sourceStream,
  16069. bool deleteSourceWhenDestroyed,
  16070. bool noWrap = false,
  16071. int64 uncompressedStreamLength = -1);
  16072. /** Creates a decompressor stream.
  16073. @param sourceStream the stream to read from - the source stream must not be
  16074. deleted until this object has been destroyed
  16075. */
  16076. GZIPDecompressorInputStream (InputStream& sourceStream);
  16077. /** Destructor. */
  16078. ~GZIPDecompressorInputStream();
  16079. int64 getPosition();
  16080. bool setPosition (int64 pos);
  16081. int64 getTotalLength();
  16082. bool isExhausted();
  16083. int read (void* destBuffer, int maxBytesToRead);
  16084. private:
  16085. OptionalScopedPointer<InputStream> sourceStream;
  16086. const int64 uncompressedStreamLength;
  16087. const bool noWrap;
  16088. bool isEof;
  16089. int activeBufferSize;
  16090. int64 originalSourcePos, currentPos;
  16091. HeapBlock <uint8> buffer;
  16092. class GZIPDecompressHelper;
  16093. friend class ScopedPointer <GZIPDecompressHelper>;
  16094. ScopedPointer <GZIPDecompressHelper> helper;
  16095. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  16096. };
  16097. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16098. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16099. #endif
  16100. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  16101. #endif
  16102. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  16103. #endif
  16104. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16105. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  16106. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16107. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16108. /**
  16109. Allows a block of data and to be accessed as a stream.
  16110. This can either be used to refer to a shared block of memory, or can make its
  16111. own internal copy of the data when the MemoryInputStream is created.
  16112. */
  16113. class JUCE_API MemoryInputStream : public InputStream
  16114. {
  16115. public:
  16116. /** Creates a MemoryInputStream.
  16117. @param sourceData the block of data to use as the stream's source
  16118. @param sourceDataSize the number of bytes in the source data block
  16119. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  16120. the source data, so this data shouldn't be changed
  16121. for the lifetime of the stream; if this parameter is
  16122. true, the stream will make its own copy of the
  16123. data and use that.
  16124. */
  16125. MemoryInputStream (const void* sourceData,
  16126. size_t sourceDataSize,
  16127. bool keepInternalCopyOfData);
  16128. /** Creates a MemoryInputStream.
  16129. @param data a block of data to use as the stream's source
  16130. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  16131. the source data, so this data shouldn't be changed
  16132. for the lifetime of the stream; if this parameter is
  16133. true, the stream will make its own copy of the
  16134. data and use that.
  16135. */
  16136. MemoryInputStream (const MemoryBlock& data,
  16137. bool keepInternalCopyOfData);
  16138. /** Destructor. */
  16139. ~MemoryInputStream();
  16140. int64 getPosition();
  16141. bool setPosition (int64 pos);
  16142. int64 getTotalLength();
  16143. bool isExhausted();
  16144. int read (void* destBuffer, int maxBytesToRead);
  16145. private:
  16146. const char* data;
  16147. size_t dataSize, position;
  16148. MemoryBlock internalCopy;
  16149. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  16150. };
  16151. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16152. /*** End of inlined file: juce_MemoryInputStream.h ***/
  16153. #endif
  16154. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16155. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  16156. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16157. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16158. /**
  16159. Writes data to an internal memory buffer, which grows as required.
  16160. The data that was written into the stream can then be accessed later as
  16161. a contiguous block of memory.
  16162. */
  16163. class JUCE_API MemoryOutputStream : public OutputStream
  16164. {
  16165. public:
  16166. /** Creates an empty memory stream ready for writing into.
  16167. @param initialSize the intial amount of capacity to allocate for writing into
  16168. */
  16169. MemoryOutputStream (size_t initialSize = 256);
  16170. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  16171. Note that the destination block will always be larger than the amount of data
  16172. that has been written to the stream, because the MemoryOutputStream keeps some
  16173. spare capactity at its end. To trim the block's size down to fit the actual
  16174. data, call flush(), or delete the MemoryOutputStream.
  16175. @param memoryBlockToWriteTo the block into which new data will be written.
  16176. @param appendToExistingBlockContent if this is true, the contents of the block will be
  16177. kept, and new data will be appended to it. If false,
  16178. the block will be cleared before use
  16179. */
  16180. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  16181. bool appendToExistingBlockContent);
  16182. /** Destructor.
  16183. This will free any data that was written to it.
  16184. */
  16185. ~MemoryOutputStream();
  16186. /** Returns a pointer to the data that has been written to the stream.
  16187. @see getDataSize
  16188. */
  16189. const void* getData() const noexcept;
  16190. /** Returns the number of bytes of data that have been written to the stream.
  16191. @see getData
  16192. */
  16193. size_t getDataSize() const noexcept { return size; }
  16194. /** Resets the stream, clearing any data that has been written to it so far. */
  16195. void reset() noexcept;
  16196. /** Increases the internal storage capacity to be able to contain at least the specified
  16197. amount of data without needing to be resized.
  16198. */
  16199. void preallocate (size_t bytesToPreallocate);
  16200. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  16201. const String toUTF8() const;
  16202. /** Attempts to detect the encoding of the data and convert it to a string.
  16203. @see String::createStringFromData
  16204. */
  16205. const String toString() const;
  16206. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  16207. capacity off the block, so that its length matches the amount of actual data that
  16208. has been written so far.
  16209. */
  16210. void flush();
  16211. bool write (const void* buffer, int howMany);
  16212. int64 getPosition() { return position; }
  16213. bool setPosition (int64 newPosition);
  16214. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  16215. private:
  16216. MemoryBlock& data;
  16217. MemoryBlock internalBlock;
  16218. size_t position, size;
  16219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  16220. };
  16221. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  16222. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  16223. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16224. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  16225. #endif
  16226. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  16227. #endif
  16228. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16229. /*** Start of inlined file: juce_SubregionStream.h ***/
  16230. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16231. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16232. /** Wraps another input stream, and reads from a specific part of it.
  16233. This lets you take a subsection of a stream and present it as an entire
  16234. stream in its own right.
  16235. */
  16236. class JUCE_API SubregionStream : public InputStream
  16237. {
  16238. public:
  16239. /** Creates a SubregionStream from an input source.
  16240. @param sourceStream the source stream to read from
  16241. @param startPositionInSourceStream this is the position in the source stream that
  16242. corresponds to position 0 in this stream
  16243. @param lengthOfSourceStream this specifies the maximum number of bytes
  16244. from the source stream that will be passed through
  16245. by this stream. When the position of this stream
  16246. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  16247. If the length passed in here is greater than the length
  16248. of the source stream (as returned by getTotalLength()),
  16249. then the smaller value will be used.
  16250. Passing a negative value for this parameter means it
  16251. will keep reading until the source's end-of-stream.
  16252. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16253. deleted by this object when it is itself deleted.
  16254. */
  16255. SubregionStream (InputStream* sourceStream,
  16256. int64 startPositionInSourceStream,
  16257. int64 lengthOfSourceStream,
  16258. bool deleteSourceWhenDestroyed);
  16259. /** Destructor.
  16260. This may also delete the source stream, if that option was chosen when the
  16261. buffered stream was created.
  16262. */
  16263. ~SubregionStream();
  16264. int64 getTotalLength();
  16265. int64 getPosition();
  16266. bool setPosition (int64 newPosition);
  16267. int read (void* destBuffer, int maxBytesToRead);
  16268. bool isExhausted();
  16269. private:
  16270. OptionalScopedPointer<InputStream> source;
  16271. const int64 startPositionInSourceStream, lengthOfSourceStream;
  16272. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  16273. };
  16274. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16275. /*** End of inlined file: juce_SubregionStream.h ***/
  16276. #endif
  16277. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  16278. #endif
  16279. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16280. /*** Start of inlined file: juce_Expression.h ***/
  16281. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16282. #define __JUCE_EXPRESSION_JUCEHEADER__
  16283. /**
  16284. A class for dynamically evaluating simple numeric expressions.
  16285. This class can parse a simple C-style string expression involving floating point
  16286. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  16287. are supported, as well as parentheses, and any alphanumeric identifiers are
  16288. assumed to be named symbols which will be resolved when the expression is
  16289. evaluated.
  16290. Expressions which use identifiers and functions require a subclass of
  16291. Expression::Scope to be supplied when evaluating them, and this object
  16292. is expected to be able to resolve the symbol names and perform the functions that
  16293. are used.
  16294. */
  16295. class JUCE_API Expression
  16296. {
  16297. public:
  16298. /** Creates a simple expression with a value of 0. */
  16299. Expression();
  16300. /** Destructor. */
  16301. ~Expression();
  16302. /** Creates a simple expression with a specified constant value. */
  16303. explicit Expression (double constant);
  16304. /** Creates a copy of an expression. */
  16305. Expression (const Expression& other);
  16306. /** Copies another expression. */
  16307. Expression& operator= (const Expression& other);
  16308. /** Creates an expression by parsing a string.
  16309. If there's a syntax error in the string, this will throw a ParseError exception.
  16310. @throws ParseError
  16311. */
  16312. explicit Expression (const String& stringToParse);
  16313. /** Returns a string version of the expression. */
  16314. const String toString() const;
  16315. /** Returns an expression which is an addtion operation of two existing expressions. */
  16316. const Expression operator+ (const Expression& other) const;
  16317. /** Returns an expression which is a subtraction operation of two existing expressions. */
  16318. const Expression operator- (const Expression& other) const;
  16319. /** Returns an expression which is a multiplication operation of two existing expressions. */
  16320. const Expression operator* (const Expression& other) const;
  16321. /** Returns an expression which is a division operation of two existing expressions. */
  16322. const Expression operator/ (const Expression& other) const;
  16323. /** Returns an expression which performs a negation operation on an existing expression. */
  16324. const Expression operator-() const;
  16325. /** Returns an Expression which is an identifier reference. */
  16326. static const Expression symbol (const String& symbol);
  16327. /** Returns an Expression which is a function call. */
  16328. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  16329. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  16330. to indicate where it finished.
  16331. The pointer is incremented so that on return, it indicates the character that follows
  16332. the end of the expression that was parsed.
  16333. If there's a syntax error in the string, this will throw a ParseError exception.
  16334. @throws ParseError
  16335. */
  16336. static const Expression parse (String::CharPointerType& stringToParse);
  16337. /** When evaluating an Expression object, this class is used to resolve symbols and
  16338. perform functions that the expression uses.
  16339. */
  16340. class JUCE_API Scope
  16341. {
  16342. public:
  16343. Scope();
  16344. virtual ~Scope();
  16345. /** Returns some kind of globally unique ID that identifies this scope. */
  16346. virtual const String getScopeUID() const;
  16347. /** Returns the value of a symbol.
  16348. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  16349. The member value is set to the part of the symbol that followed the dot, if there is
  16350. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  16351. @throws Expression::EvaluationError
  16352. */
  16353. virtual const Expression getSymbolValue (const String& symbol) const;
  16354. /** Executes a named function.
  16355. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  16356. @throws Expression::EvaluationError
  16357. */
  16358. virtual double evaluateFunction (const String& functionName,
  16359. const double* parameters, int numParameters) const;
  16360. /** Used as a callback by the Scope::visitRelativeScope() method.
  16361. You should never create an instance of this class yourself, it's used by the
  16362. expression evaluation code.
  16363. */
  16364. class Visitor
  16365. {
  16366. public:
  16367. virtual ~Visitor() {}
  16368. virtual void visit (const Scope&) = 0;
  16369. };
  16370. /** Creates a Scope object for a named scope, and then calls a visitor
  16371. to do some kind of processing with this new scope.
  16372. If the name is valid, this method must create a suitable (temporary) Scope
  16373. object to represent it, and must call the Visitor::visit() method with this
  16374. new scope.
  16375. */
  16376. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  16377. };
  16378. /** Evaluates this expression, without using a Scope.
  16379. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  16380. min, max are available.
  16381. To find out about any errors during evaluation, use the other version of this method which
  16382. takes a String parameter.
  16383. */
  16384. double evaluate() const;
  16385. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16386. or functions that it uses.
  16387. To find out about any errors during evaluation, use the other version of this method which
  16388. takes a String parameter.
  16389. */
  16390. double evaluate (const Scope& scope) const;
  16391. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16392. or functions that it uses.
  16393. */
  16394. double evaluate (const Scope& scope, String& evaluationError) const;
  16395. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  16396. to make the expression resolve to a target value.
  16397. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  16398. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  16399. case they might just be adjusted by adding a constant to the original expression.
  16400. @throws Expression::EvaluationError
  16401. */
  16402. const Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  16403. /** Represents a symbol that is used in an Expression. */
  16404. struct Symbol
  16405. {
  16406. Symbol (const String& scopeUID, const String& symbolName);
  16407. bool operator== (const Symbol&) const noexcept;
  16408. bool operator!= (const Symbol&) const noexcept;
  16409. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  16410. String symbolName; /**< The name of the symbol. */
  16411. };
  16412. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  16413. const Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  16414. /** Returns true if this expression makes use of the specified symbol.
  16415. If a suitable scope is supplied, the search will dereference and recursively check
  16416. all symbols, so that it can be determined whether this expression relies on the given
  16417. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  16418. whether the expression contains any direct references to the symbol.
  16419. @throws Expression::EvaluationError
  16420. */
  16421. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  16422. /** Returns true if this expression contains any symbols. */
  16423. bool usesAnySymbols() const;
  16424. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  16425. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  16426. /** An exception that can be thrown by Expression::parse(). */
  16427. class ParseError : public std::exception
  16428. {
  16429. public:
  16430. ParseError (const String& message);
  16431. String description;
  16432. };
  16433. /** Expression type.
  16434. @see Expression::getType()
  16435. */
  16436. enum Type
  16437. {
  16438. constantType,
  16439. functionType,
  16440. operatorType,
  16441. symbolType
  16442. };
  16443. /** Returns the type of this expression. */
  16444. Type getType() const noexcept;
  16445. /** If this expression is a symbol, function or operator, this returns its identifier. */
  16446. const String getSymbolOrFunction() const;
  16447. /** Returns the number of inputs to this expression.
  16448. @see getInput
  16449. */
  16450. int getNumInputs() const;
  16451. /** Retrieves one of the inputs to this expression.
  16452. @see getNumInputs
  16453. */
  16454. const Expression getInput (int index) const;
  16455. private:
  16456. class Term;
  16457. class Helpers;
  16458. friend class Term;
  16459. friend class Helpers;
  16460. friend class ScopedPointer<Term>;
  16461. friend class ReferenceCountedObjectPtr<Term>;
  16462. ReferenceCountedObjectPtr<Term> term;
  16463. explicit Expression (Term* term);
  16464. };
  16465. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  16466. /*** End of inlined file: juce_Expression.h ***/
  16467. #endif
  16468. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  16469. #endif
  16470. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16471. /*** Start of inlined file: juce_Random.h ***/
  16472. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16473. #define __JUCE_RANDOM_JUCEHEADER__
  16474. /**
  16475. A random number generator.
  16476. You can create a Random object and use it to generate a sequence of random numbers.
  16477. As a handy shortcut to avoid having to create and seed one yourself, you can call
  16478. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  16479. app launches.
  16480. */
  16481. class JUCE_API Random
  16482. {
  16483. public:
  16484. /** Creates a Random object based on a seed value.
  16485. For a given seed value, the subsequent numbers generated by this object
  16486. will be predictable, so a good idea is to set this value based
  16487. on the time, e.g.
  16488. new Random (Time::currentTimeMillis())
  16489. */
  16490. explicit Random (int64 seedValue) noexcept;
  16491. /** Destructor. */
  16492. ~Random() noexcept;
  16493. /** Returns the next random 32 bit integer.
  16494. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  16495. */
  16496. int nextInt() noexcept;
  16497. /** Returns the next random number, limited to a given range.
  16498. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  16499. */
  16500. int nextInt (int maxValue) noexcept;
  16501. /** Returns the next 64-bit random number.
  16502. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  16503. */
  16504. int64 nextInt64() noexcept;
  16505. /** Returns the next random floating-point number.
  16506. @returns a random value in the range 0 to 1.0
  16507. */
  16508. float nextFloat() noexcept;
  16509. /** Returns the next random floating-point number.
  16510. @returns a random value in the range 0 to 1.0
  16511. */
  16512. double nextDouble() noexcept;
  16513. /** Returns the next random boolean value.
  16514. */
  16515. bool nextBool() noexcept;
  16516. /** Returns a BigInteger containing a random number.
  16517. @returns a random value in the range 0 to (maximumValue - 1).
  16518. */
  16519. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  16520. /** Sets a range of bits in a BigInteger to random values. */
  16521. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  16522. /** To avoid the overhead of having to create a new Random object whenever
  16523. you need a number, this is a shared application-wide object that
  16524. can be used.
  16525. It's not thread-safe though, so threads should use their own Random object.
  16526. */
  16527. static Random& getSystemRandom() noexcept;
  16528. /** Resets this Random object to a given seed value. */
  16529. void setSeed (int64 newSeed) noexcept;
  16530. /** Merges this object's seed with another value.
  16531. This sets the seed to be a value created by combining the current seed and this
  16532. new value.
  16533. */
  16534. void combineSeed (int64 seedValue) noexcept;
  16535. /** Reseeds this generator using a value generated from various semi-random system
  16536. properties like the current time, etc.
  16537. Because this function convolves the time with the last seed value, calling
  16538. it repeatedly will increase the randomness of the final result.
  16539. */
  16540. void setSeedRandomly();
  16541. private:
  16542. int64 seed;
  16543. JUCE_LEAK_DETECTOR (Random);
  16544. };
  16545. #endif // __JUCE_RANDOM_JUCEHEADER__
  16546. /*** End of inlined file: juce_Random.h ***/
  16547. #endif
  16548. #ifndef __JUCE_RANGE_JUCEHEADER__
  16549. #endif
  16550. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16551. #endif
  16552. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16553. #endif
  16554. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16555. #endif
  16556. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16557. #endif
  16558. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16559. #endif
  16560. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16561. #endif
  16562. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16563. #endif
  16564. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16565. #endif
  16566. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16567. #endif
  16568. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16569. /*** Start of inlined file: juce_WeakReference.h ***/
  16570. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16571. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16572. /**
  16573. This class acts as a pointer which will automatically become null if the object
  16574. to which it points is deleted.
  16575. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16576. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16577. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16578. E.g.
  16579. @code
  16580. class MyObject
  16581. {
  16582. public:
  16583. MyObject()
  16584. {
  16585. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16586. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16587. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16588. // the first call to getWeakReference().
  16589. }
  16590. ~MyObject()
  16591. {
  16592. // This will zero all the references - you need to call this in your destructor.
  16593. masterReference.clear();
  16594. }
  16595. // Your object must provide a method that looks pretty much identical to this (except
  16596. // for the templated class name, of course).
  16597. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16598. {
  16599. return masterReference (this);
  16600. }
  16601. private:
  16602. // You need to embed one of these inside your object. It can be private.
  16603. WeakReference<MyObject>::Master masterReference;
  16604. };
  16605. // Here's an example of using a pointer..
  16606. MyObject* n = new MyObject();
  16607. WeakReference<MyObject> myObjectRef = n;
  16608. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16609. delete n;
  16610. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16611. @endcode
  16612. @see WeakReference::Master
  16613. */
  16614. template <class ObjectType>
  16615. class WeakReference
  16616. {
  16617. public:
  16618. /** Creates a null SafePointer. */
  16619. WeakReference() noexcept {}
  16620. /** Creates a WeakReference that points at the given object. */
  16621. WeakReference (ObjectType* const object) : holder (object != nullptr ? object->getWeakReference() : nullptr) {}
  16622. /** Creates a copy of another WeakReference. */
  16623. WeakReference (const WeakReference& other) noexcept : holder (other.holder) {}
  16624. /** Copies another pointer to this one. */
  16625. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16626. /** Copies another pointer to this one. */
  16627. WeakReference& operator= (ObjectType* const newObject) { holder = newObject != nullptr ? newObject->getWeakReference() : nullptr; return *this; }
  16628. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16629. ObjectType* get() const noexcept { return holder != nullptr ? holder->get() : nullptr; }
  16630. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16631. operator ObjectType*() const noexcept { return get(); }
  16632. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16633. ObjectType* operator->() noexcept { return get(); }
  16634. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16635. const ObjectType* operator->() const noexcept { return get(); }
  16636. /** This returns true if this reference has been pointing at an object, but that object has
  16637. since been deleted.
  16638. If this reference was only ever pointing at a null pointer, this will return false. Using
  16639. operator=() to make this refer to a different object will reset this flag to match the status
  16640. of the reference from which you're copying.
  16641. */
  16642. bool wasObjectDeleted() const noexcept { return holder != nullptr && holder->get() == nullptr; }
  16643. bool operator== (ObjectType* const object) const noexcept { return get() == object; }
  16644. bool operator!= (ObjectType* const object) const noexcept { return get() != object; }
  16645. /** This class is used internally by the WeakReference class - don't use it directly
  16646. in your code!
  16647. @see WeakReference
  16648. */
  16649. class SharedPointer : public ReferenceCountedObject
  16650. {
  16651. public:
  16652. explicit SharedPointer (ObjectType* const owner_) noexcept : owner (owner_) {}
  16653. inline ObjectType* get() const noexcept { return owner; }
  16654. void clearPointer() noexcept { owner = nullptr; }
  16655. private:
  16656. ObjectType* volatile owner;
  16657. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16658. };
  16659. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16660. /**
  16661. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16662. See the WeakReference class notes for an example of how to use this class.
  16663. @see WeakReference
  16664. */
  16665. class Master
  16666. {
  16667. public:
  16668. Master() noexcept {}
  16669. ~Master()
  16670. {
  16671. // You must remember to call clear() in your source object's destructor! See the notes
  16672. // for the WeakReference class for an example of how to do this.
  16673. jassert (sharedPointer == nullptr || sharedPointer->get() == nullptr);
  16674. }
  16675. /** The first call to this method will create an internal object that is shared by all weak
  16676. references to the object.
  16677. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16678. class notes for an example.
  16679. */
  16680. const SharedRef& operator() (ObjectType* const object)
  16681. {
  16682. if (sharedPointer == nullptr)
  16683. {
  16684. sharedPointer = new SharedPointer (object);
  16685. }
  16686. else
  16687. {
  16688. // You're trying to create a weak reference to an object that has already been deleted!!
  16689. jassert (sharedPointer->get() != nullptr);
  16690. }
  16691. return sharedPointer;
  16692. }
  16693. /** The object that owns this master pointer should call this before it gets destroyed,
  16694. to zero all the references to this object that may be out there. See the WeakReference
  16695. class notes for an example of how to do this.
  16696. */
  16697. void clear()
  16698. {
  16699. if (sharedPointer != nullptr)
  16700. sharedPointer->clearPointer();
  16701. }
  16702. private:
  16703. SharedRef sharedPointer;
  16704. JUCE_DECLARE_NON_COPYABLE (Master);
  16705. };
  16706. private:
  16707. SharedRef holder;
  16708. };
  16709. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16710. /*** End of inlined file: juce_WeakReference.h ***/
  16711. #endif
  16712. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16713. #endif
  16714. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16715. #endif
  16716. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16717. #endif
  16718. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16719. #endif
  16720. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16721. #endif
  16722. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16723. #endif
  16724. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16725. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16726. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16727. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16728. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16729. string into a localised version using the LocalisedStrings class.
  16730. @see LocalisedStrings
  16731. */
  16732. #define TRANS(stringLiteral) \
  16733. JUCE_NAMESPACE::LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16734. /**
  16735. Used to convert strings to localised foreign-language versions.
  16736. This is basically a look-up table of strings and their translated equivalents.
  16737. It can be loaded from a text file, so that you can supply a set of localised
  16738. versions of strings that you use in your app.
  16739. To use it in your code, simply call the translate() method on each string that
  16740. might have foreign versions, and if none is found, the method will just return
  16741. the original string.
  16742. The translation file should start with some lines specifying a description of
  16743. the language it contains, and also a list of ISO country codes where it might
  16744. be appropriate to use the file. After that, each line of the file should contain
  16745. a pair of quoted strings with an '=' sign.
  16746. E.g. for a french translation, the file might be:
  16747. @code
  16748. language: French
  16749. countries: fr be mc ch lu
  16750. "hello" = "bonjour"
  16751. "goodbye" = "au revoir"
  16752. @endcode
  16753. If the strings need to contain a quote character, they can use '\"' instead, and
  16754. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  16755. (you can use this to add comments).
  16756. Note that this is a singleton class, so don't create or destroy the object directly.
  16757. There's also a TRANS(text) macro defined to make it easy to use the this.
  16758. E.g. @code
  16759. printSomething (TRANS("hello"));
  16760. @endcode
  16761. This macro is used in the Juce classes themselves, so your application has a chance to
  16762. intercept and translate any internal Juce text strings that might be shown. (You can easily
  16763. get a list of all the messages by searching for the TRANS() macro in the Juce source
  16764. code).
  16765. */
  16766. class JUCE_API LocalisedStrings
  16767. {
  16768. public:
  16769. /** Creates a set of translations from the text of a translation file.
  16770. When you create one of these, you can call setCurrentMappings() to make it
  16771. the set of mappings that the system's using.
  16772. */
  16773. LocalisedStrings (const String& fileContents);
  16774. /** Creates a set of translations from a file.
  16775. When you create one of these, you can call setCurrentMappings() to make it
  16776. the set of mappings that the system's using.
  16777. */
  16778. LocalisedStrings (const File& fileToLoad);
  16779. /** Destructor. */
  16780. ~LocalisedStrings();
  16781. /** Selects the current set of mappings to be used by the system.
  16782. The object you pass in will be automatically deleted when no longer needed, so
  16783. don't keep a pointer to it. You can also pass in zero to remove the current
  16784. mappings.
  16785. See also the TRANS() macro, which uses the current set to do its translation.
  16786. @see translateWithCurrentMappings
  16787. */
  16788. static void setCurrentMappings (LocalisedStrings* newTranslations);
  16789. /** Returns the currently selected set of mappings.
  16790. This is the object that was last passed to setCurrentMappings(). It may
  16791. be 0 if none has been created.
  16792. */
  16793. static LocalisedStrings* getCurrentMappings();
  16794. /** Tries to translate a string using the currently selected set of mappings.
  16795. If no mapping has been set, or if the mapping doesn't contain a translation
  16796. for the string, this will just return the original string.
  16797. See also the TRANS() macro, which uses this method to do its translation.
  16798. @see setCurrentMappings, getCurrentMappings
  16799. */
  16800. static const String translateWithCurrentMappings (const String& text);
  16801. /** Tries to translate a string using the currently selected set of mappings.
  16802. If no mapping has been set, or if the mapping doesn't contain a translation
  16803. for the string, this will just return the original string.
  16804. See also the TRANS() macro, which uses this method to do its translation.
  16805. @see setCurrentMappings, getCurrentMappings
  16806. */
  16807. static const String translateWithCurrentMappings (const char* text);
  16808. /** Attempts to look up a string and return its localised version.
  16809. If the string isn't found in the list, the original string will be returned.
  16810. */
  16811. const String translate (const String& text) const;
  16812. /** Returns the name of the language specified in the translation file.
  16813. This is specified in the file using a line starting with "language:", e.g.
  16814. @code
  16815. language: german
  16816. @endcode
  16817. */
  16818. const String getLanguageName() const { return languageName; }
  16819. /** Returns the list of suitable country codes listed in the translation file.
  16820. These is specified in the file using a line starting with "countries:", e.g.
  16821. @code
  16822. countries: fr be mc ch lu
  16823. @endcode
  16824. The country codes are supposed to be 2-character ISO complient codes.
  16825. */
  16826. const StringArray getCountryCodes() const { return countryCodes; }
  16827. /** Indicates whether to use a case-insensitive search when looking up a string.
  16828. This defaults to true.
  16829. */
  16830. void setIgnoresCase (bool shouldIgnoreCase);
  16831. private:
  16832. String languageName;
  16833. StringArray countryCodes;
  16834. StringPairArray translations;
  16835. void loadFromText (const String& fileContents);
  16836. JUCE_LEAK_DETECTOR (LocalisedStrings);
  16837. };
  16838. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16839. /*** End of inlined file: juce_LocalisedStrings.h ***/
  16840. #endif
  16841. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  16842. #endif
  16843. #ifndef __JUCE_STRING_JUCEHEADER__
  16844. #endif
  16845. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16846. #endif
  16847. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16848. #endif
  16849. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16850. #endif
  16851. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16852. /*** Start of inlined file: juce_XmlDocument.h ***/
  16853. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16854. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16855. /**
  16856. Parses a text-based XML document and creates an XmlElement object from it.
  16857. The parser will parse DTDs to load external entities but won't
  16858. check the document for validity against the DTD.
  16859. e.g.
  16860. @code
  16861. XmlDocument myDocument (File ("myfile.xml"));
  16862. XmlElement* mainElement = myDocument.getDocumentElement();
  16863. if (mainElement == nullptr)
  16864. {
  16865. String error = myDocument.getLastParseError();
  16866. }
  16867. else
  16868. {
  16869. ..use the element
  16870. }
  16871. @endcode
  16872. Or you can use the static helper methods for quick parsing..
  16873. @code
  16874. XmlElement* xml = XmlDocument::parse (myXmlFile);
  16875. if (xml != nullptr && xml->hasTagName ("foobar"))
  16876. {
  16877. ...etc
  16878. @endcode
  16879. @see XmlElement
  16880. */
  16881. class JUCE_API XmlDocument
  16882. {
  16883. public:
  16884. /** Creates an XmlDocument from the xml text.
  16885. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16886. */
  16887. XmlDocument (const String& documentText);
  16888. /** Creates an XmlDocument from a file.
  16889. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16890. */
  16891. XmlDocument (const File& file);
  16892. /** Destructor. */
  16893. ~XmlDocument();
  16894. /** Creates an XmlElement object to represent the main document node.
  16895. This method will do the actual parsing of the text, and if there's a
  16896. parse error, it may returns 0 (and you can find out the error using
  16897. the getLastParseError() method).
  16898. See also the parse() methods, which provide a shorthand way to quickly
  16899. parse a file or string.
  16900. @param onlyReadOuterDocumentElement if true, the parser will only read the
  16901. first section of the file, and will only
  16902. return the outer document element - this
  16903. allows quick checking of large files to
  16904. see if they contain the correct type of
  16905. tag, without having to parse the entire file
  16906. @returns a new XmlElement which the caller will need to delete, or null if
  16907. there was an error.
  16908. @see getLastParseError
  16909. */
  16910. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  16911. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  16912. @returns the error, or an empty string if there was no error.
  16913. */
  16914. const String& getLastParseError() const noexcept;
  16915. /** Sets an input source object to use for parsing documents that reference external entities.
  16916. If the document has been created from a file, this probably won't be needed, but
  16917. if you're parsing some text and there might be a DTD that references external
  16918. files, you may need to create a custom input source that can retrieve the
  16919. other files it needs.
  16920. The object that is passed-in will be deleted automatically when no longer needed.
  16921. @see InputSource
  16922. */
  16923. void setInputSource (InputSource* newSource) noexcept;
  16924. /** Sets a flag to change the treatment of empty text elements.
  16925. If this is true (the default state), then any text elements that contain only
  16926. whitespace characters will be ingored during parsing. If you need to catch
  16927. whitespace-only text, then you should set this to false before calling the
  16928. getDocumentElement() method.
  16929. */
  16930. void setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept;
  16931. /** A handy static method that parses a file.
  16932. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16933. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16934. */
  16935. static XmlElement* parse (const File& file);
  16936. /** A handy static method that parses some XML data.
  16937. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16938. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16939. */
  16940. static XmlElement* parse (const String& xmlData);
  16941. private:
  16942. String originalText;
  16943. String::CharPointerType input;
  16944. bool outOfData, errorOccurred;
  16945. String lastError, dtdText;
  16946. StringArray tokenisedDTD;
  16947. bool needToLoadDTD, ignoreEmptyTextElements;
  16948. ScopedPointer <InputSource> inputSource;
  16949. void setLastError (const String& desc, bool carryOn);
  16950. void skipHeader();
  16951. void skipNextWhiteSpace();
  16952. juce_wchar readNextChar() noexcept;
  16953. XmlElement* readNextElement (bool alsoParseSubElements);
  16954. void readChildElements (XmlElement* parent);
  16955. int findNextTokenLength() noexcept;
  16956. void readQuotedString (String& result);
  16957. void readEntity (String& result);
  16958. const String getFileContents (const String& filename) const;
  16959. const String expandEntity (const String& entity);
  16960. const String expandExternalEntity (const String& entity);
  16961. const String getParameterEntity (const String& entity);
  16962. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  16963. };
  16964. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  16965. /*** End of inlined file: juce_XmlDocument.h ***/
  16966. #endif
  16967. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  16968. #endif
  16969. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  16970. #endif
  16971. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16972. /*** Start of inlined file: juce_InterProcessLock.h ***/
  16973. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16974. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16975. /**
  16976. Acts as a critical section which processes can use to block each other.
  16977. @see CriticalSection
  16978. */
  16979. class JUCE_API InterProcessLock
  16980. {
  16981. public:
  16982. /** Creates a lock object.
  16983. @param name a name that processes will use to identify this lock object
  16984. */
  16985. explicit InterProcessLock (const String& name);
  16986. /** Destructor.
  16987. This will also release the lock if it's currently held by this process.
  16988. */
  16989. ~InterProcessLock();
  16990. /** Attempts to lock the critical section.
  16991. @param timeOutMillisecs how many milliseconds to wait if the lock
  16992. is already held by another process - a value of
  16993. 0 will return immediately, negative values will wait
  16994. forever
  16995. @returns true if the lock could be gained within the timeout period, or
  16996. false if the timeout expired.
  16997. */
  16998. bool enter (int timeOutMillisecs = -1);
  16999. /** Releases the lock if it's currently held by this process.
  17000. */
  17001. void exit();
  17002. /**
  17003. Automatically locks and unlocks an InterProcessLock object.
  17004. This works like a ScopedLock, but using an InterprocessLock rather than
  17005. a CriticalSection.
  17006. @see ScopedLock
  17007. */
  17008. class ScopedLockType
  17009. {
  17010. public:
  17011. /** Creates a scoped lock.
  17012. As soon as it is created, this will lock the InterProcessLock, and
  17013. when the ScopedLockType object is deleted, the InterProcessLock will
  17014. be unlocked.
  17015. Note that since an InterprocessLock can fail due to errors, you should check
  17016. isLocked() to make sure that the lock was successful before using it.
  17017. Make sure this object is created and deleted by the same thread,
  17018. otherwise there are no guarantees what will happen! Best just to use it
  17019. as a local stack object, rather than creating one with the new() operator.
  17020. */
  17021. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  17022. /** Destructor.
  17023. The InterProcessLock will be unlocked when the destructor is called.
  17024. Make sure this object is created and deleted by the same thread,
  17025. otherwise there are no guarantees what will happen!
  17026. */
  17027. inline ~ScopedLockType() { lock_.exit(); }
  17028. /** Returns true if the InterProcessLock was successfully locked. */
  17029. bool isLocked() const noexcept { return lockWasSuccessful; }
  17030. private:
  17031. InterProcessLock& lock_;
  17032. bool lockWasSuccessful;
  17033. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  17034. };
  17035. private:
  17036. class Pimpl;
  17037. friend class ScopedPointer <Pimpl>;
  17038. ScopedPointer <Pimpl> pimpl;
  17039. CriticalSection lock;
  17040. String name;
  17041. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  17042. };
  17043. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17044. /*** End of inlined file: juce_InterProcessLock.h ***/
  17045. #endif
  17046. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17047. /*** Start of inlined file: juce_Process.h ***/
  17048. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17049. #define __JUCE_PROCESS_JUCEHEADER__
  17050. /** Represents the current executable's process.
  17051. This contains methods for controlling the current application at the
  17052. process-level.
  17053. @see Thread, JUCEApplication
  17054. */
  17055. class JUCE_API Process
  17056. {
  17057. public:
  17058. enum ProcessPriority
  17059. {
  17060. LowPriority = 0,
  17061. NormalPriority = 1,
  17062. HighPriority = 2,
  17063. RealtimePriority = 3
  17064. };
  17065. /** Changes the current process's priority.
  17066. @param priority the process priority, where
  17067. 0=low, 1=normal, 2=high, 3=realtime
  17068. */
  17069. static void setPriority (const ProcessPriority priority);
  17070. /** Kills the current process immediately.
  17071. This is an emergency process terminator that kills the application
  17072. immediately - it's intended only for use only when something goes
  17073. horribly wrong.
  17074. @see JUCEApplication::quit
  17075. */
  17076. static void terminate();
  17077. /** Returns true if this application process is the one that the user is
  17078. currently using.
  17079. */
  17080. static bool isForegroundProcess();
  17081. /** Raises the current process's privilege level.
  17082. Does nothing if this isn't supported by the current OS, or if process
  17083. privilege level is fixed.
  17084. */
  17085. static void raisePrivilege();
  17086. /** Lowers the current process's privilege level.
  17087. Does nothing if this isn't supported by the current OS, or if process
  17088. privilege level is fixed.
  17089. */
  17090. static void lowerPrivilege();
  17091. /** Returns true if this process is being hosted by a debugger.
  17092. */
  17093. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  17094. private:
  17095. Process();
  17096. JUCE_DECLARE_NON_COPYABLE (Process);
  17097. };
  17098. #endif // __JUCE_PROCESS_JUCEHEADER__
  17099. /*** End of inlined file: juce_Process.h ***/
  17100. #endif
  17101. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17102. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  17103. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17104. #define __JUCE_READWRITELOCK_JUCEHEADER__
  17105. /*** Start of inlined file: juce_SpinLock.h ***/
  17106. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17107. #define __JUCE_SPINLOCK_JUCEHEADER__
  17108. /**
  17109. A simple spin-lock class that can be used as a simple, low-overhead mutex for
  17110. uncontended situations.
  17111. Note that unlike a CriticalSection, this type of lock is not re-entrant, and may
  17112. be less efficient when used it a highly contended situation, but it's very small and
  17113. requires almost no initialisation.
  17114. It's most appropriate for simple situations where you're only going to hold the
  17115. lock for a very brief time.
  17116. @see CriticalSection
  17117. */
  17118. class JUCE_API SpinLock
  17119. {
  17120. public:
  17121. inline SpinLock() noexcept {}
  17122. inline ~SpinLock() noexcept {}
  17123. /** Acquires the lock.
  17124. This will block until the lock has been successfully acquired by this thread.
  17125. Note that a SpinLock is NOT re-entrant, and is not smart enough to know whether the
  17126. caller thread already has the lock - so if a thread tries to acquire a lock that it
  17127. already holds, this method will never return!
  17128. It's strongly recommended that you never call this method directly - instead use the
  17129. ScopedLockType class to manage the locking using an RAII pattern instead.
  17130. */
  17131. void enter() const noexcept;
  17132. /** Attempts to acquire the lock, returning true if this was successful. */
  17133. bool tryEnter() const noexcept;
  17134. /** Releases the lock. */
  17135. inline void exit() const noexcept
  17136. {
  17137. jassert (lock.value == 1); // Agh! Releasing a lock that isn't currently held!
  17138. lock = 0;
  17139. }
  17140. /** Provides the type of scoped lock to use for locking a SpinLock. */
  17141. typedef GenericScopedLock <SpinLock> ScopedLockType;
  17142. /** Provides the type of scoped unlocker to use with a SpinLock. */
  17143. typedef GenericScopedUnlock <SpinLock> ScopedUnlockType;
  17144. private:
  17145. mutable Atomic<int> lock;
  17146. JUCE_DECLARE_NON_COPYABLE (SpinLock);
  17147. };
  17148. #endif // __JUCE_SPINLOCK_JUCEHEADER__
  17149. /*** End of inlined file: juce_SpinLock.h ***/
  17150. /*** Start of inlined file: juce_WaitableEvent.h ***/
  17151. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17152. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  17153. /**
  17154. Allows threads to wait for events triggered by other threads.
  17155. A thread can call wait() on a WaitableObject, and this will suspend the
  17156. calling thread until another thread wakes it up by calling the signal()
  17157. method.
  17158. */
  17159. class JUCE_API WaitableEvent
  17160. {
  17161. public:
  17162. /** Creates a WaitableEvent object.
  17163. @param manualReset If this is false, the event will be reset automatically when the wait()
  17164. method is called. If manualReset is true, then once the event is signalled,
  17165. the only way to reset it will be by calling the reset() method.
  17166. */
  17167. WaitableEvent (bool manualReset = false) noexcept;
  17168. /** Destructor.
  17169. If other threads are waiting on this object when it gets deleted, this
  17170. can cause nasty errors, so be careful!
  17171. */
  17172. ~WaitableEvent() noexcept;
  17173. /** Suspends the calling thread until the event has been signalled.
  17174. This will wait until the object's signal() method is called by another thread,
  17175. or until the timeout expires.
  17176. After the event has been signalled, this method will return true and if manualReset
  17177. was set to false in the WaitableEvent's constructor, then the event will be reset.
  17178. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  17179. value will cause it to wait forever.
  17180. @returns true if the object has been signalled, false if the timeout expires first.
  17181. @see signal, reset
  17182. */
  17183. bool wait (int timeOutMilliseconds = -1) const noexcept;
  17184. /** Wakes up any threads that are currently waiting on this object.
  17185. If signal() is called when nothing is waiting, the next thread to call wait()
  17186. will return immediately and reset the signal.
  17187. @see wait, reset
  17188. */
  17189. void signal() const noexcept;
  17190. /** Resets the event to an unsignalled state.
  17191. If it's not already signalled, this does nothing.
  17192. */
  17193. void reset() const noexcept;
  17194. private:
  17195. void* internal;
  17196. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  17197. };
  17198. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  17199. /*** End of inlined file: juce_WaitableEvent.h ***/
  17200. /*** Start of inlined file: juce_Thread.h ***/
  17201. #ifndef __JUCE_THREAD_JUCEHEADER__
  17202. #define __JUCE_THREAD_JUCEHEADER__
  17203. /**
  17204. Encapsulates a thread.
  17205. Subclasses derive from Thread and implement the run() method, in which they
  17206. do their business. The thread can then be started with the startThread() method
  17207. and controlled with various other methods.
  17208. This class also contains some thread-related static methods, such
  17209. as sleep(), yield(), getCurrentThreadId() etc.
  17210. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  17211. MessageManagerLock
  17212. */
  17213. class JUCE_API Thread
  17214. {
  17215. public:
  17216. /**
  17217. Creates a thread.
  17218. When first created, the thread is not running. Use the startThread()
  17219. method to start it.
  17220. */
  17221. explicit Thread (const String& threadName);
  17222. /** Destructor.
  17223. Deleting a Thread object that is running will only give the thread a
  17224. brief opportunity to stop itself cleanly, so it's recommended that you
  17225. should always call stopThread() with a decent timeout before deleting,
  17226. to avoid the thread being forcibly killed (which is a Bad Thing).
  17227. */
  17228. virtual ~Thread();
  17229. /** Must be implemented to perform the thread's actual code.
  17230. Remember that the thread must regularly check the threadShouldExit()
  17231. method whilst running, and if this returns true it should return from
  17232. the run() method as soon as possible to avoid being forcibly killed.
  17233. @see threadShouldExit, startThread
  17234. */
  17235. virtual void run() = 0;
  17236. // Thread control functions..
  17237. /** Starts the thread running.
  17238. This will start the thread's run() method.
  17239. (if it's already started, startThread() won't do anything).
  17240. @see stopThread
  17241. */
  17242. void startThread();
  17243. /** Starts the thread with a given priority.
  17244. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  17245. If the thread is already running, its priority will be changed.
  17246. @see startThread, setPriority
  17247. */
  17248. void startThread (int priority);
  17249. /** Attempts to stop the thread running.
  17250. This method will cause the threadShouldExit() method to return true
  17251. and call notify() in case the thread is currently waiting.
  17252. Hopefully the thread will then respond to this by exiting cleanly, and
  17253. the stopThread method will wait for a given time-period for this to
  17254. happen.
  17255. If the thread is stuck and fails to respond after the time-out, it gets
  17256. forcibly killed, which is a very bad thing to happen, as it could still
  17257. be holding locks, etc. which are needed by other parts of your program.
  17258. @param timeOutMilliseconds The number of milliseconds to wait for the
  17259. thread to finish before killing it by force. A negative
  17260. value in here will wait forever.
  17261. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  17262. */
  17263. void stopThread (int timeOutMilliseconds);
  17264. /** Returns true if the thread is currently active */
  17265. bool isThreadRunning() const;
  17266. /** Sets a flag to tell the thread it should stop.
  17267. Calling this means that the threadShouldExit() method will then return true.
  17268. The thread should be regularly checking this to see whether it should exit.
  17269. If your thread makes use of wait(), you might want to call notify() after calling
  17270. this method, to interrupt any waits that might be in progress, and allow it
  17271. to reach a point where it can exit.
  17272. @see threadShouldExit
  17273. @see waitForThreadToExit
  17274. */
  17275. void signalThreadShouldExit();
  17276. /** Checks whether the thread has been told to stop running.
  17277. Threads need to check this regularly, and if it returns true, they should
  17278. return from their run() method at the first possible opportunity.
  17279. @see signalThreadShouldExit
  17280. */
  17281. inline bool threadShouldExit() const { return threadShouldExit_; }
  17282. /** Waits for the thread to stop.
  17283. This will waits until isThreadRunning() is false or until a timeout expires.
  17284. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  17285. is less than zero, it will wait forever.
  17286. @returns true if the thread exits, or false if the timeout expires first.
  17287. */
  17288. bool waitForThreadToExit (int timeOutMilliseconds) const;
  17289. /** Changes the thread's priority.
  17290. May return false if for some reason the priority can't be changed.
  17291. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  17292. of 5 is normal.
  17293. */
  17294. bool setPriority (int priority);
  17295. /** Changes the priority of the caller thread.
  17296. Similar to setPriority(), but this static method acts on the caller thread.
  17297. May return false if for some reason the priority can't be changed.
  17298. @see setPriority
  17299. */
  17300. static bool setCurrentThreadPriority (int priority);
  17301. /** Sets the affinity mask for the thread.
  17302. This will only have an effect next time the thread is started - i.e. if the
  17303. thread is already running when called, it'll have no effect.
  17304. @see setCurrentThreadAffinityMask
  17305. */
  17306. void setAffinityMask (uint32 affinityMask);
  17307. /** Changes the affinity mask for the caller thread.
  17308. This will change the affinity mask for the thread that calls this static method.
  17309. @see setAffinityMask
  17310. */
  17311. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  17312. // this can be called from any thread that needs to pause..
  17313. static void JUCE_CALLTYPE sleep (int milliseconds);
  17314. /** Yields the calling thread's current time-slot. */
  17315. static void JUCE_CALLTYPE yield();
  17316. /** Makes the thread wait for a notification.
  17317. This puts the thread to sleep until either the timeout period expires, or
  17318. another thread calls the notify() method to wake it up.
  17319. A negative time-out value means that the method will wait indefinitely.
  17320. @returns true if the event has been signalled, false if the timeout expires.
  17321. */
  17322. bool wait (int timeOutMilliseconds) const;
  17323. /** Wakes up the thread.
  17324. If the thread has called the wait() method, this will wake it up.
  17325. @see wait
  17326. */
  17327. void notify() const;
  17328. /** A value type used for thread IDs.
  17329. @see getCurrentThreadId(), getThreadId()
  17330. */
  17331. typedef void* ThreadID;
  17332. /** Returns an id that identifies the caller thread.
  17333. To find the ID of a particular thread object, use getThreadId().
  17334. @returns a unique identifier that identifies the calling thread.
  17335. @see getThreadId
  17336. */
  17337. static ThreadID getCurrentThreadId();
  17338. /** Finds the thread object that is currently running.
  17339. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  17340. object associated with them, so this will return 0.
  17341. */
  17342. static Thread* getCurrentThread();
  17343. /** Returns the ID of this thread.
  17344. That means the ID of this thread object - not of the thread that's calling the method.
  17345. This can change when the thread is started and stopped, and will be invalid if the
  17346. thread's not actually running.
  17347. @see getCurrentThreadId
  17348. */
  17349. ThreadID getThreadId() const noexcept { return threadId_; }
  17350. /** Returns the name of the thread.
  17351. This is the name that gets set in the constructor.
  17352. */
  17353. const String getThreadName() const { return threadName_; }
  17354. /** Returns the number of currently-running threads.
  17355. @returns the number of Thread objects known to be currently running.
  17356. @see stopAllThreads
  17357. */
  17358. static int getNumRunningThreads();
  17359. /** Tries to stop all currently-running threads.
  17360. This will attempt to stop all the threads known to be running at the moment.
  17361. */
  17362. static void stopAllThreads (int timeoutInMillisecs);
  17363. private:
  17364. const String threadName_;
  17365. void* volatile threadHandle_;
  17366. ThreadID threadId_;
  17367. CriticalSection startStopLock;
  17368. WaitableEvent startSuspensionEvent_, defaultEvent_;
  17369. int threadPriority_;
  17370. uint32 affinityMask_;
  17371. bool volatile threadShouldExit_;
  17372. #ifndef DOXYGEN
  17373. friend class MessageManager;
  17374. friend void JUCE_API juce_threadEntryPoint (void*);
  17375. #endif
  17376. void launchThread();
  17377. void closeThreadHandle();
  17378. void killThread();
  17379. void threadEntryPoint();
  17380. static void setCurrentThreadName (const String& name);
  17381. static bool setThreadPriority (void* handle, int priority);
  17382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  17383. };
  17384. #endif // __JUCE_THREAD_JUCEHEADER__
  17385. /*** End of inlined file: juce_Thread.h ***/
  17386. /**
  17387. A critical section that allows multiple simultaneous readers.
  17388. Features of this type of lock are:
  17389. - Multiple readers can hold the lock at the same time, but only one writer
  17390. can hold it at once.
  17391. - Writers trying to gain the lock will be blocked until all readers and writers
  17392. have released it
  17393. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  17394. blocked until the writer has obtained and released it
  17395. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  17396. there are no other readers
  17397. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  17398. - Recursive locking is supported.
  17399. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  17400. */
  17401. class JUCE_API ReadWriteLock
  17402. {
  17403. public:
  17404. /**
  17405. Creates a ReadWriteLock object.
  17406. */
  17407. ReadWriteLock() noexcept;
  17408. /** Destructor.
  17409. If the object is deleted whilst locked, any subsequent behaviour
  17410. is unpredictable.
  17411. */
  17412. ~ReadWriteLock() noexcept;
  17413. /** Locks this object for reading.
  17414. Multiple threads can simulaneously lock the object for reading, but if another
  17415. thread has it locked for writing, then this will block until it releases the
  17416. lock.
  17417. @see exitRead, ScopedReadLock
  17418. */
  17419. void enterRead() const noexcept;
  17420. /** Releases the read-lock.
  17421. If the caller thread hasn't got the lock, this can have unpredictable results.
  17422. If the enterRead() method has been called multiple times by the thread, each
  17423. call must be matched by a call to exitRead() before other threads will be allowed
  17424. to take over the lock.
  17425. @see enterRead, ScopedReadLock
  17426. */
  17427. void exitRead() const noexcept;
  17428. /** Locks this object for writing.
  17429. This will block until any other threads that have it locked for reading or
  17430. writing have released their lock.
  17431. @see exitWrite, ScopedWriteLock
  17432. */
  17433. void enterWrite() const noexcept;
  17434. /** Tries to lock this object for writing.
  17435. This is like enterWrite(), but doesn't block - it returns true if it manages
  17436. to obtain the lock.
  17437. @see enterWrite
  17438. */
  17439. bool tryEnterWrite() const noexcept;
  17440. /** Releases the write-lock.
  17441. If the caller thread hasn't got the lock, this can have unpredictable results.
  17442. If the enterWrite() method has been called multiple times by the thread, each
  17443. call must be matched by a call to exit() before other threads will be allowed
  17444. to take over the lock.
  17445. @see enterWrite, ScopedWriteLock
  17446. */
  17447. void exitWrite() const noexcept;
  17448. private:
  17449. SpinLock accessLock;
  17450. WaitableEvent waitEvent;
  17451. mutable int numWaitingWriters, numWriters;
  17452. mutable Thread::ThreadID writerThreadId;
  17453. mutable Array <Thread::ThreadID> readerThreads;
  17454. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  17455. };
  17456. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  17457. /*** End of inlined file: juce_ReadWriteLock.h ***/
  17458. #endif
  17459. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  17460. #endif
  17461. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17462. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  17463. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17464. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17465. /**
  17466. Automatically locks and unlocks a ReadWriteLock object.
  17467. Use one of these as a local variable to control access to a ReadWriteLock.
  17468. e.g. @code
  17469. ReadWriteLock myLock;
  17470. for (;;)
  17471. {
  17472. const ScopedReadLock myScopedLock (myLock);
  17473. // myLock is now locked
  17474. ...do some stuff...
  17475. // myLock gets unlocked here.
  17476. }
  17477. @endcode
  17478. @see ReadWriteLock, ScopedWriteLock
  17479. */
  17480. class JUCE_API ScopedReadLock
  17481. {
  17482. public:
  17483. /** Creates a ScopedReadLock.
  17484. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  17485. when the ScopedReadLock object is deleted, the ReadWriteLock will
  17486. be unlocked.
  17487. Make sure this object is created and deleted by the same thread,
  17488. otherwise there are no guarantees what will happen! Best just to use it
  17489. as a local stack object, rather than creating one with the new() operator.
  17490. */
  17491. inline explicit ScopedReadLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterRead(); }
  17492. /** Destructor.
  17493. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  17494. Make sure this object is created and deleted by the same thread,
  17495. otherwise there are no guarantees what will happen!
  17496. */
  17497. inline ~ScopedReadLock() noexcept { lock_.exitRead(); }
  17498. private:
  17499. const ReadWriteLock& lock_;
  17500. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  17501. };
  17502. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17503. /*** End of inlined file: juce_ScopedReadLock.h ***/
  17504. #endif
  17505. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17506. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  17507. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17508. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17509. /**
  17510. Automatically locks and unlocks a ReadWriteLock object.
  17511. Use one of these as a local variable to control access to a ReadWriteLock.
  17512. e.g. @code
  17513. ReadWriteLock myLock;
  17514. for (;;)
  17515. {
  17516. const ScopedWriteLock myScopedLock (myLock);
  17517. // myLock is now locked
  17518. ...do some stuff...
  17519. // myLock gets unlocked here.
  17520. }
  17521. @endcode
  17522. @see ReadWriteLock, ScopedReadLock
  17523. */
  17524. class JUCE_API ScopedWriteLock
  17525. {
  17526. public:
  17527. /** Creates a ScopedWriteLock.
  17528. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  17529. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  17530. be unlocked.
  17531. Make sure this object is created and deleted by the same thread,
  17532. otherwise there are no guarantees what will happen! Best just to use it
  17533. as a local stack object, rather than creating one with the new() operator.
  17534. */
  17535. inline explicit ScopedWriteLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterWrite(); }
  17536. /** Destructor.
  17537. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  17538. Make sure this object is created and deleted by the same thread,
  17539. otherwise there are no guarantees what will happen!
  17540. */
  17541. inline ~ScopedWriteLock() noexcept { lock_.exitWrite(); }
  17542. private:
  17543. const ReadWriteLock& lock_;
  17544. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17545. };
  17546. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17547. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17548. #endif
  17549. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17550. #endif
  17551. #ifndef __JUCE_THREAD_JUCEHEADER__
  17552. #endif
  17553. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17554. /*** Start of inlined file: juce_ThreadPool.h ***/
  17555. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17556. #define __JUCE_THREADPOOL_JUCEHEADER__
  17557. class ThreadPool;
  17558. class ThreadPoolThread;
  17559. /**
  17560. A task that is executed by a ThreadPool object.
  17561. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17562. its threads.
  17563. The runJob() method needs to be implemented to do the task, and if the code that
  17564. does the work takes a significant time to run, it must keep checking the shouldExit()
  17565. method to see if something is trying to interrupt the job. If shouldExit() returns
  17566. true, the runJob() method must return immediately.
  17567. @see ThreadPool, Thread
  17568. */
  17569. class JUCE_API ThreadPoolJob
  17570. {
  17571. public:
  17572. /** Creates a thread pool job object.
  17573. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17574. */
  17575. explicit ThreadPoolJob (const String& name);
  17576. /** Destructor. */
  17577. virtual ~ThreadPoolJob();
  17578. /** Returns the name of this job.
  17579. @see setJobName
  17580. */
  17581. const String getJobName() const;
  17582. /** Changes the job's name.
  17583. @see getJobName
  17584. */
  17585. void setJobName (const String& newName);
  17586. /** These are the values that can be returned by the runJob() method.
  17587. */
  17588. enum JobStatus
  17589. {
  17590. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17591. removed from the pool. */
  17592. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17593. should be automatically deleted by the pool. */
  17594. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17595. again when a thread is free. */
  17596. };
  17597. /** Peforms the actual work that this job needs to do.
  17598. Your subclass must implement this method, in which is does its work.
  17599. If the code in this method takes a significant time to run, it must repeatedly check
  17600. the shouldExit() method to see if something is trying to interrupt the job.
  17601. If shouldExit() ever returns true, the runJob() method must return immediately.
  17602. If this method returns jobHasFinished, then the job will be removed from the pool
  17603. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17604. pool and will get a chance to run again as soon as a thread is free.
  17605. @see shouldExit()
  17606. */
  17607. virtual JobStatus runJob() = 0;
  17608. /** Returns true if this job is currently running its runJob() method. */
  17609. bool isRunning() const { return isActive; }
  17610. /** Returns true if something is trying to interrupt this job and make it stop.
  17611. Your runJob() method must call this whenever it gets a chance, and if it ever
  17612. returns true, the runJob() method must return immediately.
  17613. @see signalJobShouldExit()
  17614. */
  17615. bool shouldExit() const { return shouldStop; }
  17616. /** Calling this will cause the shouldExit() method to return true, and the job
  17617. should (if it's been implemented correctly) stop as soon as possible.
  17618. @see shouldExit()
  17619. */
  17620. void signalJobShouldExit();
  17621. private:
  17622. friend class ThreadPool;
  17623. friend class ThreadPoolThread;
  17624. String jobName;
  17625. ThreadPool* pool;
  17626. bool shouldStop, isActive, shouldBeDeleted;
  17627. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17628. };
  17629. /**
  17630. A set of threads that will run a list of jobs.
  17631. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17632. will be called by the next pooled thread that becomes free.
  17633. @see ThreadPoolJob, Thread
  17634. */
  17635. class JUCE_API ThreadPool
  17636. {
  17637. public:
  17638. /** Creates a thread pool.
  17639. Once you've created a pool, you can give it some things to do with the addJob()
  17640. method.
  17641. @param numberOfThreads the maximum number of actual threads to run.
  17642. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17643. until there are some jobs to run. If false, then
  17644. all the threads will be fired-up immediately so that
  17645. they're ready for action
  17646. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17647. inactive for this length of time, they will automatically
  17648. be stopped until more jobs come along and they're needed
  17649. */
  17650. ThreadPool (int numberOfThreads,
  17651. bool startThreadsOnlyWhenNeeded = true,
  17652. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17653. /** Destructor.
  17654. This will attempt to remove all the jobs before deleting, but if you want to
  17655. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17656. the pool.
  17657. */
  17658. ~ThreadPool();
  17659. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17660. for some kind of operation.
  17661. @see ThreadPool::removeAllJobs
  17662. */
  17663. class JUCE_API JobSelector
  17664. {
  17665. public:
  17666. virtual ~JobSelector() {}
  17667. /** Should return true if the specified thread matches your criteria for whatever
  17668. operation that this object is being used for.
  17669. Any implementation of this method must be extremely fast and thread-safe!
  17670. */
  17671. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17672. };
  17673. /** Adds a job to the queue.
  17674. Once a job has been added, then the next time a thread is free, it will run
  17675. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17676. runJob() method, the pool will either remove the job from the pool or add it to
  17677. the back of the queue to be run again.
  17678. */
  17679. void addJob (ThreadPoolJob* job);
  17680. /** Tries to remove a job from the pool.
  17681. If the job isn't yet running, this will simply remove it. If it is running, it
  17682. will wait for it to finish.
  17683. If the timeout period expires before the job finishes running, then the job will be
  17684. left in the pool and this will return false. It returns true if the job is sucessfully
  17685. stopped and removed.
  17686. @param job the job to remove
  17687. @param interruptIfRunning if true, then if the job is currently busy, its
  17688. ThreadPoolJob::signalJobShouldExit() method will be called to try
  17689. to interrupt it. If false, then if the job will be allowed to run
  17690. until it stops normally (or the timeout expires)
  17691. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  17692. before giving up and returning false
  17693. */
  17694. bool removeJob (ThreadPoolJob* job,
  17695. bool interruptIfRunning,
  17696. int timeOutMilliseconds);
  17697. /** Tries to remove all jobs from the pool.
  17698. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  17699. methods called to try to interrupt them
  17700. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  17701. before giving up and returning false
  17702. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  17703. they will simply be removed from the pool. Jobs that are already running when
  17704. this method is called can choose whether they should be deleted by
  17705. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  17706. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  17707. jobs should be removed. If it is zero, all jobs are removed
  17708. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  17709. expires while waiting for one or more jobs to stop
  17710. */
  17711. bool removeAllJobs (bool interruptRunningJobs,
  17712. int timeOutMilliseconds,
  17713. bool deleteInactiveJobs = false,
  17714. JobSelector* selectedJobsToRemove = 0);
  17715. /** Returns the number of jobs currently running or queued.
  17716. */
  17717. int getNumJobs() const;
  17718. /** Returns one of the jobs in the queue.
  17719. Note that this can be a very volatile list as jobs might be continuously getting shifted
  17720. around in the list, and this method may return 0 if the index is currently out-of-range.
  17721. */
  17722. ThreadPoolJob* getJob (int index) const;
  17723. /** Returns true if the given job is currently queued or running.
  17724. @see isJobRunning()
  17725. */
  17726. bool contains (const ThreadPoolJob* job) const;
  17727. /** Returns true if the given job is currently being run by a thread.
  17728. */
  17729. bool isJobRunning (const ThreadPoolJob* job) const;
  17730. /** Waits until a job has finished running and has been removed from the pool.
  17731. This will wait until the job is no longer in the pool - i.e. until its
  17732. runJob() method returns ThreadPoolJob::jobHasFinished.
  17733. If the timeout period expires before the job finishes, this will return false;
  17734. it returns true if the job has finished successfully.
  17735. */
  17736. bool waitForJobToFinish (const ThreadPoolJob* job,
  17737. int timeOutMilliseconds) const;
  17738. /** Returns a list of the names of all the jobs currently running or queued.
  17739. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  17740. */
  17741. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  17742. /** Changes the priority of all the threads.
  17743. This will call Thread::setPriority() for each thread in the pool.
  17744. May return false if for some reason the priority can't be changed.
  17745. */
  17746. bool setThreadPriorities (int newPriority);
  17747. private:
  17748. const int threadStopTimeout;
  17749. int priority;
  17750. class ThreadPoolThread;
  17751. friend class OwnedArray <ThreadPoolThread>;
  17752. OwnedArray <ThreadPoolThread> threads;
  17753. Array <ThreadPoolJob*> jobs;
  17754. CriticalSection lock;
  17755. uint32 lastJobEndTime;
  17756. WaitableEvent jobFinishedSignal;
  17757. friend class ThreadPoolThread;
  17758. bool runNextJob();
  17759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  17760. };
  17761. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  17762. /*** End of inlined file: juce_ThreadPool.h ***/
  17763. #endif
  17764. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17765. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  17766. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17767. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17768. class TimeSliceThread;
  17769. /**
  17770. Used by the TimeSliceThread class.
  17771. To register your class with a TimeSliceThread, derive from this class and
  17772. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  17773. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  17774. deleting your client!
  17775. @see TimeSliceThread
  17776. */
  17777. class JUCE_API TimeSliceClient
  17778. {
  17779. public:
  17780. /** Destructor. */
  17781. virtual ~TimeSliceClient() {}
  17782. /** Called back by a TimeSliceThread.
  17783. When you register this class with it, a TimeSliceThread will repeatedly call
  17784. this method.
  17785. The implementation of this method should use its time-slice to do something that's
  17786. quick - never block for longer than absolutely necessary.
  17787. @returns Your method should return the number of milliseconds which it would like to wait before being called
  17788. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  17789. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  17790. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  17791. thread - the actual time before the next callback may be more or less than specified.
  17792. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  17793. */
  17794. virtual int useTimeSlice() = 0;
  17795. private:
  17796. friend class TimeSliceThread;
  17797. Time nextCallTime;
  17798. };
  17799. /**
  17800. A thread that keeps a list of clients, and calls each one in turn, giving them
  17801. all a chance to run some sort of short task.
  17802. @see TimeSliceClient, Thread
  17803. */
  17804. class JUCE_API TimeSliceThread : public Thread
  17805. {
  17806. public:
  17807. /**
  17808. Creates a TimeSliceThread.
  17809. When first created, the thread is not running. Use the startThread()
  17810. method to start it.
  17811. */
  17812. explicit TimeSliceThread (const String& threadName);
  17813. /** Destructor.
  17814. Deleting a Thread object that is running will only give the thread a
  17815. brief opportunity to stop itself cleanly, so it's recommended that you
  17816. should always call stopThread() with a decent timeout before deleting,
  17817. to avoid the thread being forcibly killed (which is a Bad Thing).
  17818. */
  17819. ~TimeSliceThread();
  17820. /** Adds a client to the list.
  17821. The client's callbacks will start after the number of milliseconds specified
  17822. by millisecondsBeforeStarting (and this may happen before this method has returned).
  17823. */
  17824. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  17825. /** Removes a client from the list.
  17826. This method will make sure that all callbacks to the client have completely
  17827. finished before the method returns.
  17828. */
  17829. void removeTimeSliceClient (TimeSliceClient* client);
  17830. /** Returns the number of registered clients. */
  17831. int getNumClients() const;
  17832. /** Returns one of the registered clients. */
  17833. TimeSliceClient* getClient (int index) const;
  17834. /** @internal */
  17835. void run();
  17836. private:
  17837. CriticalSection callbackLock, listLock;
  17838. Array <TimeSliceClient*> clients;
  17839. TimeSliceClient* clientBeingCalled;
  17840. TimeSliceClient* getNextClient (int index) const;
  17841. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  17842. };
  17843. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17844. /*** End of inlined file: juce_TimeSliceThread.h ***/
  17845. #endif
  17846. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17847. #endif
  17848. #endif
  17849. /*** End of inlined file: juce_core_includes.h ***/
  17850. // if you're compiling a command-line app, you might want to just include the core headers,
  17851. // so you can set this macro before including juce.h
  17852. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  17853. /*** Start of inlined file: juce_app_includes.h ***/
  17854. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17855. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17856. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17857. /*** Start of inlined file: juce_Application.h ***/
  17858. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17859. #define __JUCE_APPLICATION_JUCEHEADER__
  17860. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  17861. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17862. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17863. /*** Start of inlined file: juce_Component.h ***/
  17864. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  17865. #define __JUCE_COMPONENT_JUCEHEADER__
  17866. /*** Start of inlined file: juce_MouseCursor.h ***/
  17867. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  17868. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  17869. class Image;
  17870. class ComponentPeer;
  17871. class Component;
  17872. /**
  17873. Represents a mouse cursor image.
  17874. This object can either be used to represent one of the standard mouse
  17875. cursor shapes, or a custom one generated from an image.
  17876. */
  17877. class JUCE_API MouseCursor
  17878. {
  17879. public:
  17880. /** The set of available standard mouse cursors. */
  17881. enum StandardCursorType
  17882. {
  17883. NoCursor = 0, /**< An invisible cursor. */
  17884. NormalCursor, /**< The stardard arrow cursor. */
  17885. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  17886. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  17887. CrosshairCursor, /**< A pair of crosshairs. */
  17888. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  17889. that you're dragging a copy of something. */
  17890. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  17891. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  17892. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  17893. UpDownResizeCursor, /**< an arrow pointing up and down. */
  17894. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  17895. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  17896. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  17897. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  17898. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  17899. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  17900. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  17901. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  17902. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  17903. };
  17904. /** Creates the standard arrow cursor. */
  17905. MouseCursor();
  17906. /** Creates one of the standard mouse cursor */
  17907. MouseCursor (StandardCursorType type);
  17908. /** Creates a custom cursor from an image.
  17909. @param image the image to use for the cursor - if this is bigger than the
  17910. system can manage, it might get scaled down first, and might
  17911. also have to be turned to black-and-white if it can't do colour
  17912. cursors.
  17913. @param hotSpotX the x position of the cursor's hotspot within the image
  17914. @param hotSpotY the y position of the cursor's hotspot within the image
  17915. */
  17916. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  17917. /** Creates a copy of another cursor object. */
  17918. MouseCursor (const MouseCursor& other);
  17919. /** Copies this cursor from another object. */
  17920. MouseCursor& operator= (const MouseCursor& other);
  17921. /** Destructor. */
  17922. ~MouseCursor();
  17923. /** Checks whether two mouse cursors are the same.
  17924. For custom cursors, two cursors created from the same image won't be
  17925. recognised as the same, only MouseCursor objects that have been
  17926. copied from the same object.
  17927. */
  17928. bool operator== (const MouseCursor& other) const noexcept;
  17929. /** Checks whether two mouse cursors are the same.
  17930. For custom cursors, two cursors created from the same image won't be
  17931. recognised as the same, only MouseCursor objects that have been
  17932. copied from the same object.
  17933. */
  17934. bool operator!= (const MouseCursor& other) const noexcept;
  17935. /** Makes the system show its default 'busy' cursor.
  17936. This will turn the system cursor to an hourglass or spinning beachball
  17937. until the next time the mouse is moved, or hideWaitCursor() is called.
  17938. This is handy if the message loop is about to block for a couple of
  17939. seconds while busy and you want to give the user feedback about this.
  17940. @see MessageManager::setTimeBeforeShowingWaitCursor
  17941. */
  17942. static void showWaitCursor();
  17943. /** If showWaitCursor has been called, this will return the mouse to its
  17944. normal state.
  17945. This will look at what component is under the mouse, and update the
  17946. cursor to be the correct one for that component.
  17947. @see showWaitCursor
  17948. */
  17949. static void hideWaitCursor();
  17950. private:
  17951. class SharedCursorHandle;
  17952. friend class SharedCursorHandle;
  17953. SharedCursorHandle* cursorHandle;
  17954. friend class MouseInputSourceInternal;
  17955. void showInWindow (ComponentPeer* window) const;
  17956. void showInAllWindows() const;
  17957. void* getHandle() const noexcept;
  17958. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  17959. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  17960. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  17961. JUCE_LEAK_DETECTOR (MouseCursor);
  17962. };
  17963. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  17964. /*** End of inlined file: juce_MouseCursor.h ***/
  17965. /*** Start of inlined file: juce_MouseListener.h ***/
  17966. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  17967. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  17968. class MouseEvent;
  17969. /**
  17970. A MouseListener can be registered with a component to receive callbacks
  17971. about mouse events that happen to that component.
  17972. @see Component::addMouseListener, Component::removeMouseListener
  17973. */
  17974. class JUCE_API MouseListener
  17975. {
  17976. public:
  17977. /** Destructor. */
  17978. virtual ~MouseListener() {}
  17979. /** Called when the mouse moves inside a component.
  17980. If the mouse button isn't pressed and the mouse moves over a component,
  17981. this will be called to let the component react to this.
  17982. A component will always get a mouseEnter callback before a mouseMove.
  17983. @param e details about the position and status of the mouse event, including
  17984. the source component in which it occurred
  17985. @see mouseEnter, mouseExit, mouseDrag, contains
  17986. */
  17987. virtual void mouseMove (const MouseEvent& e);
  17988. /** Called when the mouse first enters a component.
  17989. If the mouse button isn't pressed and the mouse moves into a component,
  17990. this will be called to let the component react to this.
  17991. When the mouse button is pressed and held down while being moved in
  17992. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17993. mouseDrag messages are sent to the component that the mouse was originally
  17994. clicked on, until the button is released.
  17995. @param e details about the position and status of the mouse event, including
  17996. the source component in which it occurred
  17997. @see mouseExit, mouseDrag, mouseMove, contains
  17998. */
  17999. virtual void mouseEnter (const MouseEvent& e);
  18000. /** Called when the mouse moves out of a component.
  18001. This will be called when the mouse moves off the edge of this
  18002. component.
  18003. If the mouse button was pressed, and it was then dragged off the
  18004. edge of the component and released, then this callback will happen
  18005. when the button is released, after the mouseUp callback.
  18006. @param e details about the position and status of the mouse event, including
  18007. the source component in which it occurred
  18008. @see mouseEnter, mouseDrag, mouseMove, contains
  18009. */
  18010. virtual void mouseExit (const MouseEvent& e);
  18011. /** Called when a mouse button is pressed.
  18012. The MouseEvent object passed in contains lots of methods for finding out
  18013. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18014. were held down at the time.
  18015. Once a button is held down, the mouseDrag method will be called when the
  18016. mouse moves, until the button is released.
  18017. @param e details about the position and status of the mouse event, including
  18018. the source component in which it occurred
  18019. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18020. */
  18021. virtual void mouseDown (const MouseEvent& e);
  18022. /** Called when the mouse is moved while a button is held down.
  18023. When a mouse button is pressed inside a component, that component
  18024. receives mouseDrag callbacks each time the mouse moves, even if the
  18025. mouse strays outside the component's bounds.
  18026. @param e details about the position and status of the mouse event, including
  18027. the source component in which it occurred
  18028. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  18029. */
  18030. virtual void mouseDrag (const MouseEvent& e);
  18031. /** Called when a mouse button is released.
  18032. A mouseUp callback is sent to the component in which a button was pressed
  18033. even if the mouse is actually over a different component when the
  18034. button is released.
  18035. The MouseEvent object passed in contains lots of methods for finding out
  18036. which buttons were down just before they were released.
  18037. @param e details about the position and status of the mouse event, including
  18038. the source component in which it occurred
  18039. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18040. */
  18041. virtual void mouseUp (const MouseEvent& e);
  18042. /** Called when a mouse button has been double-clicked on a component.
  18043. The MouseEvent object passed in contains lots of methods for finding out
  18044. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18045. were held down at the time.
  18046. @param e details about the position and status of the mouse event, including
  18047. the source component in which it occurred
  18048. @see mouseDown, mouseUp
  18049. */
  18050. virtual void mouseDoubleClick (const MouseEvent& e);
  18051. /** Called when the mouse-wheel is moved.
  18052. This callback is sent to the component that the mouse is over when the
  18053. wheel is moved.
  18054. If not overridden, the component will forward this message to its parent, so
  18055. that parent components can collect mouse-wheel messages that happen to
  18056. child components which aren't interested in them.
  18057. @param e details about the position and status of the mouse event, including
  18058. the source component in which it occurred
  18059. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18060. value means the wheel has been pushed to the right, negative means it
  18061. was pushed to the left
  18062. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18063. value means the wheel has been pushed upwards, negative means it
  18064. was pushed downwards
  18065. */
  18066. virtual void mouseWheelMove (const MouseEvent& e,
  18067. float wheelIncrementX,
  18068. float wheelIncrementY);
  18069. };
  18070. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  18071. /*** End of inlined file: juce_MouseListener.h ***/
  18072. /*** Start of inlined file: juce_MouseEvent.h ***/
  18073. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  18074. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  18075. class Component;
  18076. class MouseInputSource;
  18077. /*** Start of inlined file: juce_ModifierKeys.h ***/
  18078. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  18079. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  18080. /**
  18081. Represents the state of the mouse buttons and modifier keys.
  18082. This is used both by mouse events and by KeyPress objects to describe
  18083. the state of keys such as shift, control, alt, etc.
  18084. @see KeyPress, MouseEvent::mods
  18085. */
  18086. class JUCE_API ModifierKeys
  18087. {
  18088. public:
  18089. /** Creates a ModifierKeys object from a raw set of flags.
  18090. @param flags to represent the keys that are down
  18091. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  18092. rightButtonModifier, commandModifier, popupMenuClickModifier
  18093. */
  18094. ModifierKeys (int flags = 0) noexcept;
  18095. /** Creates a copy of another object. */
  18096. ModifierKeys (const ModifierKeys& other) noexcept;
  18097. /** Copies this object from another one. */
  18098. ModifierKeys& operator= (const ModifierKeys& other) noexcept;
  18099. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  18100. This is a platform-agnostic way of checking for the operating system's
  18101. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  18102. Windows/Linux, it's actually checking for the CTRL key.
  18103. */
  18104. inline bool isCommandDown() const noexcept { return (flags & commandModifier) != 0; }
  18105. /** Checks whether the user is trying to launch a pop-up menu.
  18106. This checks for platform-specific modifiers that might indicate that the user
  18107. is following the operating system's normal method of showing a pop-up menu.
  18108. So on Windows/Linux, this method is really testing for a right-click.
  18109. On the Mac, it tests for either the CTRL key being down, or a right-click.
  18110. */
  18111. inline bool isPopupMenu() const noexcept { return (flags & popupMenuClickModifier) != 0; }
  18112. /** Checks whether the flag is set for the left mouse-button. */
  18113. inline bool isLeftButtonDown() const noexcept { return (flags & leftButtonModifier) != 0; }
  18114. /** Checks whether the flag is set for the right mouse-button.
  18115. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  18116. this is platform-independent (and makes your code more explanatory too).
  18117. */
  18118. inline bool isRightButtonDown() const noexcept { return (flags & rightButtonModifier) != 0; }
  18119. inline bool isMiddleButtonDown() const noexcept { return (flags & middleButtonModifier) != 0; }
  18120. /** Tests for any of the mouse-button flags. */
  18121. inline bool isAnyMouseButtonDown() const noexcept { return (flags & allMouseButtonModifiers) != 0; }
  18122. /** Tests for any of the modifier key flags. */
  18123. inline bool isAnyModifierKeyDown() const noexcept { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  18124. /** Checks whether the shift key's flag is set. */
  18125. inline bool isShiftDown() const noexcept { return (flags & shiftModifier) != 0; }
  18126. /** Checks whether the CTRL key's flag is set.
  18127. Remember that it's better to use the platform-agnostic routines to test for command-key and
  18128. popup-menu modifiers.
  18129. @see isCommandDown, isPopupMenu
  18130. */
  18131. inline bool isCtrlDown() const noexcept { return (flags & ctrlModifier) != 0; }
  18132. /** Checks whether the shift key's flag is set. */
  18133. inline bool isAltDown() const noexcept { return (flags & altModifier) != 0; }
  18134. /** Flags that represent the different keys. */
  18135. enum Flags
  18136. {
  18137. /** Shift key flag. */
  18138. shiftModifier = 1,
  18139. /** CTRL key flag. */
  18140. ctrlModifier = 2,
  18141. /** ALT key flag. */
  18142. altModifier = 4,
  18143. /** Left mouse button flag. */
  18144. leftButtonModifier = 16,
  18145. /** Right mouse button flag. */
  18146. rightButtonModifier = 32,
  18147. /** Middle mouse button flag. */
  18148. middleButtonModifier = 64,
  18149. #if JUCE_MAC
  18150. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18151. commandModifier = 8,
  18152. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18153. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18154. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  18155. #else
  18156. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18157. commandModifier = ctrlModifier,
  18158. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18159. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18160. popupMenuClickModifier = rightButtonModifier,
  18161. #endif
  18162. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  18163. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  18164. /** Represents a combination of all the mouse buttons at once. */
  18165. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  18166. };
  18167. /** Returns a copy of only the mouse-button flags */
  18168. const ModifierKeys withOnlyMouseButtons() const noexcept { return ModifierKeys (flags & allMouseButtonModifiers); }
  18169. /** Returns a copy of only the non-mouse flags */
  18170. const ModifierKeys withoutMouseButtons() const noexcept { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  18171. bool operator== (const ModifierKeys& other) const noexcept { return flags == other.flags; }
  18172. bool operator!= (const ModifierKeys& other) const noexcept { return flags != other.flags; }
  18173. /** Returns the raw flags for direct testing. */
  18174. inline int getRawFlags() const noexcept { return flags; }
  18175. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const noexcept { return ModifierKeys (flags & ~rawFlagsToClear); }
  18176. inline const ModifierKeys withFlags (int rawFlagsToSet) const noexcept { return ModifierKeys (flags | rawFlagsToSet); }
  18177. /** Tests a combination of flags and returns true if any of them are set. */
  18178. inline bool testFlags (const int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  18179. /** Returns the total number of mouse buttons that are down. */
  18180. int getNumMouseButtonsDown() const noexcept;
  18181. /** Creates a ModifierKeys object to represent the last-known state of the
  18182. keyboard and mouse buttons.
  18183. @see getCurrentModifiersRealtime
  18184. */
  18185. static const ModifierKeys getCurrentModifiers() noexcept;
  18186. /** Creates a ModifierKeys object to represent the current state of the
  18187. keyboard and mouse buttons.
  18188. This isn't often needed and isn't recommended, but will actively check all the
  18189. mouse and key states rather than just returning their last-known state like
  18190. getCurrentModifiers() does.
  18191. This is only needed in special circumstances for up-to-date modifier information
  18192. at times when the app's event loop isn't running normally.
  18193. Another reason to avoid this method is that it's not stateless, and calling it may
  18194. update the value returned by getCurrentModifiers(), which could cause subtle changes
  18195. in the behaviour of some components.
  18196. */
  18197. static const ModifierKeys getCurrentModifiersRealtime() noexcept;
  18198. private:
  18199. int flags;
  18200. static ModifierKeys currentModifiers;
  18201. friend class ComponentPeer;
  18202. friend class MouseInputSource;
  18203. friend class MouseInputSourceInternal;
  18204. static void updateCurrentModifiers() noexcept;
  18205. };
  18206. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  18207. /*** End of inlined file: juce_ModifierKeys.h ***/
  18208. /*** Start of inlined file: juce_Point.h ***/
  18209. #ifndef __JUCE_POINT_JUCEHEADER__
  18210. #define __JUCE_POINT_JUCEHEADER__
  18211. /*** Start of inlined file: juce_AffineTransform.h ***/
  18212. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18213. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18214. /**
  18215. Represents a 2D affine-transformation matrix.
  18216. An affine transformation is a transformation such as a rotation, scale, shear,
  18217. resize or translation.
  18218. These are used for various 2D transformation tasks, e.g. with Path objects.
  18219. @see Path, Point, Line
  18220. */
  18221. class JUCE_API AffineTransform
  18222. {
  18223. public:
  18224. /** Creates an identity transform. */
  18225. AffineTransform() noexcept;
  18226. /** Creates a copy of another transform. */
  18227. AffineTransform (const AffineTransform& other) noexcept;
  18228. /** Creates a transform from a set of raw matrix values.
  18229. The resulting matrix is:
  18230. (mat00 mat01 mat02)
  18231. (mat10 mat11 mat12)
  18232. ( 0 0 1 )
  18233. */
  18234. AffineTransform (float mat00, float mat01, float mat02,
  18235. float mat10, float mat11, float mat12) noexcept;
  18236. /** Copies from another AffineTransform object */
  18237. AffineTransform& operator= (const AffineTransform& other) noexcept;
  18238. /** Compares two transforms. */
  18239. bool operator== (const AffineTransform& other) const noexcept;
  18240. /** Compares two transforms. */
  18241. bool operator!= (const AffineTransform& other) const noexcept;
  18242. /** A ready-to-use identity transform, which you can use to append other
  18243. transformations to.
  18244. e.g. @code
  18245. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  18246. .scaled (2.0f);
  18247. @endcode
  18248. */
  18249. static const AffineTransform identity;
  18250. /** Transforms a 2D co-ordinate using this matrix. */
  18251. template <typename ValueType>
  18252. void transformPoint (ValueType& x, ValueType& y) const noexcept
  18253. {
  18254. const ValueType oldX = x;
  18255. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  18256. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  18257. }
  18258. /** Transforms two 2D co-ordinates using this matrix.
  18259. This is just a shortcut for calling transformPoint() on each of these pairs of
  18260. coordinates in turn. (And putting all the calculations into one function hopefully
  18261. also gives the compiler a bit more scope for pipelining it).
  18262. */
  18263. template <typename ValueType>
  18264. void transformPoints (ValueType& x1, ValueType& y1,
  18265. ValueType& x2, ValueType& y2) const noexcept
  18266. {
  18267. const ValueType oldX1 = x1, oldX2 = x2;
  18268. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18269. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18270. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18271. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18272. }
  18273. /** Transforms three 2D co-ordinates using this matrix.
  18274. This is just a shortcut for calling transformPoint() on each of these pairs of
  18275. coordinates in turn. (And putting all the calculations into one function hopefully
  18276. also gives the compiler a bit more scope for pipelining it).
  18277. */
  18278. template <typename ValueType>
  18279. void transformPoints (ValueType& x1, ValueType& y1,
  18280. ValueType& x2, ValueType& y2,
  18281. ValueType& x3, ValueType& y3) const noexcept
  18282. {
  18283. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  18284. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18285. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18286. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18287. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18288. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  18289. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  18290. }
  18291. /** Returns a new transform which is the same as this one followed by a translation. */
  18292. const AffineTransform translated (float deltaX,
  18293. float deltaY) const noexcept;
  18294. /** Returns a new transform which is a translation. */
  18295. static const AffineTransform translation (float deltaX,
  18296. float deltaY) noexcept;
  18297. /** Returns a transform which is the same as this one followed by a rotation.
  18298. The rotation is specified by a number of radians to rotate clockwise, centred around
  18299. the origin (0, 0).
  18300. */
  18301. const AffineTransform rotated (float angleInRadians) const noexcept;
  18302. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  18303. The rotation is specified by a number of radians to rotate clockwise, centred around
  18304. the co-ordinates passed in.
  18305. */
  18306. const AffineTransform rotated (float angleInRadians,
  18307. float pivotX,
  18308. float pivotY) const noexcept;
  18309. /** Returns a new transform which is a rotation about (0, 0). */
  18310. static const AffineTransform rotation (float angleInRadians) noexcept;
  18311. /** Returns a new transform which is a rotation about a given point. */
  18312. static const AffineTransform rotation (float angleInRadians,
  18313. float pivotX,
  18314. float pivotY) noexcept;
  18315. /** Returns a transform which is the same as this one followed by a re-scaling.
  18316. The scaling is centred around the origin (0, 0).
  18317. */
  18318. const AffineTransform scaled (float factorX,
  18319. float factorY) const noexcept;
  18320. /** Returns a transform which is the same as this one followed by a re-scaling.
  18321. The scaling is centred around the origin provided.
  18322. */
  18323. const AffineTransform scaled (float factorX, float factorY,
  18324. float pivotX, float pivotY) const noexcept;
  18325. /** Returns a new transform which is a re-scale about the origin. */
  18326. static const AffineTransform scale (float factorX,
  18327. float factorY) noexcept;
  18328. /** Returns a new transform which is a re-scale centred around the point provided. */
  18329. static const AffineTransform scale (float factorX, float factorY,
  18330. float pivotX, float pivotY) noexcept;
  18331. /** Returns a transform which is the same as this one followed by a shear.
  18332. The shear is centred around the origin (0, 0).
  18333. */
  18334. const AffineTransform sheared (float shearX, float shearY) const noexcept;
  18335. /** Returns a shear transform, centred around the origin (0, 0). */
  18336. static const AffineTransform shear (float shearX, float shearY) noexcept;
  18337. /** Returns a matrix which is the inverse operation of this one.
  18338. Some matrices don't have an inverse - in this case, the method will just return
  18339. an identity transform.
  18340. */
  18341. const AffineTransform inverted() const noexcept;
  18342. /** Returns the transform that will map three known points onto three coordinates
  18343. that are supplied.
  18344. This returns the transform that will transform (0, 0) into (x00, y00),
  18345. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  18346. */
  18347. static const AffineTransform fromTargetPoints (float x00, float y00,
  18348. float x10, float y10,
  18349. float x01, float y01) noexcept;
  18350. /** Returns the transform that will map three specified points onto three target points.
  18351. */
  18352. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  18353. float sourceX2, float sourceY2, float targetX2, float targetY2,
  18354. float sourceX3, float sourceY3, float targetX3, float targetY3) noexcept;
  18355. /** Returns the result of concatenating another transformation after this one. */
  18356. const AffineTransform followedBy (const AffineTransform& other) const noexcept;
  18357. /** Returns true if this transform has no effect on points. */
  18358. bool isIdentity() const noexcept;
  18359. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  18360. bool isSingularity() const noexcept;
  18361. /** Returns true if the transform only translates, and doesn't scale or rotate the
  18362. points. */
  18363. bool isOnlyTranslation() const noexcept;
  18364. /** If this transform is only a translation, this returns the X offset.
  18365. @see isOnlyTranslation
  18366. */
  18367. float getTranslationX() const noexcept { return mat02; }
  18368. /** If this transform is only a translation, this returns the X offset.
  18369. @see isOnlyTranslation
  18370. */
  18371. float getTranslationY() const noexcept { return mat12; }
  18372. /** Returns the approximate scale factor by which lengths will be transformed.
  18373. Obviously a length may be scaled by entirely different amounts depending on its
  18374. direction, so this is only appropriate as a rough guide.
  18375. */
  18376. float getScaleFactor() const noexcept;
  18377. /* The transform matrix is:
  18378. (mat00 mat01 mat02)
  18379. (mat10 mat11 mat12)
  18380. ( 0 0 1 )
  18381. */
  18382. float mat00, mat01, mat02;
  18383. float mat10, mat11, mat12;
  18384. private:
  18385. JUCE_LEAK_DETECTOR (AffineTransform);
  18386. };
  18387. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18388. /*** End of inlined file: juce_AffineTransform.h ***/
  18389. /**
  18390. A pair of (x, y) co-ordinates.
  18391. The ValueType template should be a primitive type such as int, float, double,
  18392. rather than a class.
  18393. @see Line, Path, AffineTransform
  18394. */
  18395. template <typename ValueType>
  18396. class Point
  18397. {
  18398. public:
  18399. /** Creates a point with co-ordinates (0, 0). */
  18400. Point() noexcept : x(), y() {}
  18401. /** Creates a copy of another point. */
  18402. Point (const Point& other) noexcept : x (other.x), y (other.y) {}
  18403. /** Creates a point from an (x, y) position. */
  18404. Point (const ValueType initialX, const ValueType initialY) noexcept : x (initialX), y (initialY) {}
  18405. /** Destructor. */
  18406. ~Point() noexcept {}
  18407. /** Copies this point from another one. */
  18408. Point& operator= (const Point& other) noexcept { x = other.x; y = other.y; return *this; }
  18409. inline bool operator== (const Point& other) const noexcept { return x == other.x && y == other.y; }
  18410. inline bool operator!= (const Point& other) const noexcept { return x != other.x || y != other.y; }
  18411. /** Returns true if the point is (0, 0). */
  18412. bool isOrigin() const noexcept { return x == ValueType() && y == ValueType(); }
  18413. /** Returns the point's x co-ordinate. */
  18414. inline ValueType getX() const noexcept { return x; }
  18415. /** Returns the point's y co-ordinate. */
  18416. inline ValueType getY() const noexcept { return y; }
  18417. /** Sets the point's x co-ordinate. */
  18418. inline void setX (const ValueType newX) noexcept { x = newX; }
  18419. /** Sets the point's y co-ordinate. */
  18420. inline void setY (const ValueType newY) noexcept { y = newY; }
  18421. /** Returns a point which has the same Y position as this one, but a new X. */
  18422. const Point withX (const ValueType newX) const noexcept { return Point (newX, y); }
  18423. /** Returns a point which has the same X position as this one, but a new Y. */
  18424. const Point withY (const ValueType newY) const noexcept { return Point (x, newY); }
  18425. /** Changes the point's x and y co-ordinates. */
  18426. void setXY (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  18427. /** Adds a pair of co-ordinates to this value. */
  18428. void addXY (const ValueType xToAdd, const ValueType yToAdd) noexcept { x += xToAdd; y += yToAdd; }
  18429. /** Returns a point with a given offset from this one. */
  18430. const Point translated (const ValueType xDelta, const ValueType yDelta) const noexcept { return Point (x + xDelta, y + yDelta); }
  18431. /** Adds two points together. */
  18432. const Point operator+ (const Point& other) const noexcept { return Point (x + other.x, y + other.y); }
  18433. /** Adds another point's co-ordinates to this one. */
  18434. Point& operator+= (const Point& other) noexcept { x += other.x; y += other.y; return *this; }
  18435. /** Subtracts one points from another. */
  18436. const Point operator- (const Point& other) const noexcept { return Point (x - other.x, y - other.y); }
  18437. /** Subtracts another point's co-ordinates to this one. */
  18438. Point& operator-= (const Point& other) noexcept { x -= other.x; y -= other.y; return *this; }
  18439. /** Returns a point whose coordinates are multiplied by a given value. */
  18440. const Point operator* (const ValueType multiplier) const noexcept { return Point (x * multiplier, y * multiplier); }
  18441. /** Multiplies the point's co-ordinates by a value. */
  18442. Point& operator*= (const ValueType multiplier) noexcept { x *= multiplier; y *= multiplier; return *this; }
  18443. /** Returns a point whose coordinates are divided by a given value. */
  18444. const Point operator/ (const ValueType divisor) const noexcept { return Point (x / divisor, y / divisor); }
  18445. /** Divides the point's co-ordinates by a value. */
  18446. Point& operator/= (const ValueType divisor) noexcept { x /= divisor; y /= divisor; return *this; }
  18447. /** Returns the inverse of this point. */
  18448. const Point operator-() const noexcept { return Point (-x, -y); }
  18449. /** Returns the straight-line distance between this point and another one. */
  18450. ValueType getDistanceFromOrigin() const noexcept { return juce_hypot (x, y); }
  18451. /** Returns the straight-line distance between this point and another one. */
  18452. ValueType getDistanceFrom (const Point& other) const noexcept { return juce_hypot (x - other.x, y - other.y); }
  18453. /** Returns the angle from this point to another one.
  18454. The return value is the number of radians clockwise from the 3 o'clock direction,
  18455. where this point is the centre and the other point is on the circumference.
  18456. */
  18457. ValueType getAngleToPoint (const Point& other) const noexcept { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  18458. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  18459. @param radius the radius of the circle.
  18460. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18461. */
  18462. const Point getPointOnCircumference (const float radius, const float angle) const noexcept { return Point<float> (x + radius * std::sin (angle),
  18463. y - radius * std::cos (angle)); }
  18464. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  18465. @param radiusX the horizontal radius of the circle.
  18466. @param radiusY the vertical radius of the circle.
  18467. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18468. */
  18469. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const noexcept { return Point<float> (x + radiusX * std::sin (angle),
  18470. y - radiusY * std::cos (angle)); }
  18471. /** Uses a transform to change the point's co-ordinates.
  18472. This will only compile if ValueType = float!
  18473. @see AffineTransform::transformPoint
  18474. */
  18475. void applyTransform (const AffineTransform& transform) noexcept { transform.transformPoint (x, y); }
  18476. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  18477. const Point transformedBy (const AffineTransform& transform) const noexcept { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  18478. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  18479. /** Casts this point to a Point<int> object. */
  18480. const Point<int> toInt() const noexcept { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  18481. /** Casts this point to a Point<float> object. */
  18482. const Point<float> toFloat() const noexcept { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  18483. /** Casts this point to a Point<double> object. */
  18484. const Point<double> toDouble() const noexcept { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  18485. /** Returns the point as a string in the form "x, y". */
  18486. const String toString() const { return String (x) + ", " + String (y); }
  18487. private:
  18488. ValueType x, y;
  18489. };
  18490. #endif // __JUCE_POINT_JUCEHEADER__
  18491. /*** End of inlined file: juce_Point.h ***/
  18492. /**
  18493. Contains position and status information about a mouse event.
  18494. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  18495. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  18496. */
  18497. class JUCE_API MouseEvent
  18498. {
  18499. public:
  18500. /** Creates a MouseEvent.
  18501. Normally an application will never need to use this.
  18502. @param source the source that's invoking the event
  18503. @param position the position of the mouse, relative to the component that is passed-in
  18504. @param modifiers the key modifiers at the time of the event
  18505. @param eventComponent the component that the mouse event applies to
  18506. @param originator the component that originally received the event
  18507. @param eventTime the time the event happened
  18508. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  18509. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18510. the same as the current mouse-x position.
  18511. @param mouseDownTime the time at which the corresponding mouse-down event happened
  18512. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18513. the same as the current mouse-event time.
  18514. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  18515. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  18516. */
  18517. MouseEvent (MouseInputSource& source,
  18518. const Point<int>& position,
  18519. const ModifierKeys& modifiers,
  18520. Component* eventComponent,
  18521. Component* originator,
  18522. const Time& eventTime,
  18523. const Point<int> mouseDownPos,
  18524. const Time& mouseDownTime,
  18525. int numberOfClicks,
  18526. bool mouseWasDragged) noexcept;
  18527. /** Destructor. */
  18528. ~MouseEvent() noexcept;
  18529. /** The x-position of the mouse when the event occurred.
  18530. This value is relative to the top-left of the component to which the
  18531. event applies (as indicated by the MouseEvent::eventComponent field).
  18532. */
  18533. const int x;
  18534. /** The y-position of the mouse when the event occurred.
  18535. This value is relative to the top-left of the component to which the
  18536. event applies (as indicated by the MouseEvent::eventComponent field).
  18537. */
  18538. const int y;
  18539. /** The key modifiers associated with the event.
  18540. This will let you find out which mouse buttons were down, as well as which
  18541. modifier keys were held down.
  18542. When used for mouse-up events, this will indicate the state of the mouse buttons
  18543. just before they were released, so that you can tell which button they let go of.
  18544. */
  18545. const ModifierKeys mods;
  18546. /** The component that this event applies to.
  18547. This is usually the component that the mouse was over at the time, but for mouse-drag
  18548. events the mouse could actually be over a different component and the events are
  18549. still sent to the component that the button was originally pressed on.
  18550. The x and y member variables are relative to this component's position.
  18551. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18552. component, this pointer will be updated, but originalComponent remains unchanged.
  18553. @see originalComponent
  18554. */
  18555. Component* const eventComponent;
  18556. /** The component that the event first occurred on.
  18557. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18558. component, this value remains unchanged to indicate the first component that received it.
  18559. @see eventComponent
  18560. */
  18561. Component* const originalComponent;
  18562. /** The time that this mouse-event occurred.
  18563. */
  18564. const Time eventTime;
  18565. /** The source device that generated this event.
  18566. */
  18567. MouseInputSource& source;
  18568. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18569. The co-ordinate is relative to the component specified in MouseEvent::component.
  18570. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18571. */
  18572. int getMouseDownX() const noexcept;
  18573. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18574. The co-ordinate is relative to the component specified in MouseEvent::component.
  18575. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18576. */
  18577. int getMouseDownY() const noexcept;
  18578. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18579. The co-ordinates are relative to the component specified in MouseEvent::component.
  18580. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18581. */
  18582. const Point<int> getMouseDownPosition() const noexcept;
  18583. /** Returns the straight-line distance between where the mouse is now and where it
  18584. was the last time the button was pressed.
  18585. This is quite handy for things like deciding whether the user has moved far enough
  18586. for it to be considered a drag operation.
  18587. @see getDistanceFromDragStartX
  18588. */
  18589. int getDistanceFromDragStart() const noexcept;
  18590. /** Returns the difference between the mouse's current x postion and where it was
  18591. when the button was last pressed.
  18592. @see getDistanceFromDragStart
  18593. */
  18594. int getDistanceFromDragStartX() const noexcept;
  18595. /** Returns the difference between the mouse's current y postion and where it was
  18596. when the button was last pressed.
  18597. @see getDistanceFromDragStart
  18598. */
  18599. int getDistanceFromDragStartY() const noexcept;
  18600. /** Returns the difference between the mouse's current postion and where it was
  18601. when the button was last pressed.
  18602. @see getDistanceFromDragStart
  18603. */
  18604. const Point<int> getOffsetFromDragStart() const noexcept;
  18605. /** Returns true if the mouse has just been clicked.
  18606. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18607. the user has dragged the mouse more than a few pixels from the place where the
  18608. mouse-down occurred.
  18609. Once they have dragged it far enough for this method to return false, it will continue
  18610. to return false until the mouse-up, even if they move the mouse back to the same
  18611. position where they originally pressed it. This means that it's very handy for
  18612. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18613. callback to ignore any small movements they might make while clicking.
  18614. @returns true if the mouse wasn't dragged by more than a few pixels between
  18615. the last time the button was pressed and released.
  18616. */
  18617. bool mouseWasClicked() const noexcept;
  18618. /** For a click event, the number of times the mouse was clicked in succession.
  18619. So for example a double-click event will return 2, a triple-click 3, etc.
  18620. */
  18621. int getNumberOfClicks() const noexcept { return numberOfClicks; }
  18622. /** Returns the time that the mouse button has been held down for.
  18623. If called from a mouseDrag or mouseUp callback, this will return the
  18624. number of milliseconds since the corresponding mouseDown event occurred.
  18625. If called in other contexts, e.g. a mouseMove, then the returned value
  18626. may be 0 or an undefined value.
  18627. */
  18628. int getLengthOfMousePress() const noexcept;
  18629. /** The position of the mouse when the event occurred.
  18630. This position is relative to the top-left of the component to which the
  18631. event applies (as indicated by the MouseEvent::eventComponent field).
  18632. */
  18633. const Point<int> getPosition() const noexcept;
  18634. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18635. The co-ordinates are relative to the top-left of the main monitor.
  18636. @see getScreenPosition
  18637. */
  18638. int getScreenX() const;
  18639. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18640. The co-ordinates are relative to the top-left of the main monitor.
  18641. @see getScreenPosition
  18642. */
  18643. int getScreenY() const;
  18644. /** Returns the mouse position of this event, in global screen co-ordinates.
  18645. The co-ordinates are relative to the top-left of the main monitor.
  18646. @see getMouseDownScreenPosition
  18647. */
  18648. const Point<int> getScreenPosition() const;
  18649. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18650. The co-ordinates are relative to the top-left of the main monitor.
  18651. @see getMouseDownScreenPosition
  18652. */
  18653. int getMouseDownScreenX() const;
  18654. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18655. The co-ordinates are relative to the top-left of the main monitor.
  18656. @see getMouseDownScreenPosition
  18657. */
  18658. int getMouseDownScreenY() const;
  18659. /** Returns the co-ordinates at which the mouse button was last pressed.
  18660. The co-ordinates are relative to the top-left of the main monitor.
  18661. @see getScreenPosition
  18662. */
  18663. const Point<int> getMouseDownScreenPosition() const;
  18664. /** Creates a version of this event that is relative to a different component.
  18665. The x and y positions of the event that is returned will have been
  18666. adjusted to be relative to the new component.
  18667. */
  18668. const MouseEvent getEventRelativeTo (Component* otherComponent) const noexcept;
  18669. /** Creates a copy of this event with a different position.
  18670. All other members of the event object are the same, but the x and y are
  18671. replaced with these new values.
  18672. */
  18673. const MouseEvent withNewPosition (const Point<int>& newPosition) const noexcept;
  18674. /** Changes the application-wide setting for the double-click time limit.
  18675. This is the maximum length of time between mouse-clicks for it to be
  18676. considered a double-click. It's used by the Component class.
  18677. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18678. */
  18679. static void setDoubleClickTimeout (int timeOutMilliseconds) noexcept;
  18680. /** Returns the application-wide setting for the double-click time limit.
  18681. This is the maximum length of time between mouse-clicks for it to be
  18682. considered a double-click. It's used by the Component class.
  18683. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18684. */
  18685. static int getDoubleClickTimeout() noexcept;
  18686. private:
  18687. const Point<int> mouseDownPos;
  18688. const Time mouseDownTime;
  18689. const int numberOfClicks;
  18690. const bool wasMovedSinceMouseDown;
  18691. static int doubleClickTimeOutMs;
  18692. MouseEvent& operator= (const MouseEvent&);
  18693. };
  18694. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  18695. /*** End of inlined file: juce_MouseEvent.h ***/
  18696. /*** Start of inlined file: juce_ComponentListener.h ***/
  18697. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18698. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18699. class Component;
  18700. /**
  18701. Gets informed about changes to a component's hierarchy or position.
  18702. To monitor a component for changes, register a subclass of ComponentListener
  18703. with the component using Component::addComponentListener().
  18704. Be sure to deregister listeners before you delete them!
  18705. @see Component::addComponentListener, Component::removeComponentListener
  18706. */
  18707. class JUCE_API ComponentListener
  18708. {
  18709. public:
  18710. /** Destructor. */
  18711. virtual ~ComponentListener() {}
  18712. /** Called when the component's position or size changes.
  18713. @param component the component that was moved or resized
  18714. @param wasMoved true if the component's top-left corner has just moved
  18715. @param wasResized true if the component's width or height has just changed
  18716. @see Component::setBounds, Component::resized, Component::moved
  18717. */
  18718. virtual void componentMovedOrResized (Component& component,
  18719. bool wasMoved,
  18720. bool wasResized);
  18721. /** Called when the component is brought to the top of the z-order.
  18722. @param component the component that was moved
  18723. @see Component::toFront, Component::broughtToFront
  18724. */
  18725. virtual void componentBroughtToFront (Component& component);
  18726. /** Called when the component is made visible or invisible.
  18727. @param component the component that changed
  18728. @see Component::setVisible
  18729. */
  18730. virtual void componentVisibilityChanged (Component& component);
  18731. /** Called when the component has children added or removed.
  18732. @param component the component whose children were changed
  18733. @see Component::childrenChanged, Component::addChildComponent,
  18734. Component::removeChildComponent
  18735. */
  18736. virtual void componentChildrenChanged (Component& component);
  18737. /** Called to indicate that the component's parents have changed.
  18738. When a component is added or removed from its parent, all of its children
  18739. will produce this notification (recursively - so all children of its
  18740. children will also be called as well).
  18741. @param component the component that this listener is registered with
  18742. @see Component::parentHierarchyChanged
  18743. */
  18744. virtual void componentParentHierarchyChanged (Component& component);
  18745. /** Called when the component's name is changed.
  18746. @see Component::setName, Component::getName
  18747. */
  18748. virtual void componentNameChanged (Component& component);
  18749. /** Called when the component is in the process of being deleted.
  18750. This callback is made from inside the destructor, so be very, very cautious
  18751. about what you do in here.
  18752. In particular, bear in mind that it's the Component base class's destructor that calls
  18753. this - so if the object that's being deleted is a subclass of Component, then the
  18754. subclass layers of the object will already have been destructed when it gets to this
  18755. point!
  18756. */
  18757. virtual void componentBeingDeleted (Component& component);
  18758. };
  18759. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18760. /*** End of inlined file: juce_ComponentListener.h ***/
  18761. /*** Start of inlined file: juce_KeyListener.h ***/
  18762. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  18763. #define __JUCE_KEYLISTENER_JUCEHEADER__
  18764. /*** Start of inlined file: juce_KeyPress.h ***/
  18765. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  18766. #define __JUCE_KEYPRESS_JUCEHEADER__
  18767. /**
  18768. Represents a key press, including any modifier keys that are needed.
  18769. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  18770. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  18771. */
  18772. class JUCE_API KeyPress
  18773. {
  18774. public:
  18775. /** Creates an (invalid) KeyPress.
  18776. @see isValid
  18777. */
  18778. KeyPress() noexcept;
  18779. /** Creates a KeyPress for a key and some modifiers.
  18780. e.g.
  18781. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  18782. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  18783. @param keyCode a code that represents the key - this value must be
  18784. one of special constants listed in this class, or an
  18785. 8-bit character code such as a letter (case is ignored),
  18786. digit or a simple key like "," or ".". Note that this
  18787. isn't the same as the textCharacter parameter, so for example
  18788. a keyCode of 'a' and a shift-key modifier should have a
  18789. textCharacter value of 'A'.
  18790. @param modifiers the modifiers to associate with the keystroke
  18791. @param textCharacter the character that would be printed if someone typed
  18792. this keypress into a text editor. This value may be
  18793. null if the keypress is a non-printing character
  18794. @see getKeyCode, isKeyCode, getModifiers
  18795. */
  18796. KeyPress (int keyCode,
  18797. const ModifierKeys& modifiers,
  18798. juce_wchar textCharacter) noexcept;
  18799. /** Creates a keypress with a keyCode but no modifiers or text character.
  18800. */
  18801. KeyPress (int keyCode) noexcept;
  18802. /** Creates a copy of another KeyPress. */
  18803. KeyPress (const KeyPress& other) noexcept;
  18804. /** Copies this KeyPress from another one. */
  18805. KeyPress& operator= (const KeyPress& other) noexcept;
  18806. /** Compares two KeyPress objects. */
  18807. bool operator== (const KeyPress& other) const noexcept;
  18808. /** Compares two KeyPress objects. */
  18809. bool operator!= (const KeyPress& other) const noexcept;
  18810. /** Returns true if this is a valid KeyPress.
  18811. A null keypress can be created by the default constructor, in case it's
  18812. needed.
  18813. */
  18814. bool isValid() const noexcept { return keyCode != 0; }
  18815. /** Returns the key code itself.
  18816. This will either be one of the special constants defined in this class,
  18817. or an 8-bit character code.
  18818. */
  18819. int getKeyCode() const noexcept { return keyCode; }
  18820. /** Returns the key modifiers.
  18821. @see ModifierKeys
  18822. */
  18823. const ModifierKeys getModifiers() const noexcept { return mods; }
  18824. /** Returns the character that is associated with this keypress.
  18825. This is the character that you'd expect to see printed if you press this
  18826. keypress in a text editor or similar component.
  18827. */
  18828. juce_wchar getTextCharacter() const noexcept { return textCharacter; }
  18829. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  18830. the modifiers.
  18831. The values for key codes can either be one of the special constants defined in
  18832. this class, or an 8-bit character code.
  18833. @see getKeyCode
  18834. */
  18835. bool isKeyCode (int keyCodeToCompare) const noexcept { return keyCode == keyCodeToCompare; }
  18836. /** Converts a textual key description to a KeyPress.
  18837. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  18838. This isn't designed to cope with any kind of input, but should be given the
  18839. strings that are created by the getTextDescription() method.
  18840. If the string can't be parsed, the object returned will be invalid.
  18841. @see getTextDescription
  18842. */
  18843. static const KeyPress createFromDescription (const String& textVersion);
  18844. /** Creates a textual description of the key combination.
  18845. e.g. "CTRL + C" or "DELETE".
  18846. To store a keypress in a file, use this method, along with createFromDescription()
  18847. to retrieve it later.
  18848. */
  18849. const String getTextDescription() const;
  18850. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  18851. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  18852. modifier key descriptions that are returned by getTextDescription()
  18853. */
  18854. const String getTextDescriptionWithIcons() const;
  18855. /** Checks whether the user is currently holding down the keys that make up this
  18856. KeyPress.
  18857. Note that this will return false if any extra modifier keys are
  18858. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  18859. then it will be false.
  18860. */
  18861. bool isCurrentlyDown() const;
  18862. /** Checks whether a particular key is held down, irrespective of modifiers.
  18863. The values for key codes can either be one of the special constants defined in
  18864. this class, or an 8-bit character code.
  18865. */
  18866. static bool isKeyCurrentlyDown (int keyCode);
  18867. // Key codes
  18868. //
  18869. // Note that the actual values of these are platform-specific and may change
  18870. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  18871. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  18872. //
  18873. static const int spaceKey; /**< key-code for the space bar */
  18874. static const int escapeKey; /**< key-code for the escape key */
  18875. static const int returnKey; /**< key-code for the return key*/
  18876. static const int tabKey; /**< key-code for the tab key*/
  18877. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  18878. static const int backspaceKey; /**< key-code for the backspace key */
  18879. static const int insertKey; /**< key-code for the insert key */
  18880. static const int upKey; /**< key-code for the cursor-up key */
  18881. static const int downKey; /**< key-code for the cursor-down key */
  18882. static const int leftKey; /**< key-code for the cursor-left key */
  18883. static const int rightKey; /**< key-code for the cursor-right key */
  18884. static const int pageUpKey; /**< key-code for the page-up key */
  18885. static const int pageDownKey; /**< key-code for the page-down key */
  18886. static const int homeKey; /**< key-code for the home key */
  18887. static const int endKey; /**< key-code for the end key */
  18888. static const int F1Key; /**< key-code for the F1 key */
  18889. static const int F2Key; /**< key-code for the F2 key */
  18890. static const int F3Key; /**< key-code for the F3 key */
  18891. static const int F4Key; /**< key-code for the F4 key */
  18892. static const int F5Key; /**< key-code for the F5 key */
  18893. static const int F6Key; /**< key-code for the F6 key */
  18894. static const int F7Key; /**< key-code for the F7 key */
  18895. static const int F8Key; /**< key-code for the F8 key */
  18896. static const int F9Key; /**< key-code for the F9 key */
  18897. static const int F10Key; /**< key-code for the F10 key */
  18898. static const int F11Key; /**< key-code for the F11 key */
  18899. static const int F12Key; /**< key-code for the F12 key */
  18900. static const int F13Key; /**< key-code for the F13 key */
  18901. static const int F14Key; /**< key-code for the F14 key */
  18902. static const int F15Key; /**< key-code for the F15 key */
  18903. static const int F16Key; /**< key-code for the F16 key */
  18904. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  18905. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  18906. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  18907. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  18908. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  18909. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  18910. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  18911. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  18912. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  18913. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  18914. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  18915. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  18916. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  18917. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  18918. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  18919. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  18920. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  18921. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  18922. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  18923. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  18924. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  18925. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  18926. private:
  18927. int keyCode;
  18928. ModifierKeys mods;
  18929. juce_wchar textCharacter;
  18930. JUCE_LEAK_DETECTOR (KeyPress);
  18931. };
  18932. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  18933. /*** End of inlined file: juce_KeyPress.h ***/
  18934. class Component;
  18935. /**
  18936. Receives callbacks when keys are pressed.
  18937. You can add a key listener to a component to be informed when that component
  18938. gets key events. See the Component::addListener method for more details.
  18939. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  18940. */
  18941. class JUCE_API KeyListener
  18942. {
  18943. public:
  18944. /** Destructor. */
  18945. virtual ~KeyListener() {}
  18946. /** Called to indicate that a key has been pressed.
  18947. If your implementation returns true, then the key event is considered to have
  18948. been consumed, and will not be passed on to any other components. If it returns
  18949. false, then the key will be passed to other components that might want to use it.
  18950. @param key the keystroke, including modifier keys
  18951. @param originatingComponent the component that received the key event
  18952. @see keyStateChanged, Component::keyPressed
  18953. */
  18954. virtual bool keyPressed (const KeyPress& key,
  18955. Component* originatingComponent) = 0;
  18956. /** Called when any key is pressed or released.
  18957. When this is called, classes that might be interested in
  18958. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  18959. check whether their key has changed.
  18960. If your implementation returns true, then the key event is considered to have
  18961. been consumed, and will not be passed on to any other components. If it returns
  18962. false, then the key will be passed to other components that might want to use it.
  18963. @param originatingComponent the component that received the key event
  18964. @param isKeyDown true if a key is being pressed, false if one is being released
  18965. @see KeyPress, Component::keyStateChanged
  18966. */
  18967. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  18968. };
  18969. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  18970. /*** End of inlined file: juce_KeyListener.h ***/
  18971. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  18972. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18973. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18974. class Component;
  18975. /**
  18976. Controls the order in which focus moves between components.
  18977. The default algorithm used by this class to work out the order of traversal
  18978. is as follows:
  18979. - if two components both have an explicit focus order specified, then the
  18980. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  18981. method).
  18982. - any component with an explicit focus order greater than 0 comes before ones
  18983. that don't have an order specified.
  18984. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  18985. order.
  18986. If you need traversal in a more customised way, you can create a subclass
  18987. of KeyboardFocusTraverser that uses your own algorithm, and use
  18988. Component::createFocusTraverser() to create it.
  18989. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  18990. */
  18991. class JUCE_API KeyboardFocusTraverser
  18992. {
  18993. public:
  18994. KeyboardFocusTraverser();
  18995. /** Destructor. */
  18996. virtual ~KeyboardFocusTraverser();
  18997. /** Returns the component that should be given focus after the specified one
  18998. when moving "forwards".
  18999. The default implementation will return the next component which is to the
  19000. right of or below this one.
  19001. This may return 0 if there's no suitable candidate.
  19002. */
  19003. virtual Component* getNextComponent (Component* current);
  19004. /** Returns the component that should be given focus after the specified one
  19005. when moving "backwards".
  19006. The default implementation will return the next component which is to the
  19007. left of or above this one.
  19008. This may return 0 if there's no suitable candidate.
  19009. */
  19010. virtual Component* getPreviousComponent (Component* current);
  19011. /** Returns the component that should receive focus be default within the given
  19012. parent component.
  19013. The default implementation will just return the foremost child component that
  19014. wants focus.
  19015. This may return 0 if there's no suitable candidate.
  19016. */
  19017. virtual Component* getDefaultComponent (Component* parentComponent);
  19018. };
  19019. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19020. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  19021. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  19022. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19023. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19024. /*** Start of inlined file: juce_Graphics.h ***/
  19025. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  19026. #define __JUCE_GRAPHICS_JUCEHEADER__
  19027. /*** Start of inlined file: juce_Font.h ***/
  19028. #ifndef __JUCE_FONT_JUCEHEADER__
  19029. #define __JUCE_FONT_JUCEHEADER__
  19030. /*** Start of inlined file: juce_Typeface.h ***/
  19031. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  19032. #define __JUCE_TYPEFACE_JUCEHEADER__
  19033. /*** Start of inlined file: juce_Path.h ***/
  19034. #ifndef __JUCE_PATH_JUCEHEADER__
  19035. #define __JUCE_PATH_JUCEHEADER__
  19036. /*** Start of inlined file: juce_Line.h ***/
  19037. #ifndef __JUCE_LINE_JUCEHEADER__
  19038. #define __JUCE_LINE_JUCEHEADER__
  19039. /**
  19040. Represents a line.
  19041. This class contains a bunch of useful methods for various geometric
  19042. tasks.
  19043. The ValueType template parameter should be a primitive type - float or double
  19044. are what it's designed for. Integer types will work in a basic way, but some methods
  19045. that perform mathematical operations may not compile, or they may not produce
  19046. sensible results.
  19047. @see Point, Rectangle, Path, Graphics::drawLine
  19048. */
  19049. template <typename ValueType>
  19050. class Line
  19051. {
  19052. public:
  19053. /** Creates a line, using (0, 0) as its start and end points. */
  19054. Line() noexcept {}
  19055. /** Creates a copy of another line. */
  19056. Line (const Line& other) noexcept
  19057. : start (other.start),
  19058. end (other.end)
  19059. {
  19060. }
  19061. /** Creates a line based on the co-ordinates of its start and end points. */
  19062. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) noexcept
  19063. : start (startX, startY),
  19064. end (endX, endY)
  19065. {
  19066. }
  19067. /** Creates a line from its start and end points. */
  19068. Line (const Point<ValueType>& startPoint,
  19069. const Point<ValueType>& endPoint) noexcept
  19070. : start (startPoint),
  19071. end (endPoint)
  19072. {
  19073. }
  19074. /** Copies a line from another one. */
  19075. Line& operator= (const Line& other) noexcept
  19076. {
  19077. start = other.start;
  19078. end = other.end;
  19079. return *this;
  19080. }
  19081. /** Destructor. */
  19082. ~Line() noexcept {}
  19083. /** Returns the x co-ordinate of the line's start point. */
  19084. inline ValueType getStartX() const noexcept { return start.getX(); }
  19085. /** Returns the y co-ordinate of the line's start point. */
  19086. inline ValueType getStartY() const noexcept { return start.getY(); }
  19087. /** Returns the x co-ordinate of the line's end point. */
  19088. inline ValueType getEndX() const noexcept { return end.getX(); }
  19089. /** Returns the y co-ordinate of the line's end point. */
  19090. inline ValueType getEndY() const noexcept { return end.getY(); }
  19091. /** Returns the line's start point. */
  19092. inline const Point<ValueType>& getStart() const noexcept { return start; }
  19093. /** Returns the line's end point. */
  19094. inline const Point<ValueType>& getEnd() const noexcept { return end; }
  19095. /** Changes this line's start point */
  19096. void setStart (ValueType newStartX, ValueType newStartY) noexcept { start.setXY (newStartX, newStartY); }
  19097. /** Changes this line's end point */
  19098. void setEnd (ValueType newEndX, ValueType newEndY) noexcept { end.setXY (newEndX, newEndY); }
  19099. /** Changes this line's start point */
  19100. void setStart (const Point<ValueType>& newStart) noexcept { start = newStart; }
  19101. /** Changes this line's end point */
  19102. void setEnd (const Point<ValueType>& newEnd) noexcept { end = newEnd; }
  19103. /** Returns a line that is the same as this one, but with the start and end reversed, */
  19104. const Line reversed() const noexcept { return Line (end, start); }
  19105. /** Applies an affine transform to the line's start and end points. */
  19106. void applyTransform (const AffineTransform& transform) noexcept
  19107. {
  19108. start.applyTransform (transform);
  19109. end.applyTransform (transform);
  19110. }
  19111. /** Returns the length of the line. */
  19112. ValueType getLength() const noexcept { return start.getDistanceFrom (end); }
  19113. /** Returns true if the line's start and end x co-ordinates are the same. */
  19114. bool isVertical() const noexcept { return start.getX() == end.getX(); }
  19115. /** Returns true if the line's start and end y co-ordinates are the same. */
  19116. bool isHorizontal() const noexcept { return start.getY() == end.getY(); }
  19117. /** Returns the line's angle.
  19118. This value is the number of radians clockwise from the 3 o'clock direction,
  19119. where the line's start point is considered to be at the centre.
  19120. */
  19121. ValueType getAngle() const noexcept { return start.getAngleToPoint (end); }
  19122. /** Compares two lines. */
  19123. bool operator== (const Line& other) const noexcept { return start == other.start && end == other.end; }
  19124. /** Compares two lines. */
  19125. bool operator!= (const Line& other) const noexcept { return start != other.start || end != other.end; }
  19126. /** Finds the intersection between two lines.
  19127. @param line the other line
  19128. @param intersection the position of the point where the lines meet (or
  19129. where they would meet if they were infinitely long)
  19130. the intersection (if the lines intersect). If the lines
  19131. are parallel, this will just be set to the position
  19132. of one of the line's endpoints.
  19133. @returns true if the line segments intersect; false if they dont. Even if they
  19134. don't intersect, the intersection co-ordinates returned will still
  19135. be valid
  19136. */
  19137. bool intersects (const Line& line, Point<ValueType>& intersection) const noexcept
  19138. {
  19139. return findIntersection (start, end, line.start, line.end, intersection);
  19140. }
  19141. /** Finds the intersection between two lines.
  19142. @param line the line to intersect with
  19143. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  19144. */
  19145. const Point<ValueType> getIntersection (const Line& line) const noexcept
  19146. {
  19147. Point<ValueType> p;
  19148. findIntersection (start, end, line.start, line.end, p);
  19149. return p;
  19150. }
  19151. /** Returns the location of the point which is a given distance along this line.
  19152. @param distanceFromStart the distance to move along the line from its
  19153. start point. This value can be negative or longer
  19154. than the line itself
  19155. @see getPointAlongLineProportionally
  19156. */
  19157. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const noexcept
  19158. {
  19159. return start + (end - start) * (distanceFromStart / getLength());
  19160. }
  19161. /** Returns a point which is a certain distance along and to the side of this line.
  19162. This effectively moves a given distance along the line, then another distance
  19163. perpendicularly to this, and returns the resulting position.
  19164. @param distanceFromStart the distance to move along the line from its
  19165. start point. This value can be negative or longer
  19166. than the line itself
  19167. @param perpendicularDistance how far to move sideways from the line. If you're
  19168. looking along the line from its start towards its
  19169. end, then a positive value here will move to the
  19170. right, negative value move to the left.
  19171. */
  19172. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  19173. ValueType perpendicularDistance) const noexcept
  19174. {
  19175. const Point<ValueType> delta (end - start);
  19176. const double length = juce_hypot ((double) delta.getX(),
  19177. (double) delta.getY());
  19178. if (length <= 0)
  19179. return start;
  19180. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  19181. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  19182. }
  19183. /** Returns the location of the point which is a given distance along this line
  19184. proportional to the line's length.
  19185. @param proportionOfLength the distance to move along the line from its
  19186. start point, in multiples of the line's length.
  19187. So a value of 0.0 will return the line's start point
  19188. and a value of 1.0 will return its end point. (This value
  19189. can be negative or greater than 1.0).
  19190. @see getPointAlongLine
  19191. */
  19192. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const noexcept
  19193. {
  19194. return start + (end - start) * proportionOfLength;
  19195. }
  19196. /** Returns the smallest distance between this line segment and a given point.
  19197. So if the point is close to the line, this will return the perpendicular
  19198. distance from the line; if the point is a long way beyond one of the line's
  19199. end-point's, it'll return the straight-line distance to the nearest end-point.
  19200. pointOnLine receives the position of the point that is found.
  19201. @returns the point's distance from the line
  19202. @see getPositionAlongLineOfNearestPoint
  19203. */
  19204. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  19205. Point<ValueType>& pointOnLine) const noexcept
  19206. {
  19207. const Point<ValueType> delta (end - start);
  19208. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  19209. if (length > 0)
  19210. {
  19211. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  19212. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  19213. if (prop >= 0 && prop <= 1.0)
  19214. {
  19215. pointOnLine = start + delta * (ValueType) prop;
  19216. return targetPoint.getDistanceFrom (pointOnLine);
  19217. }
  19218. }
  19219. const float fromStart = targetPoint.getDistanceFrom (start);
  19220. const float fromEnd = targetPoint.getDistanceFrom (end);
  19221. if (fromStart < fromEnd)
  19222. {
  19223. pointOnLine = start;
  19224. return fromStart;
  19225. }
  19226. else
  19227. {
  19228. pointOnLine = end;
  19229. return fromEnd;
  19230. }
  19231. }
  19232. /** Finds the point on this line which is nearest to a given point, and
  19233. returns its position as a proportional position along the line.
  19234. @returns a value 0 to 1.0 which is the distance along this line from the
  19235. line's start to the point which is nearest to the point passed-in. To
  19236. turn this number into a position, use getPointAlongLineProportionally().
  19237. @see getDistanceFromPoint, getPointAlongLineProportionally
  19238. */
  19239. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const noexcept
  19240. {
  19241. const Point<ValueType> delta (end - start);
  19242. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  19243. return length <= 0 ? 0
  19244. : jlimit ((ValueType) 0, (ValueType) 1,
  19245. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  19246. + (point.getY() - start.getY()) * delta.getY()) / length));
  19247. }
  19248. /** Finds the point on this line which is nearest to a given point.
  19249. @see getDistanceFromPoint, findNearestProportionalPositionTo
  19250. */
  19251. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const noexcept
  19252. {
  19253. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  19254. }
  19255. /** Returns true if the given point lies above this line.
  19256. The return value is true if the point's y coordinate is less than the y
  19257. coordinate of this line at the given x (assuming the line extends infinitely
  19258. in both directions).
  19259. */
  19260. bool isPointAbove (const Point<ValueType>& point) const noexcept
  19261. {
  19262. return start.getX() != end.getX()
  19263. && point.getY() < ((end.getY() - start.getY())
  19264. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  19265. }
  19266. /** Returns a shortened copy of this line.
  19267. This will chop off part of the start of this line by a certain amount, (leaving the
  19268. end-point the same), and return the new line.
  19269. */
  19270. const Line withShortenedStart (ValueType distanceToShortenBy) const noexcept
  19271. {
  19272. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  19273. }
  19274. /** Returns a shortened copy of this line.
  19275. This will chop off part of the end of this line by a certain amount, (leaving the
  19276. start-point the same), and return the new line.
  19277. */
  19278. const Line withShortenedEnd (ValueType distanceToShortenBy) const noexcept
  19279. {
  19280. const ValueType length = getLength();
  19281. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  19282. }
  19283. private:
  19284. Point<ValueType> start, end;
  19285. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  19286. const Point<ValueType>& p3, const Point<ValueType>& p4,
  19287. Point<ValueType>& intersection) noexcept
  19288. {
  19289. if (p2 == p3)
  19290. {
  19291. intersection = p2;
  19292. return true;
  19293. }
  19294. const Point<ValueType> d1 (p2 - p1);
  19295. const Point<ValueType> d2 (p4 - p3);
  19296. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  19297. if (divisor == 0)
  19298. {
  19299. if (! (d1.isOrigin() || d2.isOrigin()))
  19300. {
  19301. if (d1.getY() == 0 && d2.getY() != 0)
  19302. {
  19303. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  19304. intersection = p1.withX (p3.getX() + along * d2.getX());
  19305. return along >= 0 && along <= (ValueType) 1;
  19306. }
  19307. else if (d2.getY() == 0 && d1.getY() != 0)
  19308. {
  19309. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  19310. intersection = p3.withX (p1.getX() + along * d1.getX());
  19311. return along >= 0 && along <= (ValueType) 1;
  19312. }
  19313. else if (d1.getX() == 0 && d2.getX() != 0)
  19314. {
  19315. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  19316. intersection = p1.withY (p3.getY() + along * d2.getY());
  19317. return along >= 0 && along <= (ValueType) 1;
  19318. }
  19319. else if (d2.getX() == 0 && d1.getX() != 0)
  19320. {
  19321. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  19322. intersection = p3.withY (p1.getY() + along * d1.getY());
  19323. return along >= 0 && along <= (ValueType) 1;
  19324. }
  19325. }
  19326. intersection = (p2 + p3) / (ValueType) 2;
  19327. return false;
  19328. }
  19329. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  19330. intersection = p1 + d1 * along1;
  19331. if (along1 < 0 || along1 > (ValueType) 1)
  19332. return false;
  19333. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  19334. return along2 >= 0 && along2 <= (ValueType) 1;
  19335. }
  19336. };
  19337. #endif // __JUCE_LINE_JUCEHEADER__
  19338. /*** End of inlined file: juce_Line.h ***/
  19339. /*** Start of inlined file: juce_Rectangle.h ***/
  19340. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  19341. #define __JUCE_RECTANGLE_JUCEHEADER__
  19342. class RectangleList;
  19343. /**
  19344. Manages a rectangle and allows geometric operations to be performed on it.
  19345. @see RectangleList, Path, Line, Point
  19346. */
  19347. template <typename ValueType>
  19348. class Rectangle
  19349. {
  19350. public:
  19351. /** Creates a rectangle of zero size.
  19352. The default co-ordinates will be (0, 0, 0, 0).
  19353. */
  19354. Rectangle() noexcept
  19355. : x(), y(), w(), h()
  19356. {
  19357. }
  19358. /** Creates a copy of another rectangle. */
  19359. Rectangle (const Rectangle& other) noexcept
  19360. : x (other.x), y (other.y),
  19361. w (other.w), h (other.h)
  19362. {
  19363. }
  19364. /** Creates a rectangle with a given position and size. */
  19365. Rectangle (const ValueType initialX, const ValueType initialY,
  19366. const ValueType width, const ValueType height) noexcept
  19367. : x (initialX), y (initialY),
  19368. w (width), h (height)
  19369. {
  19370. }
  19371. /** Creates a rectangle with a given size, and a position of (0, 0). */
  19372. Rectangle (const ValueType width, const ValueType height) noexcept
  19373. : x(), y(), w (width), h (height)
  19374. {
  19375. }
  19376. /** Creates a Rectangle from the positions of two opposite corners. */
  19377. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) noexcept
  19378. : x (jmin (corner1.getX(), corner2.getX())),
  19379. y (jmin (corner1.getY(), corner2.getY())),
  19380. w (corner1.getX() - corner2.getX()),
  19381. h (corner1.getY() - corner2.getY())
  19382. {
  19383. if (w < ValueType()) w = -w;
  19384. if (h < ValueType()) h = -h;
  19385. }
  19386. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  19387. The right and bottom values must be larger than the left and top ones, or the resulting
  19388. rectangle will have a negative size.
  19389. */
  19390. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  19391. const ValueType right, const ValueType bottom) noexcept
  19392. {
  19393. return Rectangle (left, top, right - left, bottom - top);
  19394. }
  19395. Rectangle& operator= (const Rectangle& other) noexcept
  19396. {
  19397. x = other.x; y = other.y;
  19398. w = other.w; h = other.h;
  19399. return *this;
  19400. }
  19401. /** Destructor. */
  19402. ~Rectangle() noexcept {}
  19403. /** Returns true if the rectangle's width and height are both zero or less */
  19404. bool isEmpty() const noexcept { return w <= ValueType() || h <= ValueType(); }
  19405. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  19406. inline ValueType getX() const noexcept { return x; }
  19407. /** Returns the y co-ordinate of the rectangle's top edge. */
  19408. inline ValueType getY() const noexcept { return y; }
  19409. /** Returns the width of the rectangle. */
  19410. inline ValueType getWidth() const noexcept { return w; }
  19411. /** Returns the height of the rectangle. */
  19412. inline ValueType getHeight() const noexcept { return h; }
  19413. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  19414. inline ValueType getRight() const noexcept { return x + w; }
  19415. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  19416. inline ValueType getBottom() const noexcept { return y + h; }
  19417. /** Returns the x co-ordinate of the rectangle's centre. */
  19418. ValueType getCentreX() const noexcept { return x + w / (ValueType) 2; }
  19419. /** Returns the y co-ordinate of the rectangle's centre. */
  19420. ValueType getCentreY() const noexcept { return y + h / (ValueType) 2; }
  19421. /** Returns the centre point of the rectangle. */
  19422. const Point<ValueType> getCentre() const noexcept { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  19423. /** Returns the aspect ratio of the rectangle's width / height.
  19424. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  19425. it returns height / width. */
  19426. ValueType getAspectRatio (const bool widthOverHeight = true) const noexcept { return widthOverHeight ? w / h : h / w; }
  19427. /** Returns the rectangle's top-left position as a Point. */
  19428. const Point<ValueType> getPosition() const noexcept { return Point<ValueType> (x, y); }
  19429. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19430. void setPosition (const Point<ValueType>& newPos) noexcept { x = newPos.getX(); y = newPos.getY(); }
  19431. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19432. void setPosition (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  19433. /** Returns a rectangle with the same size as this one, but a new position. */
  19434. const Rectangle withPosition (const ValueType newX, const ValueType newY) const noexcept { return Rectangle (newX, newY, w, h); }
  19435. /** Returns a rectangle with the same size as this one, but a new position. */
  19436. const Rectangle withPosition (const Point<ValueType>& newPos) const noexcept { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  19437. /** Returns the rectangle's top-left position as a Point. */
  19438. const Point<ValueType> getTopLeft() const noexcept { return getPosition(); }
  19439. /** Returns the rectangle's top-right position as a Point. */
  19440. const Point<ValueType> getTopRight() const noexcept { return Point<ValueType> (x + w, y); }
  19441. /** Returns the rectangle's bottom-left position as a Point. */
  19442. const Point<ValueType> getBottomLeft() const noexcept { return Point<ValueType> (x, y + h); }
  19443. /** Returns the rectangle's bottom-right position as a Point. */
  19444. const Point<ValueType> getBottomRight() const noexcept { return Point<ValueType> (x + w, y + h); }
  19445. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  19446. void setSize (const ValueType newWidth, const ValueType newHeight) noexcept { w = newWidth; h = newHeight; }
  19447. /** Returns a rectangle with the same position as this one, but a new size. */
  19448. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const noexcept { return Rectangle (x, y, newWidth, newHeight); }
  19449. /** Changes all the rectangle's co-ordinates. */
  19450. void setBounds (const ValueType newX, const ValueType newY,
  19451. const ValueType newWidth, const ValueType newHeight) noexcept
  19452. {
  19453. x = newX; y = newY; w = newWidth; h = newHeight;
  19454. }
  19455. /** Changes the rectangle's X coordinate */
  19456. void setX (const ValueType newX) noexcept { x = newX; }
  19457. /** Changes the rectangle's Y coordinate */
  19458. void setY (const ValueType newY) noexcept { y = newY; }
  19459. /** Changes the rectangle's width */
  19460. void setWidth (const ValueType newWidth) noexcept { w = newWidth; }
  19461. /** Changes the rectangle's height */
  19462. void setHeight (const ValueType newHeight) noexcept { h = newHeight; }
  19463. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  19464. const Rectangle withX (const ValueType newX) const noexcept { return Rectangle (newX, y, w, h); }
  19465. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  19466. const Rectangle withY (const ValueType newY) const noexcept { return Rectangle (x, newY, w, h); }
  19467. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  19468. const Rectangle withWidth (const ValueType newWidth) const noexcept { return Rectangle (x, y, newWidth, h); }
  19469. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  19470. const Rectangle withHeight (const ValueType newHeight) const noexcept { return Rectangle (x, y, w, newHeight); }
  19471. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  19472. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  19473. @see withLeft
  19474. */
  19475. void setLeft (const ValueType newLeft) noexcept
  19476. {
  19477. w = jmax (ValueType(), x + w - newLeft);
  19478. x = newLeft;
  19479. }
  19480. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  19481. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  19482. @see setLeft
  19483. */
  19484. const Rectangle withLeft (const ValueType newLeft) const noexcept { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  19485. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  19486. If the y is moved to be below the current bottom edge, the height will be set to zero.
  19487. @see withTop
  19488. */
  19489. void setTop (const ValueType newTop) noexcept
  19490. {
  19491. h = jmax (ValueType(), y + h - newTop);
  19492. y = newTop;
  19493. }
  19494. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  19495. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19496. @see setTop
  19497. */
  19498. const Rectangle withTop (const ValueType newTop) const noexcept { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  19499. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  19500. If the new right is below the current X value, the X will be pushed down to match it.
  19501. @see getRight, withRight
  19502. */
  19503. void setRight (const ValueType newRight) noexcept
  19504. {
  19505. x = jmin (x, newRight);
  19506. w = newRight - x;
  19507. }
  19508. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  19509. If the new right edge is below the current left-hand edge, the width will be set to zero.
  19510. @see setRight
  19511. */
  19512. const Rectangle withRight (const ValueType newRight) const noexcept { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  19513. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  19514. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  19515. @see getBottom, withBottom
  19516. */
  19517. void setBottom (const ValueType newBottom) noexcept
  19518. {
  19519. y = jmin (y, newBottom);
  19520. h = newBottom - y;
  19521. }
  19522. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  19523. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19524. @see setBottom
  19525. */
  19526. const Rectangle withBottom (const ValueType newBottom) const noexcept { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  19527. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  19528. void translate (const ValueType deltaX,
  19529. const ValueType deltaY) noexcept
  19530. {
  19531. x += deltaX;
  19532. y += deltaY;
  19533. }
  19534. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19535. const Rectangle translated (const ValueType deltaX,
  19536. const ValueType deltaY) const noexcept
  19537. {
  19538. return Rectangle (x + deltaX, y + deltaY, w, h);
  19539. }
  19540. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19541. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const noexcept
  19542. {
  19543. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19544. }
  19545. /** Moves this rectangle by a given amount. */
  19546. Rectangle& operator+= (const Point<ValueType>& deltaPosition) noexcept
  19547. {
  19548. x += deltaPosition.getX(); y += deltaPosition.getY();
  19549. return *this;
  19550. }
  19551. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19552. const Rectangle operator- (const Point<ValueType>& deltaPosition) const noexcept
  19553. {
  19554. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19555. }
  19556. /** Moves this rectangle by a given amount. */
  19557. Rectangle& operator-= (const Point<ValueType>& deltaPosition) noexcept
  19558. {
  19559. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19560. return *this;
  19561. }
  19562. /** Expands the rectangle by a given amount.
  19563. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19564. @see expanded, reduce, reduced
  19565. */
  19566. void expand (const ValueType deltaX,
  19567. const ValueType deltaY) noexcept
  19568. {
  19569. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19570. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19571. setBounds (x - deltaX, y - deltaY, nw, nh);
  19572. }
  19573. /** Returns a rectangle that is larger than this one by a given amount.
  19574. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19575. @see expand, reduce, reduced
  19576. */
  19577. const Rectangle expanded (const ValueType deltaX,
  19578. const ValueType deltaY) const noexcept
  19579. {
  19580. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19581. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19582. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19583. }
  19584. /** Shrinks the rectangle by a given amount.
  19585. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19586. @see reduced, expand, expanded
  19587. */
  19588. void reduce (const ValueType deltaX,
  19589. const ValueType deltaY) noexcept
  19590. {
  19591. expand (-deltaX, -deltaY);
  19592. }
  19593. /** Returns a rectangle that is smaller than this one by a given amount.
  19594. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19595. @see reduce, expand, expanded
  19596. */
  19597. const Rectangle reduced (const ValueType deltaX,
  19598. const ValueType deltaY) const noexcept
  19599. {
  19600. return expanded (-deltaX, -deltaY);
  19601. }
  19602. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19603. by the specified amount and returning the section that was removed.
  19604. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19605. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19606. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19607. that value.
  19608. */
  19609. const Rectangle removeFromTop (const ValueType amountToRemove) noexcept
  19610. {
  19611. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19612. y += r.h; h -= r.h;
  19613. return r;
  19614. }
  19615. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19616. by the specified amount and returning the section that was removed.
  19617. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19618. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19619. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19620. that value.
  19621. */
  19622. const Rectangle removeFromLeft (const ValueType amountToRemove) noexcept
  19623. {
  19624. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19625. x += r.w; w -= r.w;
  19626. return r;
  19627. }
  19628. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19629. by the specified amount and returning the section that was removed.
  19630. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19631. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19632. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19633. that value.
  19634. */
  19635. const Rectangle removeFromRight (ValueType amountToRemove) noexcept
  19636. {
  19637. amountToRemove = jmin (amountToRemove, w);
  19638. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19639. w -= amountToRemove;
  19640. return r;
  19641. }
  19642. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  19643. by the specified amount and returning the section that was removed.
  19644. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19645. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19646. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19647. that value.
  19648. */
  19649. const Rectangle removeFromBottom (ValueType amountToRemove) noexcept
  19650. {
  19651. amountToRemove = jmin (amountToRemove, h);
  19652. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19653. h -= amountToRemove;
  19654. return r;
  19655. }
  19656. /** Returns true if the two rectangles are identical. */
  19657. bool operator== (const Rectangle& other) const noexcept
  19658. {
  19659. return x == other.x && y == other.y
  19660. && w == other.w && h == other.h;
  19661. }
  19662. /** Returns true if the two rectangles are not identical. */
  19663. bool operator!= (const Rectangle& other) const noexcept
  19664. {
  19665. return x != other.x || y != other.y
  19666. || w != other.w || h != other.h;
  19667. }
  19668. /** Returns true if this co-ordinate is inside the rectangle. */
  19669. bool contains (const ValueType xCoord, const ValueType yCoord) const noexcept
  19670. {
  19671. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  19672. }
  19673. /** Returns true if this co-ordinate is inside the rectangle. */
  19674. bool contains (const Point<ValueType>& point) const noexcept
  19675. {
  19676. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  19677. }
  19678. /** Returns true if this other rectangle is completely inside this one. */
  19679. bool contains (const Rectangle& other) const noexcept
  19680. {
  19681. return x <= other.x && y <= other.y
  19682. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  19683. }
  19684. /** Returns the nearest point to the specified point that lies within this rectangle. */
  19685. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const noexcept
  19686. {
  19687. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  19688. jlimit (y, y + h, point.getY()));
  19689. }
  19690. /** Returns true if any part of another rectangle overlaps this one. */
  19691. bool intersects (const Rectangle& other) const noexcept
  19692. {
  19693. return x + w > other.x
  19694. && y + h > other.y
  19695. && x < other.x + other.w
  19696. && y < other.y + other.h
  19697. && w > ValueType() && h > ValueType();
  19698. }
  19699. /** Returns the region that is the overlap between this and another rectangle.
  19700. If the two rectangles don't overlap, the rectangle returned will be empty.
  19701. */
  19702. const Rectangle getIntersection (const Rectangle& other) const noexcept
  19703. {
  19704. const ValueType nx = jmax (x, other.x);
  19705. const ValueType ny = jmax (y, other.y);
  19706. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  19707. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  19708. if (nw >= ValueType() && nh >= ValueType())
  19709. return Rectangle (nx, ny, nw, nh);
  19710. return Rectangle();
  19711. }
  19712. /** Clips a rectangle so that it lies only within this one.
  19713. This is a non-static version of intersectRectangles().
  19714. Returns false if the two regions didn't overlap.
  19715. */
  19716. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const noexcept
  19717. {
  19718. const int maxX = jmax (otherX, x);
  19719. otherW = jmin (otherX + otherW, x + w) - maxX;
  19720. if (otherW > ValueType())
  19721. {
  19722. const int maxY = jmax (otherY, y);
  19723. otherH = jmin (otherY + otherH, y + h) - maxY;
  19724. if (otherH > ValueType())
  19725. {
  19726. otherX = maxX; otherY = maxY;
  19727. return true;
  19728. }
  19729. }
  19730. return false;
  19731. }
  19732. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  19733. If either this or the other rectangle are empty, they will not be counted as
  19734. part of the resulting region.
  19735. */
  19736. const Rectangle getUnion (const Rectangle& other) const noexcept
  19737. {
  19738. if (other.isEmpty()) return *this;
  19739. if (isEmpty()) return other;
  19740. const ValueType newX = jmin (x, other.x);
  19741. const ValueType newY = jmin (y, other.y);
  19742. return Rectangle (newX, newY,
  19743. jmax (x + w, other.x + other.w) - newX,
  19744. jmax (y + h, other.y + other.h) - newY);
  19745. }
  19746. /** If this rectangle merged with another one results in a simple rectangle, this
  19747. will set this rectangle to the result, and return true.
  19748. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19749. or if they form a complex region.
  19750. */
  19751. bool enlargeIfAdjacent (const Rectangle& other) noexcept
  19752. {
  19753. if (x == other.x && getRight() == other.getRight()
  19754. && (other.getBottom() >= y && other.y <= getBottom()))
  19755. {
  19756. const ValueType newY = jmin (y, other.y);
  19757. h = jmax (getBottom(), other.getBottom()) - newY;
  19758. y = newY;
  19759. return true;
  19760. }
  19761. else if (y == other.y && getBottom() == other.getBottom()
  19762. && (other.getRight() >= x && other.x <= getRight()))
  19763. {
  19764. const ValueType newX = jmin (x, other.x);
  19765. w = jmax (getRight(), other.getRight()) - newX;
  19766. x = newX;
  19767. return true;
  19768. }
  19769. return false;
  19770. }
  19771. /** If after removing another rectangle from this one the result is a simple rectangle,
  19772. this will set this object's bounds to be the result, and return true.
  19773. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19774. or if removing the other one would form a complex region.
  19775. */
  19776. bool reduceIfPartlyContainedIn (const Rectangle& other) noexcept
  19777. {
  19778. int inside = 0;
  19779. const int otherR = other.getRight();
  19780. if (x >= other.x && x < otherR) inside = 1;
  19781. const int otherB = other.getBottom();
  19782. if (y >= other.y && y < otherB) inside |= 2;
  19783. const int r = x + w;
  19784. if (r >= other.x && r < otherR) inside |= 4;
  19785. const int b = y + h;
  19786. if (b >= other.y && b < otherB) inside |= 8;
  19787. switch (inside)
  19788. {
  19789. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  19790. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  19791. case 2 + 4 + 8: w = other.x - x; return true;
  19792. case 1 + 4 + 8: h = other.y - y; return true;
  19793. }
  19794. return false;
  19795. }
  19796. /** Returns the smallest rectangle that can contain the shape created by applying
  19797. a transform to this rectangle.
  19798. This should only be used on floating point rectangles.
  19799. */
  19800. const Rectangle transformed (const AffineTransform& transform) const noexcept
  19801. {
  19802. float x1 = x, y1 = y;
  19803. float x2 = x + w, y2 = y;
  19804. float x3 = x, y3 = y + h;
  19805. float x4 = x2, y4 = y3;
  19806. transform.transformPoints (x1, y1, x2, y2);
  19807. transform.transformPoints (x3, y3, x4, y4);
  19808. const float rx = jmin (x1, x2, x3, x4);
  19809. const float ry = jmin (y1, y2, y3, y4);
  19810. return Rectangle (rx, ry,
  19811. jmax (x1, x2, x3, x4) - rx,
  19812. jmax (y1, y2, y3, y4) - ry);
  19813. }
  19814. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  19815. This is only relevent for floating-point rectangles, of course.
  19816. @see toFloat()
  19817. */
  19818. const Rectangle<int> getSmallestIntegerContainer() const noexcept
  19819. {
  19820. const int x1 = (int) std::floor (static_cast<float> (x));
  19821. const int y1 = (int) std::floor (static_cast<float> (y));
  19822. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  19823. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  19824. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  19825. }
  19826. /** Returns the smallest Rectangle that can contain a set of points. */
  19827. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) noexcept
  19828. {
  19829. if (numPoints == 0)
  19830. return Rectangle();
  19831. ValueType minX (points[0].getX());
  19832. ValueType maxX (minX);
  19833. ValueType minY (points[0].getY());
  19834. ValueType maxY (minY);
  19835. for (int i = 1; i < numPoints; ++i)
  19836. {
  19837. minX = jmin (minX, points[i].getX());
  19838. maxX = jmax (maxX, points[i].getX());
  19839. minY = jmin (minY, points[i].getY());
  19840. maxY = jmax (maxY, points[i].getY());
  19841. }
  19842. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  19843. }
  19844. /** Casts this rectangle to a Rectangle<float>.
  19845. Obviously this is mainly useful for rectangles that use integer types.
  19846. @see getSmallestIntegerContainer
  19847. */
  19848. const Rectangle<float> toFloat() const noexcept
  19849. {
  19850. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  19851. static_cast<float> (w), static_cast<float> (h));
  19852. }
  19853. /** Static utility to intersect two sets of rectangular co-ordinates.
  19854. Returns false if the two regions didn't overlap.
  19855. @see intersectRectangle
  19856. */
  19857. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  19858. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) noexcept
  19859. {
  19860. const ValueType x = jmax (x1, x2);
  19861. w1 = jmin (x1 + w1, x2 + w2) - x;
  19862. if (w1 > ValueType())
  19863. {
  19864. const ValueType y = jmax (y1, y2);
  19865. h1 = jmin (y1 + h1, y2 + h2) - y;
  19866. if (h1 > ValueType())
  19867. {
  19868. x1 = x; y1 = y;
  19869. return true;
  19870. }
  19871. }
  19872. return false;
  19873. }
  19874. /** Creates a string describing this rectangle.
  19875. The string will be of the form "x y width height", e.g. "100 100 400 200".
  19876. Coupled with the fromString() method, this is very handy for things like
  19877. storing rectangles (particularly component positions) in XML attributes.
  19878. @see fromString
  19879. */
  19880. const String toString() const
  19881. {
  19882. String s;
  19883. s.preallocateBytes (32);
  19884. s << x << ' ' << y << ' ' << w << ' ' << h;
  19885. return s;
  19886. }
  19887. /** Parses a string containing a rectangle's details.
  19888. The string should contain 4 integer tokens, in the form "x y width height". They
  19889. can be comma or whitespace separated.
  19890. This method is intended to go with the toString() method, to form an easy way
  19891. of saving/loading rectangles as strings.
  19892. @see toString
  19893. */
  19894. static const Rectangle fromString (const String& stringVersion)
  19895. {
  19896. StringArray toks;
  19897. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  19898. return Rectangle (toks[0].trim().getIntValue(),
  19899. toks[1].trim().getIntValue(),
  19900. toks[2].trim().getIntValue(),
  19901. toks[3].trim().getIntValue());
  19902. }
  19903. private:
  19904. friend class RectangleList;
  19905. ValueType x, y, w, h;
  19906. };
  19907. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  19908. /*** End of inlined file: juce_Rectangle.h ***/
  19909. /*** Start of inlined file: juce_Justification.h ***/
  19910. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  19911. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  19912. /**
  19913. Represents a type of justification to be used when positioning graphical items.
  19914. e.g. it indicates whether something should be placed top-left, top-right,
  19915. centred, etc.
  19916. It is used in various places wherever this kind of information is needed.
  19917. */
  19918. class JUCE_API Justification
  19919. {
  19920. public:
  19921. /** Creates a Justification object using a combination of flags. */
  19922. inline Justification (int flags_) noexcept : flags (flags_) {}
  19923. /** Creates a copy of another Justification object. */
  19924. Justification (const Justification& other) noexcept;
  19925. /** Copies another Justification object. */
  19926. Justification& operator= (const Justification& other) noexcept;
  19927. bool operator== (const Justification& other) const noexcept { return flags == other.flags; }
  19928. bool operator!= (const Justification& other) const noexcept { return flags != other.flags; }
  19929. /** Returns the raw flags that are set for this Justification object. */
  19930. inline int getFlags() const noexcept { return flags; }
  19931. /** Tests a set of flags for this object.
  19932. @returns true if any of the flags passed in are set on this object.
  19933. */
  19934. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  19935. /** Returns just the flags from this object that deal with vertical layout. */
  19936. int getOnlyVerticalFlags() const noexcept;
  19937. /** Returns just the flags from this object that deal with horizontal layout. */
  19938. int getOnlyHorizontalFlags() const noexcept;
  19939. /** Adjusts the position of a rectangle to fit it into a space.
  19940. The (x, y) position of the rectangle will be updated to position it inside the
  19941. given space according to the justification flags.
  19942. */
  19943. template <typename ValueType>
  19944. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  19945. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const noexcept
  19946. {
  19947. x = spaceX;
  19948. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  19949. else if ((flags & right) != 0) x += spaceW - w;
  19950. y = spaceY;
  19951. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  19952. else if ((flags & bottom) != 0) y += spaceH - h;
  19953. }
  19954. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  19955. */
  19956. template <typename ValueType>
  19957. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  19958. const Rectangle<ValueType>& targetSpace) const noexcept
  19959. {
  19960. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  19961. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  19962. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  19963. return areaToAdjust.withPosition (x, y);
  19964. }
  19965. /** Flag values that can be combined and used in the constructor. */
  19966. enum
  19967. {
  19968. /** Indicates that the item should be aligned against the left edge of the available space. */
  19969. left = 1,
  19970. /** Indicates that the item should be aligned against the right edge of the available space. */
  19971. right = 2,
  19972. /** Indicates that the item should be placed in the centre between the left and right
  19973. sides of the available space. */
  19974. horizontallyCentred = 4,
  19975. /** Indicates that the item should be aligned against the top edge of the available space. */
  19976. top = 8,
  19977. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  19978. bottom = 16,
  19979. /** Indicates that the item should be placed in the centre between the top and bottom
  19980. sides of the available space. */
  19981. verticallyCentred = 32,
  19982. /** Indicates that lines of text should be spread out to fill the maximum width
  19983. available, so that both margins are aligned vertically.
  19984. */
  19985. horizontallyJustified = 64,
  19986. /** Indicates that the item should be centred vertically and horizontally.
  19987. This is equivalent to (horizontallyCentred | verticallyCentred)
  19988. */
  19989. centred = 36,
  19990. /** Indicates that the item should be centred vertically but placed on the left hand side.
  19991. This is equivalent to (left | verticallyCentred)
  19992. */
  19993. centredLeft = 33,
  19994. /** Indicates that the item should be centred vertically but placed on the right hand side.
  19995. This is equivalent to (right | verticallyCentred)
  19996. */
  19997. centredRight = 34,
  19998. /** Indicates that the item should be centred horizontally and placed at the top.
  19999. This is equivalent to (horizontallyCentred | top)
  20000. */
  20001. centredTop = 12,
  20002. /** Indicates that the item should be centred horizontally and placed at the bottom.
  20003. This is equivalent to (horizontallyCentred | bottom)
  20004. */
  20005. centredBottom = 20,
  20006. /** Indicates that the item should be placed in the top-left corner.
  20007. This is equivalent to (left | top)
  20008. */
  20009. topLeft = 9,
  20010. /** Indicates that the item should be placed in the top-right corner.
  20011. This is equivalent to (right | top)
  20012. */
  20013. topRight = 10,
  20014. /** Indicates that the item should be placed in the bottom-left corner.
  20015. This is equivalent to (left | bottom)
  20016. */
  20017. bottomLeft = 17,
  20018. /** Indicates that the item should be placed in the bottom-left corner.
  20019. This is equivalent to (right | bottom)
  20020. */
  20021. bottomRight = 18
  20022. };
  20023. private:
  20024. int flags;
  20025. };
  20026. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  20027. /*** End of inlined file: juce_Justification.h ***/
  20028. class Image;
  20029. /**
  20030. A path is a sequence of lines and curves that may either form a closed shape
  20031. or be open-ended.
  20032. To use a path, you can create an empty one, then add lines and curves to it
  20033. to create shapes, then it can be rendered by a Graphics context or used
  20034. for geometric operations.
  20035. e.g. @code
  20036. Path myPath;
  20037. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  20038. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  20039. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  20040. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  20041. // add an ellipse as well, which will form a second sub-path within the path..
  20042. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  20043. // double the width of the whole thing..
  20044. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  20045. // and draw it to a graphics context with a 5-pixel thick outline.
  20046. g.strokePath (myPath, PathStrokeType (5.0f));
  20047. @endcode
  20048. A path object can actually contain multiple sub-paths, which may themselves
  20049. be open or closed.
  20050. @see PathFlatteningIterator, PathStrokeType, Graphics
  20051. */
  20052. class JUCE_API Path
  20053. {
  20054. public:
  20055. /** Creates an empty path. */
  20056. Path();
  20057. /** Creates a copy of another path. */
  20058. Path (const Path& other);
  20059. /** Destructor. */
  20060. ~Path();
  20061. /** Copies this path from another one. */
  20062. Path& operator= (const Path& other);
  20063. bool operator== (const Path& other) const noexcept;
  20064. bool operator!= (const Path& other) const noexcept;
  20065. /** Returns true if the path doesn't contain any lines or curves. */
  20066. bool isEmpty() const noexcept;
  20067. /** Returns the smallest rectangle that contains all points within the path.
  20068. */
  20069. const Rectangle<float> getBounds() const noexcept;
  20070. /** Returns the smallest rectangle that contains all points within the path
  20071. after it's been transformed with the given tranasform matrix.
  20072. */
  20073. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const noexcept;
  20074. /** Checks whether a point lies within the path.
  20075. This is only relevent for closed paths (see closeSubPath()), and
  20076. may produce false results if used on a path which has open sub-paths.
  20077. The path's winding rule is taken into account by this method.
  20078. The tolerance parameter is the maximum error allowed when flattening the path,
  20079. so this method could return a false positive when your point is up to this distance
  20080. outside the path's boundary.
  20081. @see closeSubPath, setUsingNonZeroWinding
  20082. */
  20083. bool contains (float x, float y,
  20084. float tolerance = 1.0f) const;
  20085. /** Checks whether a point lies within the path.
  20086. This is only relevent for closed paths (see closeSubPath()), and
  20087. may produce false results if used on a path which has open sub-paths.
  20088. The path's winding rule is taken into account by this method.
  20089. The tolerance parameter is the maximum error allowed when flattening the path,
  20090. so this method could return a false positive when your point is up to this distance
  20091. outside the path's boundary.
  20092. @see closeSubPath, setUsingNonZeroWinding
  20093. */
  20094. bool contains (const Point<float>& point,
  20095. float tolerance = 1.0f) const;
  20096. /** Checks whether a line crosses the path.
  20097. This will return positive if the line crosses any of the paths constituent
  20098. lines or curves. It doesn't take into account whether the line is inside
  20099. or outside the path, or whether the path is open or closed.
  20100. The tolerance parameter is the maximum error allowed when flattening the path,
  20101. so this method could return a false positive when your point is up to this distance
  20102. outside the path's boundary.
  20103. */
  20104. bool intersectsLine (const Line<float>& line,
  20105. float tolerance = 1.0f);
  20106. /** Cuts off parts of a line to keep the parts that are either inside or
  20107. outside this path.
  20108. Note that this isn't smart enough to cope with situations where the
  20109. line would need to be cut into multiple pieces to correctly clip against
  20110. a re-entrant shape.
  20111. @param line the line to clip
  20112. @param keepSectionOutsidePath if true, it's the section outside the path
  20113. that will be kept; if false its the section inside
  20114. the path
  20115. */
  20116. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  20117. /** Returns the length of the path.
  20118. @see getPointAlongPath
  20119. */
  20120. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  20121. /** Returns a point that is the specified distance along the path.
  20122. If the distance is greater than the total length of the path, this will return the
  20123. end point.
  20124. @see getLength
  20125. */
  20126. const Point<float> getPointAlongPath (float distanceFromStart,
  20127. const AffineTransform& transform = AffineTransform::identity) const;
  20128. /** Finds the point along the path which is nearest to a given position.
  20129. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  20130. of the path.
  20131. */
  20132. float getNearestPoint (const Point<float>& targetPoint,
  20133. Point<float>& pointOnPath,
  20134. const AffineTransform& transform = AffineTransform::identity) const;
  20135. /** Removes all lines and curves, resetting the path completely. */
  20136. void clear() noexcept;
  20137. /** Begins a new subpath with a given starting position.
  20138. This will move the path's current position to the co-ordinates passed in and
  20139. make it ready to draw lines or curves starting from this position.
  20140. After adding whatever lines and curves are needed, you can either
  20141. close the current sub-path using closeSubPath() or call startNewSubPath()
  20142. to move to a new sub-path, leaving the old one open-ended.
  20143. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20144. */
  20145. void startNewSubPath (float startX, float startY);
  20146. /** Begins a new subpath with a given starting position.
  20147. This will move the path's current position to the co-ordinates passed in and
  20148. make it ready to draw lines or curves starting from this position.
  20149. After adding whatever lines and curves are needed, you can either
  20150. close the current sub-path using closeSubPath() or call startNewSubPath()
  20151. to move to a new sub-path, leaving the old one open-ended.
  20152. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20153. */
  20154. void startNewSubPath (const Point<float>& start);
  20155. /** Closes a the current sub-path with a line back to its start-point.
  20156. When creating a closed shape such as a triangle, don't use 3 lineTo()
  20157. calls - instead use two lineTo() calls, followed by a closeSubPath()
  20158. to join the final point back to the start.
  20159. This ensures that closes shapes are recognised as such, and this is
  20160. important for tasks like drawing strokes, which needs to know whether to
  20161. draw end-caps or not.
  20162. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  20163. */
  20164. void closeSubPath();
  20165. /** Adds a line from the shape's last position to a new end-point.
  20166. This will connect the end-point of the last line or curve that was added
  20167. to a new point, using a straight line.
  20168. See the class description for an example of how to add lines and curves to a path.
  20169. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20170. */
  20171. void lineTo (float endX, float endY);
  20172. /** Adds a line from the shape's last position to a new end-point.
  20173. This will connect the end-point of the last line or curve that was added
  20174. to a new point, using a straight line.
  20175. See the class description for an example of how to add lines and curves to a path.
  20176. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20177. */
  20178. void lineTo (const Point<float>& end);
  20179. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20180. This will connect the end-point of the last line or curve that was added
  20181. to a new point, using a quadratic spline with one control-point.
  20182. See the class description for an example of how to add lines and curves to a path.
  20183. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20184. */
  20185. void quadraticTo (float controlPointX,
  20186. float controlPointY,
  20187. float endPointX,
  20188. float endPointY);
  20189. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20190. This will connect the end-point of the last line or curve that was added
  20191. to a new point, using a quadratic spline with one control-point.
  20192. See the class description for an example of how to add lines and curves to a path.
  20193. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20194. */
  20195. void quadraticTo (const Point<float>& controlPoint,
  20196. const Point<float>& endPoint);
  20197. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20198. This will connect the end-point of the last line or curve that was added
  20199. to a new point, using a cubic spline with two control-points.
  20200. See the class description for an example of how to add lines and curves to a path.
  20201. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20202. */
  20203. void cubicTo (float controlPoint1X,
  20204. float controlPoint1Y,
  20205. float controlPoint2X,
  20206. float controlPoint2Y,
  20207. float endPointX,
  20208. float endPointY);
  20209. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20210. This will connect the end-point of the last line or curve that was added
  20211. to a new point, using a cubic spline with two control-points.
  20212. See the class description for an example of how to add lines and curves to a path.
  20213. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20214. */
  20215. void cubicTo (const Point<float>& controlPoint1,
  20216. const Point<float>& controlPoint2,
  20217. const Point<float>& endPoint);
  20218. /** Returns the last point that was added to the path by one of the drawing methods.
  20219. */
  20220. const Point<float> getCurrentPosition() const;
  20221. /** Adds a rectangle to the path.
  20222. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20223. @see addRoundedRectangle, addTriangle
  20224. */
  20225. void addRectangle (float x, float y, float width, float height);
  20226. /** Adds a rectangle to the path.
  20227. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20228. @see addRoundedRectangle, addTriangle
  20229. */
  20230. template <typename ValueType>
  20231. void addRectangle (const Rectangle<ValueType>& rectangle)
  20232. {
  20233. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20234. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  20235. }
  20236. /** Adds a rectangle with rounded corners to the path.
  20237. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20238. @see addRectangle, addTriangle
  20239. */
  20240. void addRoundedRectangle (float x, float y, float width, float height,
  20241. float cornerSize);
  20242. /** Adds a rectangle with rounded corners to the path.
  20243. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20244. @see addRectangle, addTriangle
  20245. */
  20246. void addRoundedRectangle (float x, float y, float width, float height,
  20247. float cornerSizeX,
  20248. float cornerSizeY);
  20249. /** Adds a rectangle with rounded corners to the path.
  20250. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20251. @see addRectangle, addTriangle
  20252. */
  20253. template <typename ValueType>
  20254. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  20255. {
  20256. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20257. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  20258. cornerSizeX, cornerSizeY);
  20259. }
  20260. /** Adds a rectangle with rounded corners to the path.
  20261. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20262. @see addRectangle, addTriangle
  20263. */
  20264. template <typename ValueType>
  20265. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  20266. {
  20267. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  20268. }
  20269. /** Adds a triangle to the path.
  20270. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  20271. Note that whether the vertices are specified in clockwise or anticlockwise
  20272. order will affect how the triangle is filled when it overlaps other
  20273. shapes (the winding order setting will affect this of course).
  20274. */
  20275. void addTriangle (float x1, float y1,
  20276. float x2, float y2,
  20277. float x3, float y3);
  20278. /** Adds a quadrilateral to the path.
  20279. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  20280. Note that whether the vertices are specified in clockwise or anticlockwise
  20281. order will affect how the quad is filled when it overlaps other
  20282. shapes (the winding order setting will affect this of course).
  20283. */
  20284. void addQuadrilateral (float x1, float y1,
  20285. float x2, float y2,
  20286. float x3, float y3,
  20287. float x4, float y4);
  20288. /** Adds an ellipse to the path.
  20289. The shape is added as a new sub-path. (Any currently open paths will be left open).
  20290. @see addArc
  20291. */
  20292. void addEllipse (float x, float y, float width, float height);
  20293. /** Adds an elliptical arc to the current path.
  20294. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20295. or anti-clockwise according to whether the end angle is greater than the start. This means
  20296. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20297. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20298. @param y the top edge of the rectangle in which the elliptical outline fits
  20299. @param width the width of the rectangle in which the elliptical outline fits
  20300. @param height the height of the rectangle in which the elliptical outline fits
  20301. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20302. top-centre of the ellipse)
  20303. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20304. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20305. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20306. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20307. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20308. it will be added to the current sub-path, continuing from the current postition
  20309. @see addCentredArc, arcTo, addPieSegment, addEllipse
  20310. */
  20311. void addArc (float x, float y, float width, float height,
  20312. float fromRadians,
  20313. float toRadians,
  20314. bool startAsNewSubPath = false);
  20315. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  20316. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20317. or anti-clockwise according to whether the end angle is greater than the start. This means
  20318. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20319. @param centreX the centre x of the ellipse
  20320. @param centreY the centre y of the ellipse
  20321. @param radiusX the horizontal radius of the ellipse
  20322. @param radiusY the vertical radius of the ellipse
  20323. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  20324. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20325. top-centre of the ellipse)
  20326. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20327. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20328. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20329. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20330. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20331. it will be added to the current sub-path, continuing from the current postition
  20332. @see addArc, arcTo
  20333. */
  20334. void addCentredArc (float centreX, float centreY,
  20335. float radiusX, float radiusY,
  20336. float rotationOfEllipse,
  20337. float fromRadians,
  20338. float toRadians,
  20339. bool startAsNewSubPath = false);
  20340. /** Adds a "pie-chart" shape to the path.
  20341. The shape is added as a new sub-path. (Any currently open paths will be
  20342. left open).
  20343. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20344. or anti-clockwise according to whether the end angle is greater than the start. This means
  20345. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20346. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20347. @param y the top edge of the rectangle in which the elliptical outline fits
  20348. @param width the width of the rectangle in which the elliptical outline fits
  20349. @param height the height of the rectangle in which the elliptical outline fits
  20350. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20351. top-centre of the ellipse)
  20352. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20353. top-centre of the ellipse)
  20354. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  20355. ellipse at its centre, where this value indicates the inner ellipse's size with
  20356. respect to the outer one.
  20357. @see addArc
  20358. */
  20359. void addPieSegment (float x, float y,
  20360. float width, float height,
  20361. float fromRadians,
  20362. float toRadians,
  20363. float innerCircleProportionalSize);
  20364. /** Adds a line with a specified thickness.
  20365. The line is added as a new closed sub-path. (Any currently open paths will be
  20366. left open).
  20367. @see addArrow
  20368. */
  20369. void addLineSegment (const Line<float>& line, float lineThickness);
  20370. /** Adds a line with an arrowhead on the end.
  20371. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  20372. @see PathStrokeType::createStrokeWithArrowheads
  20373. */
  20374. void addArrow (const Line<float>& line,
  20375. float lineThickness,
  20376. float arrowheadWidth,
  20377. float arrowheadLength);
  20378. /** Adds a polygon shape to the path.
  20379. @see addStar
  20380. */
  20381. void addPolygon (const Point<float>& centre,
  20382. int numberOfSides,
  20383. float radius,
  20384. float startAngle = 0.0f);
  20385. /** Adds a star shape to the path.
  20386. @see addPolygon
  20387. */
  20388. void addStar (const Point<float>& centre,
  20389. int numberOfPoints,
  20390. float innerRadius,
  20391. float outerRadius,
  20392. float startAngle = 0.0f);
  20393. /** Adds a speech-bubble shape to the path.
  20394. @param bodyX the left of the main body area of the bubble
  20395. @param bodyY the top of the main body area of the bubble
  20396. @param bodyW the width of the main body area of the bubble
  20397. @param bodyH the height of the main body area of the bubble
  20398. @param cornerSize the amount by which to round off the corners of the main body rectangle
  20399. @param arrowTipX the x position that the tip of the arrow should connect to
  20400. @param arrowTipY the y position that the tip of the arrow should connect to
  20401. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  20402. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  20403. arrow's base should be - this is a proportional distance between 0 and 1.0
  20404. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  20405. */
  20406. void addBubble (float bodyX, float bodyY,
  20407. float bodyW, float bodyH,
  20408. float cornerSize,
  20409. float arrowTipX,
  20410. float arrowTipY,
  20411. int whichSide,
  20412. float arrowPositionAlongEdgeProportional,
  20413. float arrowWidth);
  20414. /** Adds another path to this one.
  20415. The new path is added as a new sub-path. (Any currently open paths in this
  20416. path will be left open).
  20417. @param pathToAppend the path to add
  20418. */
  20419. void addPath (const Path& pathToAppend);
  20420. /** Adds another path to this one, transforming it on the way in.
  20421. The new path is added as a new sub-path, its points being transformed by the given
  20422. matrix before being added.
  20423. @param pathToAppend the path to add
  20424. @param transformToApply an optional transform to apply to the incoming vertices
  20425. */
  20426. void addPath (const Path& pathToAppend,
  20427. const AffineTransform& transformToApply);
  20428. /** Swaps the contents of this path with another one.
  20429. The internal data of the two paths is swapped over, so this is much faster than
  20430. copying it to a temp variable and back.
  20431. */
  20432. void swapWithPath (Path& other) noexcept;
  20433. /** Applies a 2D transform to all the vertices in the path.
  20434. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  20435. */
  20436. void applyTransform (const AffineTransform& transform) noexcept;
  20437. /** Rescales this path to make it fit neatly into a given space.
  20438. This is effectively a quick way of calling
  20439. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  20440. @param x the x position of the rectangle to fit the path inside
  20441. @param y the y position of the rectangle to fit the path inside
  20442. @param width the width of the rectangle to fit the path inside
  20443. @param height the height of the rectangle to fit the path inside
  20444. @param preserveProportions if true, it will fit the path into the space without altering its
  20445. horizontal/vertical scale ratio; if false, it will distort the
  20446. path to fill the specified ratio both horizontally and vertically
  20447. @see applyTransform, getTransformToScaleToFit
  20448. */
  20449. void scaleToFit (float x, float y, float width, float height,
  20450. bool preserveProportions) noexcept;
  20451. /** Returns a transform that can be used to rescale the path to fit into a given space.
  20452. @param x the x position of the rectangle to fit the path inside
  20453. @param y the y position of the rectangle to fit the path inside
  20454. @param width the width of the rectangle to fit the path inside
  20455. @param height the height of the rectangle to fit the path inside
  20456. @param preserveProportions if true, it will fit the path into the space without altering its
  20457. horizontal/vertical scale ratio; if false, it will distort the
  20458. path to fill the specified ratio both horizontally and vertically
  20459. @param justificationType if the proportions are preseved, the resultant path may be smaller
  20460. than the available rectangle, so this describes how it should be
  20461. positioned within the space.
  20462. @returns an appropriate transformation
  20463. @see applyTransform, scaleToFit
  20464. */
  20465. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  20466. bool preserveProportions,
  20467. const Justification& justificationType = Justification::centred) const;
  20468. /** Creates a version of this path where all sharp corners have been replaced by curves.
  20469. Wherever two lines meet at an angle, this will replace the corner with a curve
  20470. of the given radius.
  20471. */
  20472. const Path createPathWithRoundedCorners (float cornerRadius) const;
  20473. /** Changes the winding-rule to be used when filling the path.
  20474. If set to true (which is the default), then the path uses a non-zero-winding rule
  20475. to determine which points are inside the path. If set to false, it uses an
  20476. alternate-winding rule.
  20477. The winding-rule comes into play when areas of the shape overlap other
  20478. areas, and determines whether the overlapping regions are considered to be
  20479. inside or outside.
  20480. Changing this value just sets a flag - it doesn't affect the contents of the
  20481. path.
  20482. @see isUsingNonZeroWinding
  20483. */
  20484. void setUsingNonZeroWinding (bool isNonZeroWinding) noexcept;
  20485. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  20486. The default for a new path is true.
  20487. @see setUsingNonZeroWinding
  20488. */
  20489. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  20490. /** Iterates the lines and curves that a path contains.
  20491. @see Path, PathFlatteningIterator
  20492. */
  20493. class JUCE_API Iterator
  20494. {
  20495. public:
  20496. Iterator (const Path& path);
  20497. ~Iterator();
  20498. /** Moves onto the next element in the path.
  20499. If this returns false, there are no more elements. If it returns true,
  20500. the elementType variable will be set to the type of the current element,
  20501. and some of the x and y variables will be filled in with values.
  20502. */
  20503. bool next();
  20504. enum PathElementType
  20505. {
  20506. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  20507. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  20508. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  20509. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  20510. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  20511. };
  20512. PathElementType elementType;
  20513. float x1, y1, x2, y2, x3, y3;
  20514. private:
  20515. const Path& path;
  20516. size_t index;
  20517. JUCE_DECLARE_NON_COPYABLE (Iterator);
  20518. };
  20519. /** Loads a stored path from a data stream.
  20520. The data in the stream must have been written using writePathToStream().
  20521. Note that this will append the stored path to whatever is currently in
  20522. this path, so you might need to call clear() beforehand.
  20523. @see loadPathFromData, writePathToStream
  20524. */
  20525. void loadPathFromStream (InputStream& source);
  20526. /** Loads a stored path from a block of data.
  20527. This is similar to loadPathFromStream(), but just reads from a block
  20528. of data. Useful if you're including stored shapes in your code as a
  20529. block of static data.
  20530. @see loadPathFromStream, writePathToStream
  20531. */
  20532. void loadPathFromData (const void* data, int numberOfBytes);
  20533. /** Stores the path by writing it out to a stream.
  20534. After writing out a path, you can reload it using loadPathFromStream().
  20535. @see loadPathFromStream, loadPathFromData
  20536. */
  20537. void writePathToStream (OutputStream& destination) const;
  20538. /** Creates a string containing a textual representation of this path.
  20539. @see restoreFromString
  20540. */
  20541. const String toString() const;
  20542. /** Restores this path from a string that was created with the toString() method.
  20543. @see toString()
  20544. */
  20545. void restoreFromString (const String& stringVersion);
  20546. private:
  20547. friend class PathFlatteningIterator;
  20548. friend class Path::Iterator;
  20549. ArrayAllocationBase <float, DummyCriticalSection> data;
  20550. size_t numElements;
  20551. float pathXMin, pathXMax, pathYMin, pathYMax;
  20552. bool useNonZeroWinding;
  20553. static const float lineMarker;
  20554. static const float moveMarker;
  20555. static const float quadMarker;
  20556. static const float cubicMarker;
  20557. static const float closeSubPathMarker;
  20558. JUCE_LEAK_DETECTOR (Path);
  20559. };
  20560. #endif // __JUCE_PATH_JUCEHEADER__
  20561. /*** End of inlined file: juce_Path.h ***/
  20562. class Font;
  20563. class EdgeTable;
  20564. /** A typeface represents a size-independent font.
  20565. This base class is abstract, but calling createSystemTypefaceFor() will return
  20566. a platform-specific subclass that can be used.
  20567. The CustomTypeface subclass allow you to build your own typeface, and to
  20568. load and save it in the Juce typeface format.
  20569. Normally you should never need to deal directly with Typeface objects - the Font
  20570. class does everything you typically need for rendering text.
  20571. @see CustomTypeface, Font
  20572. */
  20573. class JUCE_API Typeface : public ReferenceCountedObject
  20574. {
  20575. public:
  20576. /** A handy typedef for a pointer to a typeface. */
  20577. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  20578. /** Returns the name of the typeface.
  20579. @see Font::getTypefaceName
  20580. */
  20581. const String getName() const noexcept { return name; }
  20582. /** Creates a new system typeface. */
  20583. static const Ptr createSystemTypefaceFor (const Font& font);
  20584. /** Destructor. */
  20585. virtual ~Typeface();
  20586. /** Returns true if this typeface can be used to render the specified font.
  20587. When called, the font will already have been checked to make sure that its name and
  20588. style flags match the typeface.
  20589. */
  20590. virtual bool isSuitableForFont (const Font&) const { return true; }
  20591. /** Returns the ascent of the font, as a proportion of its height.
  20592. The height is considered to always be normalised as 1.0, so this will be a
  20593. value less that 1.0, indicating the proportion of the font that lies above
  20594. its baseline.
  20595. */
  20596. virtual float getAscent() const = 0;
  20597. /** Returns the descent of the font, as a proportion of its height.
  20598. The height is considered to always be normalised as 1.0, so this will be a
  20599. value less that 1.0, indicating the proportion of the font that lies below
  20600. its baseline.
  20601. */
  20602. virtual float getDescent() const = 0;
  20603. /** Measures the width of a line of text.
  20604. The distance returned is based on the font having an normalised height of 1.0.
  20605. You should never need to call this directly! Use Font::getStringWidth() instead!
  20606. */
  20607. virtual float getStringWidth (const String& text) = 0;
  20608. /** Converts a line of text into its glyph numbers and their positions.
  20609. The distances returned are based on the font having an normalised height of 1.0.
  20610. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  20611. */
  20612. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  20613. /** Returns the outline for a glyph.
  20614. The path returned will be normalised to a font height of 1.0.
  20615. */
  20616. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  20617. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  20618. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  20619. /** Returns true if the typeface uses hinting. */
  20620. virtual bool isHinted() const { return false; }
  20621. /** Changes the number of fonts that are cached in memory. */
  20622. static void setTypefaceCacheSize (int numFontsToCache);
  20623. protected:
  20624. String name;
  20625. bool isFallbackFont;
  20626. explicit Typeface (const String& name) noexcept;
  20627. static const Ptr getFallbackTypeface();
  20628. private:
  20629. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  20630. };
  20631. /** A typeface that can be populated with custom glyphs.
  20632. You can create a CustomTypeface if you need one that contains your own glyphs,
  20633. or if you need to load a typeface from a Juce-formatted binary stream.
  20634. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  20635. to copy glyphs into this face.
  20636. @see Typeface, Font
  20637. */
  20638. class JUCE_API CustomTypeface : public Typeface
  20639. {
  20640. public:
  20641. /** Creates a new, empty typeface. */
  20642. CustomTypeface();
  20643. /** Loads a typeface from a previously saved stream.
  20644. The stream must have been created by writeToStream().
  20645. @see writeToStream
  20646. */
  20647. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  20648. /** Destructor. */
  20649. ~CustomTypeface();
  20650. /** Resets this typeface, deleting all its glyphs and settings. */
  20651. void clear();
  20652. /** Sets the vital statistics for the typeface.
  20653. @param name the typeface's name
  20654. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  20655. the value that will be returned by Typeface::getAscent(). The
  20656. descent is assumed to be (1.0 - ascent)
  20657. @param isBold should be true if the typeface is bold
  20658. @param isItalic should be true if the typeface is italic
  20659. @param defaultCharacter the character to be used as a replacement if there's
  20660. no glyph available for the character that's being drawn
  20661. */
  20662. void setCharacteristics (const String& name, float ascent,
  20663. bool isBold, bool isItalic,
  20664. juce_wchar defaultCharacter) noexcept;
  20665. /** Adds a glyph to the typeface.
  20666. The path that is passed in is normalised so that the font height is 1.0, and its
  20667. origin is the anchor point of the character on its baseline.
  20668. The width is the nominal width of the character, and any extra kerning values that
  20669. are specified will be added to this width.
  20670. */
  20671. void addGlyph (juce_wchar character, const Path& path, float width) noexcept;
  20672. /** Specifies an extra kerning amount to be used between a pair of characters.
  20673. The amount will be added to the nominal width of the first character when laying out a string.
  20674. */
  20675. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) noexcept;
  20676. /** Adds a range of glyphs from another typeface.
  20677. This will attempt to pull in the paths and kerning information from another typeface and
  20678. add it to this one.
  20679. */
  20680. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) noexcept;
  20681. /** Saves this typeface as a Juce-formatted font file.
  20682. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  20683. constructor.
  20684. */
  20685. bool writeToStream (OutputStream& outputStream);
  20686. // The following methods implement the basic Typeface behaviour.
  20687. float getAscent() const;
  20688. float getDescent() const;
  20689. float getStringWidth (const String& text);
  20690. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  20691. bool getOutlineForGlyph (int glyphNumber, Path& path);
  20692. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  20693. int getGlyphForCharacter (juce_wchar character);
  20694. protected:
  20695. juce_wchar defaultCharacter;
  20696. float ascent;
  20697. bool isBold, isItalic;
  20698. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  20699. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  20700. particular character and there's no corresponding glyph, they'll call this
  20701. method so that a subclass can try to add that glyph, returning true if it
  20702. manages to do so.
  20703. */
  20704. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  20705. private:
  20706. class GlyphInfo;
  20707. friend class OwnedArray<GlyphInfo>;
  20708. OwnedArray <GlyphInfo> glyphs;
  20709. short lookupTable [128];
  20710. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) noexcept;
  20711. GlyphInfo* findGlyphSubstituting (juce_wchar character) noexcept;
  20712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  20713. };
  20714. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  20715. /*** End of inlined file: juce_Typeface.h ***/
  20716. class LowLevelGraphicsContext;
  20717. /**
  20718. Represents a particular font, including its size, style, etc.
  20719. Apart from the typeface to be used, a Font object also dictates whether
  20720. the font is bold, italic, underlined, how big it is, and its kerning and
  20721. horizontal scale factor.
  20722. @see Typeface
  20723. */
  20724. class JUCE_API Font
  20725. {
  20726. public:
  20727. /** A combination of these values is used by the constructor to specify the
  20728. style of font to use.
  20729. */
  20730. enum FontStyleFlags
  20731. {
  20732. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  20733. bold = 1, /**< boldens the font. @see setStyleFlags */
  20734. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  20735. underlined = 4 /**< underlines the font. @see setStyleFlags */
  20736. };
  20737. /** Creates a sans-serif font in a given size.
  20738. @param fontHeight the height in pixels (can be fractional)
  20739. @param styleFlags the style to use - this can be a combination of the
  20740. Font::bold, Font::italic and Font::underlined, or
  20741. just Font::plain for the normal style.
  20742. @see FontStyleFlags, getDefaultSansSerifFontName
  20743. */
  20744. Font (float fontHeight, int styleFlags = plain);
  20745. /** Creates a font with a given typeface and parameters.
  20746. @param typefaceName the name of the typeface to use
  20747. @param fontHeight the height in pixels (can be fractional)
  20748. @param styleFlags the style to use - this can be a combination of the
  20749. Font::bold, Font::italic and Font::underlined, or
  20750. just Font::plain for the normal style.
  20751. @see FontStyleFlags, getDefaultSansSerifFontName
  20752. */
  20753. Font (const String& typefaceName, float fontHeight, int styleFlags);
  20754. /** Creates a copy of another Font object. */
  20755. Font (const Font& other) noexcept;
  20756. /** Creates a font for a typeface. */
  20757. Font (const Typeface::Ptr& typeface);
  20758. /** Creates a basic sans-serif font at a default height.
  20759. You should use one of the other constructors for creating a font that you're planning
  20760. on drawing with - this constructor is here to help initialise objects before changing
  20761. the font's settings later.
  20762. */
  20763. Font();
  20764. /** Copies this font from another one. */
  20765. Font& operator= (const Font& other) noexcept;
  20766. bool operator== (const Font& other) const noexcept;
  20767. bool operator!= (const Font& other) const noexcept;
  20768. /** Destructor. */
  20769. ~Font() noexcept;
  20770. /** Changes the name of the typeface family.
  20771. e.g. "Arial", "Courier", etc.
  20772. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20773. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20774. but are generic names that are used to represent the various default fonts.
  20775. If you need to know the exact typeface name being used, you can call
  20776. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20777. If a suitable font isn't found on the machine, it'll just use a default instead.
  20778. */
  20779. void setTypefaceName (const String& faceName);
  20780. /** Returns the name of the typeface family that this font uses.
  20781. e.g. "Arial", "Courier", etc.
  20782. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20783. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20784. but are generic names that are used to represent the various default fonts.
  20785. If you need to know the exact typeface name being used, you can call
  20786. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20787. */
  20788. const String& getTypefaceName() const noexcept { return font->typefaceName; }
  20789. /** Returns a typeface name that represents the default sans-serif font.
  20790. This is also the typeface that will be used when a font is created without
  20791. specifying any typeface details.
  20792. Note that this method just returns a generic placeholder string that means "the default
  20793. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  20794. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20795. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  20796. */
  20797. static const String getDefaultSansSerifFontName();
  20798. /** Returns a typeface name that represents the default sans-serif font.
  20799. Note that this method just returns a generic placeholder string that means "the default
  20800. serif font" - it's not the actual name of this font. To get the actual name, use
  20801. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20802. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  20803. */
  20804. static const String getDefaultSerifFontName();
  20805. /** Returns a typeface name that represents the default sans-serif font.
  20806. Note that this method just returns a generic placeholder string that means "the default
  20807. monospaced font" - it's not the actual name of this font. To get the actual name, use
  20808. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20809. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  20810. */
  20811. static const String getDefaultMonospacedFontName();
  20812. /** Returns the typeface names of the default fonts on the current platform. */
  20813. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  20814. /** Returns the total height of this font.
  20815. This is the maximum height, from the top of the ascent to the bottom of the
  20816. descenders.
  20817. @see setHeight, setHeightWithoutChangingWidth, getAscent
  20818. */
  20819. float getHeight() const noexcept { return font->height; }
  20820. /** Changes the font's height.
  20821. @see getHeight, setHeightWithoutChangingWidth
  20822. */
  20823. void setHeight (float newHeight);
  20824. /** Changes the font's height without changing its width.
  20825. This alters the horizontal scale to compensate for the change in height.
  20826. */
  20827. void setHeightWithoutChangingWidth (float newHeight);
  20828. /** Returns the height of the font above its baseline.
  20829. This is the maximum height from the baseline to the top.
  20830. @see getHeight, getDescent
  20831. */
  20832. float getAscent() const;
  20833. /** Returns the amount that the font descends below its baseline.
  20834. This is calculated as (getHeight() - getAscent()).
  20835. @see getAscent, getHeight
  20836. */
  20837. float getDescent() const;
  20838. /** Returns the font's style flags.
  20839. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  20840. enum, to describe whether the font is bold, italic, etc.
  20841. @see FontStyleFlags
  20842. */
  20843. int getStyleFlags() const noexcept { return font->styleFlags; }
  20844. /** Changes the font's style.
  20845. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  20846. enum, to set the font's properties
  20847. @see FontStyleFlags
  20848. */
  20849. void setStyleFlags (int newFlags);
  20850. /** Makes the font bold or non-bold. */
  20851. void setBold (bool shouldBeBold);
  20852. /** Returns a copy of this font with the bold attribute set. */
  20853. const Font boldened() const;
  20854. /** Returns true if the font is bold. */
  20855. bool isBold() const noexcept;
  20856. /** Makes the font italic or non-italic. */
  20857. void setItalic (bool shouldBeItalic);
  20858. /** Returns a copy of this font with the italic attribute set. */
  20859. const Font italicised() const;
  20860. /** Returns true if the font is italic. */
  20861. bool isItalic() const noexcept;
  20862. /** Makes the font underlined or non-underlined. */
  20863. void setUnderline (bool shouldBeUnderlined);
  20864. /** Returns true if the font is underlined. */
  20865. bool isUnderlined() const noexcept;
  20866. /** Changes the font's horizontal scale factor.
  20867. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  20868. narrower, greater than 1.0 will be stretched out.
  20869. */
  20870. void setHorizontalScale (float scaleFactor);
  20871. /** Returns the font's horizontal scale.
  20872. A value of 1.0 is the normal scale, less than this will be narrower, greater
  20873. than 1.0 will be stretched out.
  20874. @see setHorizontalScale
  20875. */
  20876. float getHorizontalScale() const noexcept { return font->horizontalScale; }
  20877. /** Changes the font's kerning.
  20878. @param extraKerning a multiple of the font's height that will be added
  20879. to space between the characters. So a value of zero is
  20880. normal spacing, positive values spread the letters out,
  20881. negative values make them closer together.
  20882. */
  20883. void setExtraKerningFactor (float extraKerning);
  20884. /** Returns the font's kerning.
  20885. This is the extra space added between adjacent characters, as a proportion
  20886. of the font's height.
  20887. A value of zero is normal spacing, positive values will spread the letters
  20888. out more, and negative values make them closer together.
  20889. */
  20890. float getExtraKerningFactor() const noexcept { return font->kerning; }
  20891. /** Changes all the font's characteristics with one call. */
  20892. void setSizeAndStyle (float newHeight,
  20893. int newStyleFlags,
  20894. float newHorizontalScale,
  20895. float newKerningAmount);
  20896. /** Returns the total width of a string as it would be drawn using this font.
  20897. For a more accurate floating-point result, use getStringWidthFloat().
  20898. */
  20899. int getStringWidth (const String& text) const;
  20900. /** Returns the total width of a string as it would be drawn using this font.
  20901. @see getStringWidth
  20902. */
  20903. float getStringWidthFloat (const String& text) const;
  20904. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  20905. An extra x offset is added at the end of the run, to indicate where the right hand
  20906. edge of the last character is.
  20907. */
  20908. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  20909. /** Returns the typeface used by this font.
  20910. Note that the object returned may go out of scope if this font is deleted
  20911. or has its style changed.
  20912. */
  20913. Typeface* getTypeface() const;
  20914. /** Creates an array of Font objects to represent all the fonts on the system.
  20915. If you just need the names of the typefaces, you can also use
  20916. findAllTypefaceNames() instead.
  20917. @param results the array to which new Font objects will be added.
  20918. */
  20919. static void findFonts (Array<Font>& results);
  20920. /** Returns a list of all the available typeface names.
  20921. The names returned can be passed into setTypefaceName().
  20922. You can use this instead of findFonts() if you only need their names, and not
  20923. font objects.
  20924. */
  20925. static const StringArray findAllTypefaceNames();
  20926. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  20927. in the requested typeface.
  20928. */
  20929. static const String getFallbackFontName();
  20930. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  20931. available in whatever font you're trying to use.
  20932. */
  20933. static void setFallbackFontName (const String& name);
  20934. /** Creates a string to describe this font.
  20935. The string will contain information to describe the font's typeface, size, and
  20936. style. To recreate the font from this string, use fromString().
  20937. */
  20938. const String toString() const;
  20939. /** Recreates a font from its stringified encoding.
  20940. This method takes a string that was created by toString(), and recreates the
  20941. original font.
  20942. */
  20943. static const Font fromString (const String& fontDescription);
  20944. private:
  20945. friend class FontGlyphAlphaMap;
  20946. friend class TypefaceCache;
  20947. class SharedFontInternal : public ReferenceCountedObject
  20948. {
  20949. public:
  20950. SharedFontInternal (float height, int styleFlags) noexcept;
  20951. SharedFontInternal (const String& typefaceName, float height, int styleFlags) noexcept;
  20952. SharedFontInternal (const Typeface::Ptr& typeface) noexcept;
  20953. SharedFontInternal (const SharedFontInternal& other) noexcept;
  20954. bool operator== (const SharedFontInternal&) const noexcept;
  20955. String typefaceName;
  20956. float height, horizontalScale, kerning, ascent;
  20957. int styleFlags;
  20958. Typeface::Ptr typeface;
  20959. };
  20960. ReferenceCountedObjectPtr <SharedFontInternal> font;
  20961. void dupeInternalIfShared();
  20962. JUCE_LEAK_DETECTOR (Font);
  20963. };
  20964. #endif // __JUCE_FONT_JUCEHEADER__
  20965. /*** End of inlined file: juce_Font.h ***/
  20966. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20967. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20968. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20969. /**
  20970. Describes a type of stroke used to render a solid outline along a path.
  20971. A PathStrokeType object can be used directly to create the shape of an outline
  20972. around a path, and is used by Graphics::strokePath to specify the type of
  20973. stroke to draw.
  20974. @see Path, Graphics::strokePath
  20975. */
  20976. class JUCE_API PathStrokeType
  20977. {
  20978. public:
  20979. /** The type of shape to use for the corners between two adjacent line segments. */
  20980. enum JointStyle
  20981. {
  20982. mitered, /**< Indicates that corners should be drawn with sharp joints.
  20983. Note that for angles that curve back on themselves, drawing a
  20984. mitre could require extending the point too far away from the
  20985. path, so a mitre limit is imposed and any corners that exceed it
  20986. are drawn as bevelled instead. */
  20987. curved, /**< Indicates that corners should be drawn as rounded-off. */
  20988. beveled /**< Indicates that corners should be drawn with a line flattening their
  20989. outside edge. */
  20990. };
  20991. /** The type shape to use for the ends of lines. */
  20992. enum EndCapStyle
  20993. {
  20994. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  20995. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  20996. the thickness of the stroke. */
  20997. rounded /**< Ends of lines are rounded-off with a circular shape. */
  20998. };
  20999. /** Creates a stroke type.
  21000. @param strokeThickness the width of the line to use
  21001. @param jointStyle the type of joints to use for corners
  21002. @param endStyle the type of end-caps to use for the ends of open paths.
  21003. */
  21004. PathStrokeType (float strokeThickness,
  21005. JointStyle jointStyle = mitered,
  21006. EndCapStyle endStyle = butt) noexcept;
  21007. /** Createes a copy of another stroke type. */
  21008. PathStrokeType (const PathStrokeType& other) noexcept;
  21009. /** Copies another stroke onto this one. */
  21010. PathStrokeType& operator= (const PathStrokeType& other) noexcept;
  21011. /** Destructor. */
  21012. ~PathStrokeType() noexcept;
  21013. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21014. @param destPath the resultant stroked outline shape will be copied into this path.
  21015. Note that it's ok for the source and destination Paths to be
  21016. the same object, so you can easily turn a path into a stroked version
  21017. of itself.
  21018. @param sourcePath the path to use as the source
  21019. @param transform an optional transform to apply to the points from the source path
  21020. as they are being used
  21021. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21022. a higher resolution, which improves the quality if you'll later want
  21023. to enlarge the stroked path. So for example, if you're planning on drawing
  21024. the stroke at 3x the size that you're creating it, you should set this to 3.
  21025. @see createDashedStroke
  21026. */
  21027. void createStrokedPath (Path& destPath,
  21028. const Path& sourcePath,
  21029. const AffineTransform& transform = AffineTransform::identity,
  21030. float extraAccuracy = 1.0f) const;
  21031. /** Applies this stroke type to a path, creating a dashed line.
  21032. This is similar to createStrokedPath, but uses the array passed in to
  21033. break the stroke up into a series of dashes.
  21034. @param destPath the resultant stroked outline shape will be copied into this path.
  21035. Note that it's ok for the source and destination Paths to be
  21036. the same object, so you can easily turn a path into a stroked version
  21037. of itself.
  21038. @param sourcePath the path to use as the source
  21039. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  21040. a line of length 2, then skip a length of 3, then add a line of length 4,
  21041. skip 5, and keep repeating this pattern.
  21042. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  21043. an even number, otherwise the pattern will get out of step as it
  21044. repeats.
  21045. @param transform an optional transform to apply to the points from the source path
  21046. as they are being used
  21047. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21048. a higher resolution, which improves the quality if you'll later want
  21049. to enlarge the stroked path. So for example, if you're planning on drawing
  21050. the stroke at 3x the size that you're creating it, you should set this to 3.
  21051. */
  21052. void createDashedStroke (Path& destPath,
  21053. const Path& sourcePath,
  21054. const float* dashLengths,
  21055. int numDashLengths,
  21056. const AffineTransform& transform = AffineTransform::identity,
  21057. float extraAccuracy = 1.0f) const;
  21058. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21059. @param destPath the resultant stroked outline shape will be copied into this path.
  21060. Note that it's ok for the source and destination Paths to be
  21061. the same object, so you can easily turn a path into a stroked version
  21062. of itself.
  21063. @param sourcePath the path to use as the source
  21064. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  21065. @param arrowheadStartLength the length of the arrowhead at the start of the path
  21066. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  21067. @param arrowheadEndLength the length of the arrowhead at the end of the path
  21068. @param transform an optional transform to apply to the points from the source path
  21069. as they are being used
  21070. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21071. a higher resolution, which improves the quality if you'll later want
  21072. to enlarge the stroked path. So for example, if you're planning on drawing
  21073. the stroke at 3x the size that you're creating it, you should set this to 3.
  21074. @see createDashedStroke
  21075. */
  21076. void createStrokeWithArrowheads (Path& destPath,
  21077. const Path& sourcePath,
  21078. float arrowheadStartWidth, float arrowheadStartLength,
  21079. float arrowheadEndWidth, float arrowheadEndLength,
  21080. const AffineTransform& transform = AffineTransform::identity,
  21081. float extraAccuracy = 1.0f) const;
  21082. /** Returns the stroke thickness. */
  21083. float getStrokeThickness() const noexcept { return thickness; }
  21084. /** Sets the stroke thickness. */
  21085. void setStrokeThickness (float newThickness) noexcept { thickness = newThickness; }
  21086. /** Returns the joint style. */
  21087. JointStyle getJointStyle() const noexcept { return jointStyle; }
  21088. /** Sets the joint style. */
  21089. void setJointStyle (JointStyle newStyle) noexcept { jointStyle = newStyle; }
  21090. /** Returns the end-cap style. */
  21091. EndCapStyle getEndStyle() const noexcept { return endStyle; }
  21092. /** Sets the end-cap style. */
  21093. void setEndStyle (EndCapStyle newStyle) noexcept { endStyle = newStyle; }
  21094. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21095. bool operator== (const PathStrokeType& other) const noexcept;
  21096. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21097. bool operator!= (const PathStrokeType& other) const noexcept;
  21098. private:
  21099. float thickness;
  21100. JointStyle jointStyle;
  21101. EndCapStyle endStyle;
  21102. JUCE_LEAK_DETECTOR (PathStrokeType);
  21103. };
  21104. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21105. /*** End of inlined file: juce_PathStrokeType.h ***/
  21106. /*** Start of inlined file: juce_Colours.h ***/
  21107. #ifndef __JUCE_COLOURS_JUCEHEADER__
  21108. #define __JUCE_COLOURS_JUCEHEADER__
  21109. /*** Start of inlined file: juce_Colour.h ***/
  21110. #ifndef __JUCE_COLOUR_JUCEHEADER__
  21111. #define __JUCE_COLOUR_JUCEHEADER__
  21112. /*** Start of inlined file: juce_PixelFormats.h ***/
  21113. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  21114. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  21115. #ifndef DOXYGEN
  21116. #if JUCE_MSVC
  21117. #pragma pack (push, 1)
  21118. #define PACKED
  21119. #elif JUCE_GCC
  21120. #define PACKED __attribute__((packed))
  21121. #else
  21122. #define PACKED
  21123. #endif
  21124. #endif
  21125. class PixelRGB;
  21126. class PixelAlpha;
  21127. /**
  21128. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  21129. operations with it.
  21130. This is used internally by the imaging classes.
  21131. @see PixelRGB
  21132. */
  21133. class JUCE_API PixelARGB
  21134. {
  21135. public:
  21136. /** Creates a pixel without defining its colour. */
  21137. PixelARGB() noexcept {}
  21138. ~PixelARGB() noexcept {}
  21139. /** Creates a pixel from a 32-bit argb value.
  21140. */
  21141. PixelARGB (const uint32 argb_) noexcept
  21142. : argb (argb_)
  21143. {
  21144. }
  21145. forcedinline uint32 getARGB() const noexcept { return argb; }
  21146. forcedinline uint32 getUnpremultipliedARGB() const noexcept { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  21147. forcedinline uint32 getRB() const noexcept { return 0x00ff00ff & argb; }
  21148. forcedinline uint32 getAG() const noexcept { return 0x00ff00ff & (argb >> 8); }
  21149. forcedinline uint8 getAlpha() const noexcept { return components.a; }
  21150. forcedinline uint8 getRed() const noexcept { return components.r; }
  21151. forcedinline uint8 getGreen() const noexcept { return components.g; }
  21152. forcedinline uint8 getBlue() const noexcept { return components.b; }
  21153. /** Blends another pixel onto this one.
  21154. This takes into account the opacity of the pixel being overlaid, and blends
  21155. it accordingly.
  21156. */
  21157. forcedinline void blend (const PixelARGB& src) noexcept
  21158. {
  21159. uint32 sargb = src.getARGB();
  21160. const uint32 alpha = 0x100 - (sargb >> 24);
  21161. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21162. sargb += 0xff00ff00 & (getAG() * alpha);
  21163. argb = sargb;
  21164. }
  21165. /** Blends another pixel onto this one.
  21166. This takes into account the opacity of the pixel being overlaid, and blends
  21167. it accordingly.
  21168. */
  21169. forcedinline void blend (const PixelAlpha& src) noexcept;
  21170. /** Blends another pixel onto this one.
  21171. This takes into account the opacity of the pixel being overlaid, and blends
  21172. it accordingly.
  21173. */
  21174. forcedinline void blend (const PixelRGB& src) noexcept;
  21175. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21176. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21177. being used, so this can blend semi-transparently from a PixelRGB argument.
  21178. */
  21179. template <class Pixel>
  21180. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21181. {
  21182. ++extraAlpha;
  21183. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  21184. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  21185. const uint32 alpha = 0x100 - (sargb >> 24);
  21186. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21187. sargb += 0xff00ff00 & (getAG() * alpha);
  21188. argb = sargb;
  21189. }
  21190. /** Blends another pixel with this one, creating a colour that is somewhere
  21191. between the two, as specified by the amount.
  21192. */
  21193. template <class Pixel>
  21194. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21195. {
  21196. uint32 drb = getRB();
  21197. drb += (((src.getRB() - drb) * amount) >> 8);
  21198. drb &= 0x00ff00ff;
  21199. uint32 dag = getAG();
  21200. dag += (((src.getAG() - dag) * amount) >> 8);
  21201. dag &= 0x00ff00ff;
  21202. dag <<= 8;
  21203. dag |= drb;
  21204. argb = dag;
  21205. }
  21206. /** Copies another pixel colour over this one.
  21207. This doesn't blend it - this colour is simply replaced by the other one.
  21208. */
  21209. template <class Pixel>
  21210. forcedinline void set (const Pixel& src) noexcept
  21211. {
  21212. argb = src.getARGB();
  21213. }
  21214. /** Replaces the colour's alpha value with another one. */
  21215. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21216. {
  21217. components.a = newAlpha;
  21218. }
  21219. /** Multiplies the colour's alpha value with another one. */
  21220. forcedinline void multiplyAlpha (int multiplier) noexcept
  21221. {
  21222. ++multiplier;
  21223. argb = ((multiplier * getAG()) & 0xff00ff00)
  21224. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  21225. }
  21226. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21227. {
  21228. multiplyAlpha ((int) (multiplier * 256.0f));
  21229. }
  21230. /** Sets the pixel's colour from individual components. */
  21231. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) noexcept
  21232. {
  21233. components.b = b;
  21234. components.g = g;
  21235. components.r = r;
  21236. components.a = a;
  21237. }
  21238. /** Premultiplies the pixel's RGB values by its alpha. */
  21239. forcedinline void premultiply() noexcept
  21240. {
  21241. const uint32 alpha = components.a;
  21242. if (alpha < 0xff)
  21243. {
  21244. if (alpha == 0)
  21245. {
  21246. components.b = 0;
  21247. components.g = 0;
  21248. components.r = 0;
  21249. }
  21250. else
  21251. {
  21252. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  21253. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  21254. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  21255. }
  21256. }
  21257. }
  21258. /** Unpremultiplies the pixel's RGB values. */
  21259. forcedinline void unpremultiply() noexcept
  21260. {
  21261. const uint32 alpha = components.a;
  21262. if (alpha < 0xff)
  21263. {
  21264. if (alpha == 0)
  21265. {
  21266. components.b = 0;
  21267. components.g = 0;
  21268. components.r = 0;
  21269. }
  21270. else
  21271. {
  21272. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  21273. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  21274. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  21275. }
  21276. }
  21277. }
  21278. forcedinline void desaturate() noexcept
  21279. {
  21280. if (components.a < 0xff && components.a > 0)
  21281. {
  21282. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  21283. components.r = components.g = components.b
  21284. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  21285. }
  21286. else
  21287. {
  21288. components.r = components.g = components.b
  21289. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  21290. }
  21291. }
  21292. /** The indexes of the different components in the byte layout of this type of colour. */
  21293. #if JUCE_BIG_ENDIAN
  21294. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  21295. #else
  21296. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  21297. #endif
  21298. private:
  21299. union
  21300. {
  21301. uint32 argb;
  21302. struct
  21303. {
  21304. #if JUCE_BIG_ENDIAN
  21305. uint8 a : 8, r : 8, g : 8, b : 8;
  21306. #else
  21307. uint8 b, g, r, a;
  21308. #endif
  21309. } PACKED components;
  21310. };
  21311. }
  21312. #ifndef DOXYGEN
  21313. PACKED
  21314. #endif
  21315. ;
  21316. /**
  21317. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  21318. This is used internally by the imaging classes.
  21319. @see PixelARGB
  21320. */
  21321. class JUCE_API PixelRGB
  21322. {
  21323. public:
  21324. /** Creates a pixel without defining its colour. */
  21325. PixelRGB() noexcept {}
  21326. ~PixelRGB() noexcept {}
  21327. /** Creates a pixel from a 32-bit argb value.
  21328. (The argb format is that used by PixelARGB)
  21329. */
  21330. PixelRGB (const uint32 argb) noexcept
  21331. {
  21332. r = (uint8) (argb >> 16);
  21333. g = (uint8) (argb >> 8);
  21334. b = (uint8) (argb);
  21335. }
  21336. forcedinline uint32 getARGB() const noexcept { return 0xff000000 | b | (g << 8) | (r << 16); }
  21337. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return getARGB(); }
  21338. forcedinline uint32 getRB() const noexcept { return b | (uint32) (r << 16); }
  21339. forcedinline uint32 getAG() const noexcept { return 0xff0000 | g; }
  21340. forcedinline uint8 getAlpha() const noexcept { return 0xff; }
  21341. forcedinline uint8 getRed() const noexcept { return r; }
  21342. forcedinline uint8 getGreen() const noexcept { return g; }
  21343. forcedinline uint8 getBlue() const noexcept { return b; }
  21344. /** Blends another pixel onto this one.
  21345. This takes into account the opacity of the pixel being overlaid, and blends
  21346. it accordingly.
  21347. */
  21348. forcedinline void blend (const PixelARGB& src) noexcept
  21349. {
  21350. uint32 sargb = src.getARGB();
  21351. const uint32 alpha = 0x100 - (sargb >> 24);
  21352. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21353. sargb += 0x0000ff00 & (g * alpha);
  21354. r = (uint8) (sargb >> 16);
  21355. g = (uint8) (sargb >> 8);
  21356. b = (uint8) sargb;
  21357. }
  21358. forcedinline void blend (const PixelRGB& src) noexcept
  21359. {
  21360. set (src);
  21361. }
  21362. forcedinline void blend (const PixelAlpha& src) noexcept;
  21363. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21364. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21365. being used, so this can blend semi-transparently from a PixelRGB argument.
  21366. */
  21367. template <class Pixel>
  21368. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21369. {
  21370. ++extraAlpha;
  21371. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  21372. const uint32 sag = extraAlpha * src.getAG();
  21373. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  21374. const uint32 alpha = 0x100 - (sargb >> 24);
  21375. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21376. sargb += 0x0000ff00 & (g * alpha);
  21377. b = (uint8) sargb;
  21378. g = (uint8) (sargb >> 8);
  21379. r = (uint8) (sargb >> 16);
  21380. }
  21381. /** Blends another pixel with this one, creating a colour that is somewhere
  21382. between the two, as specified by the amount.
  21383. */
  21384. template <class Pixel>
  21385. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21386. {
  21387. uint32 drb = getRB();
  21388. drb += (((src.getRB() - drb) * amount) >> 8);
  21389. uint32 dag = getAG();
  21390. dag += (((src.getAG() - dag) * amount) >> 8);
  21391. b = (uint8) drb;
  21392. g = (uint8) dag;
  21393. r = (uint8) (drb >> 16);
  21394. }
  21395. /** Copies another pixel colour over this one.
  21396. This doesn't blend it - this colour is simply replaced by the other one.
  21397. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  21398. is thrown away.
  21399. */
  21400. template <class Pixel>
  21401. forcedinline void set (const Pixel& src) noexcept
  21402. {
  21403. b = src.getBlue();
  21404. g = src.getGreen();
  21405. r = src.getRed();
  21406. }
  21407. /** This method is included for compatibility with the PixelARGB class. */
  21408. forcedinline void setAlpha (const uint8) noexcept {}
  21409. /** Multiplies the colour's alpha value with another one. */
  21410. forcedinline void multiplyAlpha (int) noexcept {}
  21411. /** Sets the pixel's colour from individual components. */
  21412. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) noexcept
  21413. {
  21414. r = r_;
  21415. g = g_;
  21416. b = b_;
  21417. }
  21418. /** Premultiplies the pixel's RGB values by its alpha. */
  21419. forcedinline void premultiply() noexcept {}
  21420. /** Unpremultiplies the pixel's RGB values. */
  21421. forcedinline void unpremultiply() noexcept {}
  21422. forcedinline void desaturate() noexcept
  21423. {
  21424. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  21425. }
  21426. /** The indexes of the different components in the byte layout of this type of colour. */
  21427. #if JUCE_MAC
  21428. enum { indexR = 0, indexG = 1, indexB = 2 };
  21429. #else
  21430. enum { indexR = 2, indexG = 1, indexB = 0 };
  21431. #endif
  21432. private:
  21433. #if JUCE_MAC
  21434. uint8 r, g, b;
  21435. #else
  21436. uint8 b, g, r;
  21437. #endif
  21438. }
  21439. #ifndef DOXYGEN
  21440. PACKED
  21441. #endif
  21442. ;
  21443. forcedinline void PixelARGB::blend (const PixelRGB& src) noexcept
  21444. {
  21445. set (src);
  21446. }
  21447. /**
  21448. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  21449. This is used internally by the imaging classes.
  21450. @see PixelARGB, PixelRGB
  21451. */
  21452. class JUCE_API PixelAlpha
  21453. {
  21454. public:
  21455. /** Creates a pixel without defining its colour. */
  21456. PixelAlpha() noexcept {}
  21457. ~PixelAlpha() noexcept {}
  21458. /** Creates a pixel from a 32-bit argb value.
  21459. (The argb format is that used by PixelARGB)
  21460. */
  21461. PixelAlpha (const uint32 argb) noexcept
  21462. {
  21463. a = (uint8) (argb >> 24);
  21464. }
  21465. forcedinline uint32 getARGB() const noexcept { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  21466. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return (((uint32) a) << 24) | 0xffffff; }
  21467. forcedinline uint32 getRB() const noexcept { return (((uint32) a) << 16) | a; }
  21468. forcedinline uint32 getAG() const noexcept { return (((uint32) a) << 16) | a; }
  21469. forcedinline uint8 getAlpha() const noexcept { return a; }
  21470. forcedinline uint8 getRed() const noexcept { return 0; }
  21471. forcedinline uint8 getGreen() const noexcept { return 0; }
  21472. forcedinline uint8 getBlue() const noexcept { return 0; }
  21473. /** Blends another pixel onto this one.
  21474. This takes into account the opacity of the pixel being overlaid, and blends
  21475. it accordingly.
  21476. */
  21477. template <class Pixel>
  21478. forcedinline void blend (const Pixel& src) noexcept
  21479. {
  21480. const int srcA = src.getAlpha();
  21481. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  21482. }
  21483. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21484. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21485. being used, so this can blend semi-transparently from a PixelRGB argument.
  21486. */
  21487. template <class Pixel>
  21488. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21489. {
  21490. ++extraAlpha;
  21491. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  21492. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  21493. }
  21494. /** Blends another pixel with this one, creating a colour that is somewhere
  21495. between the two, as specified by the amount.
  21496. */
  21497. template <class Pixel>
  21498. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21499. {
  21500. a += ((src,getAlpha() - a) * amount) >> 8;
  21501. }
  21502. /** Copies another pixel colour over this one.
  21503. This doesn't blend it - this colour is simply replaced by the other one.
  21504. */
  21505. template <class Pixel>
  21506. forcedinline void set (const Pixel& src) noexcept
  21507. {
  21508. a = src.getAlpha();
  21509. }
  21510. /** Replaces the colour's alpha value with another one. */
  21511. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21512. {
  21513. a = newAlpha;
  21514. }
  21515. /** Multiplies the colour's alpha value with another one. */
  21516. forcedinline void multiplyAlpha (int multiplier) noexcept
  21517. {
  21518. ++multiplier;
  21519. a = (uint8) ((a * multiplier) >> 8);
  21520. }
  21521. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21522. {
  21523. a = (uint8) (a * multiplier);
  21524. }
  21525. /** Sets the pixel's colour from individual components. */
  21526. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) noexcept
  21527. {
  21528. a = a_;
  21529. }
  21530. /** Premultiplies the pixel's RGB values by its alpha. */
  21531. forcedinline void premultiply() noexcept
  21532. {
  21533. }
  21534. /** Unpremultiplies the pixel's RGB values. */
  21535. forcedinline void unpremultiply() noexcept
  21536. {
  21537. }
  21538. forcedinline void desaturate() noexcept
  21539. {
  21540. }
  21541. /** The indexes of the different components in the byte layout of this type of colour. */
  21542. enum { indexA = 0 };
  21543. private:
  21544. uint8 a : 8;
  21545. }
  21546. #ifndef DOXYGEN
  21547. PACKED
  21548. #endif
  21549. ;
  21550. forcedinline void PixelRGB::blend (const PixelAlpha& src) noexcept
  21551. {
  21552. blend (PixelARGB (src.getARGB()));
  21553. }
  21554. forcedinline void PixelARGB::blend (const PixelAlpha& src) noexcept
  21555. {
  21556. uint32 sargb = src.getARGB();
  21557. const uint32 alpha = 0x100 - (sargb >> 24);
  21558. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21559. sargb += 0xff00ff00 & (getAG() * alpha);
  21560. argb = sargb;
  21561. }
  21562. #if JUCE_MSVC
  21563. #pragma pack (pop)
  21564. #endif
  21565. #undef PACKED
  21566. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21567. /*** End of inlined file: juce_PixelFormats.h ***/
  21568. /**
  21569. Represents a colour, also including a transparency value.
  21570. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21571. */
  21572. class JUCE_API Colour
  21573. {
  21574. public:
  21575. /** Creates a transparent black colour. */
  21576. Colour() noexcept;
  21577. /** Creates a copy of another Colour object. */
  21578. Colour (const Colour& other) noexcept;
  21579. /** Creates a colour from a 32-bit ARGB value.
  21580. The format of this number is:
  21581. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21582. All components in the range 0x00 to 0xff.
  21583. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21584. @see getPixelARGB
  21585. */
  21586. explicit Colour (uint32 argb) noexcept;
  21587. /** Creates an opaque colour using 8-bit red, green and blue values */
  21588. Colour (uint8 red,
  21589. uint8 green,
  21590. uint8 blue) noexcept;
  21591. /** Creates an opaque colour using 8-bit red, green and blue values */
  21592. static const Colour fromRGB (uint8 red,
  21593. uint8 green,
  21594. uint8 blue) noexcept;
  21595. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21596. Colour (uint8 red,
  21597. uint8 green,
  21598. uint8 blue,
  21599. uint8 alpha) noexcept;
  21600. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21601. static const Colour fromRGBA (uint8 red,
  21602. uint8 green,
  21603. uint8 blue,
  21604. uint8 alpha) noexcept;
  21605. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21606. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21607. Values outside the valid range will be clipped.
  21608. */
  21609. Colour (uint8 red,
  21610. uint8 green,
  21611. uint8 blue,
  21612. float alpha) noexcept;
  21613. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21614. static const Colour fromRGBAFloat (uint8 red,
  21615. uint8 green,
  21616. uint8 blue,
  21617. float alpha) noexcept;
  21618. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21619. The floating point values must be between 0.0 and 1.0.
  21620. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21621. Values outside the valid range will be clipped.
  21622. */
  21623. Colour (float hue,
  21624. float saturation,
  21625. float brightness,
  21626. uint8 alpha) noexcept;
  21627. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21628. All values must be between 0.0 and 1.0.
  21629. Numbers outside the valid range will be clipped.
  21630. */
  21631. Colour (float hue,
  21632. float saturation,
  21633. float brightness,
  21634. float alpha) noexcept;
  21635. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21636. The floating point values must be between 0.0 and 1.0.
  21637. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21638. Values outside the valid range will be clipped.
  21639. */
  21640. static const Colour fromHSV (float hue,
  21641. float saturation,
  21642. float brightness,
  21643. float alpha) noexcept;
  21644. /** Destructor. */
  21645. ~Colour() noexcept;
  21646. /** Copies another Colour object. */
  21647. Colour& operator= (const Colour& other) noexcept;
  21648. /** Compares two colours. */
  21649. bool operator== (const Colour& other) const noexcept;
  21650. /** Compares two colours. */
  21651. bool operator!= (const Colour& other) const noexcept;
  21652. /** Returns the red component of this colour.
  21653. @returns a value between 0x00 and 0xff.
  21654. */
  21655. uint8 getRed() const noexcept { return argb.getRed(); }
  21656. /** Returns the green component of this colour.
  21657. @returns a value between 0x00 and 0xff.
  21658. */
  21659. uint8 getGreen() const noexcept { return argb.getGreen(); }
  21660. /** Returns the blue component of this colour.
  21661. @returns a value between 0x00 and 0xff.
  21662. */
  21663. uint8 getBlue() const noexcept { return argb.getBlue(); }
  21664. /** Returns the red component of this colour as a floating point value.
  21665. @returns a value between 0.0 and 1.0
  21666. */
  21667. float getFloatRed() const noexcept;
  21668. /** Returns the green component of this colour as a floating point value.
  21669. @returns a value between 0.0 and 1.0
  21670. */
  21671. float getFloatGreen() const noexcept;
  21672. /** Returns the blue component of this colour as a floating point value.
  21673. @returns a value between 0.0 and 1.0
  21674. */
  21675. float getFloatBlue() const noexcept;
  21676. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21677. */
  21678. const PixelARGB getPixelARGB() const noexcept;
  21679. /** Returns a 32-bit integer that represents this colour.
  21680. The format of this number is:
  21681. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21682. */
  21683. uint32 getARGB() const noexcept;
  21684. /** Returns the colour's alpha (opacity).
  21685. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21686. */
  21687. uint8 getAlpha() const noexcept { return argb.getAlpha(); }
  21688. /** Returns the colour's alpha (opacity) as a floating point value.
  21689. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21690. */
  21691. float getFloatAlpha() const noexcept;
  21692. /** Returns true if this colour is completely opaque.
  21693. Equivalent to (getAlpha() == 0xff).
  21694. */
  21695. bool isOpaque() const noexcept;
  21696. /** Returns true if this colour is completely transparent.
  21697. Equivalent to (getAlpha() == 0x00).
  21698. */
  21699. bool isTransparent() const noexcept;
  21700. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21701. const Colour withAlpha (uint8 newAlpha) const noexcept;
  21702. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21703. const Colour withAlpha (float newAlpha) const noexcept;
  21704. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21705. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21706. */
  21707. const Colour withMultipliedAlpha (float alphaMultiplier) const noexcept;
  21708. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21709. If the foreground colour is semi-transparent, it is blended onto this colour
  21710. accordingly.
  21711. */
  21712. const Colour overlaidWith (const Colour& foregroundColour) const noexcept;
  21713. /** Returns a colour that lies somewhere between this one and another.
  21714. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21715. is 1.0, the result is 100% of the other colour.
  21716. */
  21717. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const noexcept;
  21718. /** Returns the colour's hue component.
  21719. The value returned is in the range 0.0 to 1.0
  21720. */
  21721. float getHue() const noexcept;
  21722. /** Returns the colour's saturation component.
  21723. The value returned is in the range 0.0 to 1.0
  21724. */
  21725. float getSaturation() const noexcept;
  21726. /** Returns the colour's brightness component.
  21727. The value returned is in the range 0.0 to 1.0
  21728. */
  21729. float getBrightness() const noexcept;
  21730. /** Returns the colour's hue, saturation and brightness components all at once.
  21731. The values returned are in the range 0.0 to 1.0
  21732. */
  21733. void getHSB (float& hue,
  21734. float& saturation,
  21735. float& brightness) const noexcept;
  21736. /** Returns a copy of this colour with a different hue. */
  21737. const Colour withHue (float newHue) const noexcept;
  21738. /** Returns a copy of this colour with a different saturation. */
  21739. const Colour withSaturation (float newSaturation) const noexcept;
  21740. /** Returns a copy of this colour with a different brightness.
  21741. @see brighter, darker, withMultipliedBrightness
  21742. */
  21743. const Colour withBrightness (float newBrightness) const noexcept;
  21744. /** Returns a copy of this colour with it hue rotated.
  21745. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21746. @see brighter, darker, withMultipliedBrightness
  21747. */
  21748. const Colour withRotatedHue (float amountToRotate) const noexcept;
  21749. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21750. The new colour's saturation is (this->getSaturation() * multiplier)
  21751. (the result is clipped to legal limits).
  21752. */
  21753. const Colour withMultipliedSaturation (float multiplier) const noexcept;
  21754. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21755. The new colour's saturation is (this->getBrightness() * multiplier)
  21756. (the result is clipped to legal limits).
  21757. */
  21758. const Colour withMultipliedBrightness (float amount) const noexcept;
  21759. /** Returns a brighter version of this colour.
  21760. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21761. unchanged, and higher values make it brighter
  21762. @see withMultipliedBrightness
  21763. */
  21764. const Colour brighter (float amountBrighter = 0.4f) const noexcept;
  21765. /** Returns a darker version of this colour.
  21766. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  21767. unchanged, and higher values make it darker
  21768. @see withMultipliedBrightness
  21769. */
  21770. const Colour darker (float amountDarker = 0.4f) const noexcept;
  21771. /** Returns a colour that will be clearly visible against this colour.
  21772. The amount parameter indicates how contrasting the new colour should
  21773. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  21774. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  21775. return white; Colours::white.contrasting (1.0f) will return black, etc.
  21776. */
  21777. const Colour contrasting (float amount = 1.0f) const noexcept;
  21778. /** Returns a colour that contrasts against two colours.
  21779. Looks for a colour that contrasts with both of the colours passed-in.
  21780. Handy for things like choosing a highlight colour in text editors, etc.
  21781. */
  21782. static const Colour contrasting (const Colour& colour1,
  21783. const Colour& colour2) noexcept;
  21784. /** Returns an opaque shade of grey.
  21785. @param brightness the level of grey to return - 0 is black, 1.0 is white
  21786. */
  21787. static const Colour greyLevel (float brightness) noexcept;
  21788. /** Returns a stringified version of this colour.
  21789. The string can be turned back into a colour using the fromString() method.
  21790. */
  21791. const String toString() const;
  21792. /** Reads the colour from a string that was created with toString().
  21793. */
  21794. static const Colour fromString (const String& encodedColourString);
  21795. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  21796. const String toDisplayString (bool includeAlphaValue) const;
  21797. private:
  21798. PixelARGB argb;
  21799. };
  21800. #endif // __JUCE_COLOUR_JUCEHEADER__
  21801. /*** End of inlined file: juce_Colour.h ***/
  21802. /**
  21803. Contains a set of predefined named colours (mostly standard HTML colours)
  21804. @see Colour, Colours::greyLevel
  21805. */
  21806. class Colours
  21807. {
  21808. public:
  21809. static JUCE_API const Colour
  21810. transparentBlack, /**< ARGB = 0x00000000 */
  21811. transparentWhite, /**< ARGB = 0x00ffffff */
  21812. black, /**< ARGB = 0xff000000 */
  21813. white, /**< ARGB = 0xffffffff */
  21814. blue, /**< ARGB = 0xff0000ff */
  21815. grey, /**< ARGB = 0xff808080 */
  21816. green, /**< ARGB = 0xff008000 */
  21817. red, /**< ARGB = 0xffff0000 */
  21818. yellow, /**< ARGB = 0xffffff00 */
  21819. aliceblue, antiquewhite, aqua, aquamarine,
  21820. azure, beige, bisque, blanchedalmond,
  21821. blueviolet, brown, burlywood, cadetblue,
  21822. chartreuse, chocolate, coral, cornflowerblue,
  21823. cornsilk, crimson, cyan, darkblue,
  21824. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  21825. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  21826. darkorchid, darkred, darksalmon, darkseagreen,
  21827. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  21828. deeppink, deepskyblue, dimgrey, dodgerblue,
  21829. firebrick, floralwhite, forestgreen, fuchsia,
  21830. gainsboro, gold, goldenrod, greenyellow,
  21831. honeydew, hotpink, indianred, indigo,
  21832. ivory, khaki, lavender, lavenderblush,
  21833. lemonchiffon, lightblue, lightcoral, lightcyan,
  21834. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  21835. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  21836. lightsteelblue, lightyellow, lime, limegreen,
  21837. linen, magenta, maroon, mediumaquamarine,
  21838. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  21839. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  21840. midnightblue, mintcream, mistyrose, navajowhite,
  21841. navy, oldlace, olive, olivedrab,
  21842. orange, orangered, orchid, palegoldenrod,
  21843. palegreen, paleturquoise, palevioletred, papayawhip,
  21844. peachpuff, peru, pink, plum,
  21845. powderblue, purple, rosybrown, royalblue,
  21846. saddlebrown, salmon, sandybrown, seagreen,
  21847. seashell, sienna, silver, skyblue,
  21848. slateblue, slategrey, snow, springgreen,
  21849. steelblue, tan, teal, thistle,
  21850. tomato, turquoise, violet, wheat,
  21851. whitesmoke, yellowgreen;
  21852. /** Attempts to look up a string in the list of known colour names, and return
  21853. the appropriate colour.
  21854. A non-case-sensitive search is made of the list of predefined colours, and
  21855. if a match is found, that colour is returned. If no match is found, the
  21856. colour passed in as the defaultColour parameter is returned.
  21857. */
  21858. static JUCE_API const Colour findColourForName (const String& colourName,
  21859. const Colour& defaultColour);
  21860. private:
  21861. // this isn't a class you should ever instantiate - it's just here for the
  21862. // static values in it.
  21863. Colours();
  21864. JUCE_DECLARE_NON_COPYABLE (Colours);
  21865. };
  21866. #endif // __JUCE_COLOURS_JUCEHEADER__
  21867. /*** End of inlined file: juce_Colours.h ***/
  21868. /*** Start of inlined file: juce_ColourGradient.h ***/
  21869. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  21870. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  21871. /**
  21872. Describes the layout and colours that should be used to paint a colour gradient.
  21873. @see Graphics::setGradientFill
  21874. */
  21875. class JUCE_API ColourGradient
  21876. {
  21877. public:
  21878. /** Creates a gradient object.
  21879. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  21880. colour2 should be. In between them there's a gradient.
  21881. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  21882. its centre.
  21883. The alpha transparencies of the colours are used, so note that
  21884. if you blend from transparent to a solid colour, the RGB of the transparent
  21885. colour will become visible in parts of the gradient. e.g. blending
  21886. from Colour::transparentBlack to Colours::white will produce a
  21887. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  21888. will be white all the way across.
  21889. @see ColourGradient
  21890. */
  21891. ColourGradient (const Colour& colour1, float x1, float y1,
  21892. const Colour& colour2, float x2, float y2,
  21893. bool isRadial);
  21894. /** Creates an uninitialised gradient.
  21895. If you use this constructor instead of the other one, be sure to set all the
  21896. object's public member variables before using it!
  21897. */
  21898. ColourGradient() noexcept;
  21899. /** Destructor */
  21900. ~ColourGradient();
  21901. /** Removes any colours that have been added.
  21902. This will also remove any start and end colours, so the gradient won't work. You'll
  21903. need to add more colours with addColour().
  21904. */
  21905. void clearColours();
  21906. /** Adds a colour at a point along the length of the gradient.
  21907. This allows the gradient to go through a spectrum of colours, instead of just a
  21908. start and end colour.
  21909. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  21910. of the distance along the line between the two points
  21911. at which the colour should occur.
  21912. @param colour the colour that should be used at this point
  21913. @returns the index at which the new point was added
  21914. */
  21915. int addColour (double proportionAlongGradient,
  21916. const Colour& colour);
  21917. /** Removes one of the colours from the gradient. */
  21918. void removeColour (int index);
  21919. /** Multiplies the alpha value of all the colours by the given scale factor */
  21920. void multiplyOpacity (float multiplier) noexcept;
  21921. /** Returns the number of colour-stops that have been added. */
  21922. int getNumColours() const noexcept;
  21923. /** Returns the position along the length of the gradient of the colour with this index.
  21924. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  21925. */
  21926. double getColourPosition (int index) const noexcept;
  21927. /** Returns the colour that was added with a given index.
  21928. The index is from 0 to getNumColours() - 1.
  21929. */
  21930. const Colour getColour (int index) const noexcept;
  21931. /** Changes the colour at a given index.
  21932. The index is from 0 to getNumColours() - 1.
  21933. */
  21934. void setColour (int index, const Colour& newColour) noexcept;
  21935. /** Returns the an interpolated colour at any position along the gradient.
  21936. @param position the position along the gradient, between 0 and 1
  21937. */
  21938. const Colour getColourAtPosition (double position) const noexcept;
  21939. /** Creates a set of interpolated premultiplied ARGB values.
  21940. This will resize the HeapBlock, fill it with the colours, and will return the number of
  21941. colours that it added.
  21942. */
  21943. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  21944. /** Returns true if all colours are opaque. */
  21945. bool isOpaque() const noexcept;
  21946. /** Returns true if all colours are completely transparent. */
  21947. bool isInvisible() const noexcept;
  21948. Point<float> point1, point2;
  21949. /** If true, the gradient should be filled circularly, centred around
  21950. point1, with point2 defining a point on the circumference.
  21951. If false, the gradient is linear between the two points.
  21952. */
  21953. bool isRadial;
  21954. bool operator== (const ColourGradient& other) const noexcept;
  21955. bool operator!= (const ColourGradient& other) const noexcept;
  21956. private:
  21957. struct ColourPoint
  21958. {
  21959. ColourPoint() noexcept {}
  21960. ColourPoint (const double position_, const Colour& colour_) noexcept
  21961. : position (position_), colour (colour_)
  21962. {}
  21963. bool operator== (const ColourPoint& other) const noexcept;
  21964. bool operator!= (const ColourPoint& other) const noexcept;
  21965. double position;
  21966. Colour colour;
  21967. };
  21968. Array <ColourPoint> colours;
  21969. JUCE_LEAK_DETECTOR (ColourGradient);
  21970. };
  21971. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  21972. /*** End of inlined file: juce_ColourGradient.h ***/
  21973. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  21974. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21975. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21976. /**
  21977. Defines the method used to postion some kind of rectangular object within
  21978. a rectangular viewport.
  21979. Although similar to Justification, this is more specific, and has some extra
  21980. options.
  21981. */
  21982. class JUCE_API RectanglePlacement
  21983. {
  21984. public:
  21985. /** Creates a RectanglePlacement object using a combination of flags. */
  21986. inline RectanglePlacement (int flags_) noexcept : flags (flags_) {}
  21987. /** Creates a copy of another RectanglePlacement object. */
  21988. RectanglePlacement (const RectanglePlacement& other) noexcept;
  21989. /** Copies another RectanglePlacement object. */
  21990. RectanglePlacement& operator= (const RectanglePlacement& other) noexcept;
  21991. bool operator== (const RectanglePlacement& other) const noexcept;
  21992. bool operator!= (const RectanglePlacement& other) const noexcept;
  21993. /** Flag values that can be combined and used in the constructor. */
  21994. enum
  21995. {
  21996. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  21997. xLeft = 1,
  21998. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  21999. xRight = 2,
  22000. /** Indicates that the source should be placed in the centre between the left and right
  22001. sides of the available space. */
  22002. xMid = 4,
  22003. /** Indicates that the source's top edge should be aligned with the top edge of the
  22004. destination rectangle. */
  22005. yTop = 8,
  22006. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  22007. destination rectangle. */
  22008. yBottom = 16,
  22009. /** Indicates that the source should be placed in the centre between the top and bottom
  22010. sides of the available space. */
  22011. yMid = 32,
  22012. /** If this flag is set, then the source rectangle will be resized to completely fill
  22013. the destination rectangle, and all other flags are ignored.
  22014. */
  22015. stretchToFit = 64,
  22016. /** If this flag is set, then the source rectangle will be resized so that it is the
  22017. minimum size to completely fill the destination rectangle, without changing its
  22018. aspect ratio. This means that some of the source rectangle may fall outside
  22019. the destination.
  22020. If this flag is not set, the source will be given the maximum size at which none
  22021. of it falls outside the destination rectangle.
  22022. */
  22023. fillDestination = 128,
  22024. /** Indicates that the source rectangle can be reduced in size if required, but should
  22025. never be made larger than its original size.
  22026. */
  22027. onlyReduceInSize = 256,
  22028. /** Indicates that the source rectangle can be enlarged if required, but should
  22029. never be made smaller than its original size.
  22030. */
  22031. onlyIncreaseInSize = 512,
  22032. /** Indicates that the source rectangle's size should be left unchanged.
  22033. */
  22034. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  22035. /** A shorthand value that is equivalent to (xMid | yMid). */
  22036. centred = 4 + 32
  22037. };
  22038. /** Returns the raw flags that are set for this object. */
  22039. inline int getFlags() const noexcept { return flags; }
  22040. /** Tests a set of flags for this object.
  22041. @returns true if any of the flags passed in are set on this object.
  22042. */
  22043. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  22044. /** Adjusts the position and size of a rectangle to fit it into a space.
  22045. The source rectangle co-ordinates will be adjusted so that they fit into
  22046. the destination rectangle based on this object's flags.
  22047. */
  22048. void applyTo (double& sourceX,
  22049. double& sourceY,
  22050. double& sourceW,
  22051. double& sourceH,
  22052. double destinationX,
  22053. double destinationY,
  22054. double destinationW,
  22055. double destinationH) const noexcept;
  22056. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22057. into the destination rectangle using the current flags.
  22058. */
  22059. template <typename ValueType>
  22060. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  22061. const Rectangle<ValueType>& destination) const noexcept
  22062. {
  22063. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  22064. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  22065. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  22066. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  22067. static_cast <ValueType> (w), static_cast <ValueType> (h));
  22068. }
  22069. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22070. into the destination rectangle using the current flags.
  22071. */
  22072. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  22073. const Rectangle<float>& destination) const noexcept;
  22074. private:
  22075. int flags;
  22076. };
  22077. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22078. /*** End of inlined file: juce_RectanglePlacement.h ***/
  22079. class LowLevelGraphicsContext;
  22080. class Image;
  22081. class FillType;
  22082. class RectangleList;
  22083. /**
  22084. A graphics context, used for drawing a component or image.
  22085. When a Component needs painting, a Graphics context is passed to its
  22086. Component::paint() method, and this you then call methods within this
  22087. object to actually draw the component's content.
  22088. A Graphics can also be created from an image, to allow drawing directly onto
  22089. that image.
  22090. @see Component::paint
  22091. */
  22092. class JUCE_API Graphics
  22093. {
  22094. public:
  22095. /** Creates a Graphics object to draw directly onto the given image.
  22096. The graphics object that is created will be set up to draw onto the image,
  22097. with the context's clipping area being the entire size of the image, and its
  22098. origin being the image's origin. To draw into a subsection of an image, use the
  22099. reduceClipRegion() and setOrigin() methods.
  22100. Obviously you shouldn't delete the image before this context is deleted.
  22101. */
  22102. explicit Graphics (const Image& imageToDrawOnto);
  22103. /** Destructor. */
  22104. ~Graphics();
  22105. /** Changes the current drawing colour.
  22106. This sets the colour that will now be used for drawing operations - it also
  22107. sets the opacity to that of the colour passed-in.
  22108. If a brush is being used when this method is called, the brush will be deselected,
  22109. and any subsequent drawing will be done with a solid colour brush instead.
  22110. @see setOpacity
  22111. */
  22112. void setColour (const Colour& newColour);
  22113. /** Changes the opacity to use with the current colour.
  22114. If a solid colour is being used for drawing, this changes its opacity
  22115. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  22116. If a gradient is being used, this will have no effect on it.
  22117. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  22118. */
  22119. void setOpacity (float newOpacity);
  22120. /** Sets the context to use a gradient for its fill pattern.
  22121. */
  22122. void setGradientFill (const ColourGradient& gradient);
  22123. /** Sets the context to use a tiled image pattern for filling.
  22124. Make sure that you don't delete this image while it's still being used by
  22125. this context!
  22126. */
  22127. void setTiledImageFill (const Image& imageToUse,
  22128. int anchorX, int anchorY,
  22129. float opacity);
  22130. /** Changes the current fill settings.
  22131. @see setColour, setGradientFill, setTiledImageFill
  22132. */
  22133. void setFillType (const FillType& newFill);
  22134. /** Changes the font to use for subsequent text-drawing functions.
  22135. Note there's also a setFont (float, int) method to quickly change the size and
  22136. style of the current font.
  22137. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  22138. */
  22139. void setFont (const Font& newFont);
  22140. /** Changes the size and style of the currently-selected font.
  22141. This is a convenient shortcut that changes the context's current font to a
  22142. different size or style. The typeface won't be changed.
  22143. @see Font
  22144. */
  22145. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  22146. /** Returns the currently selected font. */
  22147. const Font getCurrentFont() const;
  22148. /** Draws a one-line text string.
  22149. This will use the current colour (or brush) to fill the text. The font is the last
  22150. one specified by setFont().
  22151. @param text the string to draw
  22152. @param startX the position to draw the left-hand edge of the text
  22153. @param baselineY the position of the text's baseline
  22154. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  22155. */
  22156. void drawSingleLineText (const String& text,
  22157. int startX, int baselineY) const;
  22158. /** Draws text across multiple lines.
  22159. This will break the text onto a new line where there's a new-line or
  22160. carriage-return character, or at a word-boundary when the text becomes wider
  22161. than the size specified by the maximumLineWidth parameter.
  22162. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  22163. */
  22164. void drawMultiLineText (const String& text,
  22165. int startX, int baselineY,
  22166. int maximumLineWidth) const;
  22167. /** Renders a string of text as a vector path.
  22168. This allows a string to be transformed with an arbitrary AffineTransform and
  22169. rendered using the current colour/brush. It's much slower than the normal text methods
  22170. but more accurate.
  22171. @see setFont
  22172. */
  22173. void drawTextAsPath (const String& text,
  22174. const AffineTransform& transform) const;
  22175. /** Draws a line of text within a specified rectangle.
  22176. The text will be positioned within the rectangle based on the justification
  22177. flags passed-in. If the string is too long to fit inside the rectangle, it will
  22178. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  22179. flag is true).
  22180. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  22181. */
  22182. void drawText (const String& text,
  22183. int x, int y, int width, int height,
  22184. const Justification& justificationType,
  22185. bool useEllipsesIfTooBig) const;
  22186. /** Tries to draw a text string inside a given space.
  22187. This does its best to make the given text readable within the specified rectangle,
  22188. so it useful for labelling things.
  22189. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  22190. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  22191. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  22192. it's been truncated.
  22193. A Justification parameter lets you specify how the text is laid out within the rectangle,
  22194. both horizontally and vertically.
  22195. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  22196. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  22197. can set this value to 1.0f.
  22198. @see GlyphArrangement::addFittedText
  22199. */
  22200. void drawFittedText (const String& text,
  22201. int x, int y, int width, int height,
  22202. const Justification& justificationFlags,
  22203. int maximumNumberOfLines,
  22204. float minimumHorizontalScale = 0.7f) const;
  22205. /** Fills the context's entire clip region with the current colour or brush.
  22206. (See also the fillAll (const Colour&) method which is a quick way of filling
  22207. it with a given colour).
  22208. */
  22209. void fillAll() const;
  22210. /** Fills the context's entire clip region with a given colour.
  22211. This leaves the context's current colour and brush unchanged, it just
  22212. uses the specified colour temporarily.
  22213. */
  22214. void fillAll (const Colour& colourToUse) const;
  22215. /** Fills a rectangle with the current colour or brush.
  22216. @see drawRect, fillRoundedRectangle
  22217. */
  22218. void fillRect (int x, int y, int width, int height) const;
  22219. /** Fills a rectangle with the current colour or brush. */
  22220. void fillRect (const Rectangle<int>& rectangle) const;
  22221. /** Fills a rectangle with the current colour or brush.
  22222. This uses sub-pixel positioning so is slower than the fillRect method which
  22223. takes integer co-ordinates.
  22224. */
  22225. void fillRect (float x, float y, float width, float height) const;
  22226. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22227. @see drawRoundedRectangle, Path::addRoundedRectangle
  22228. */
  22229. void fillRoundedRectangle (float x, float y, float width, float height,
  22230. float cornerSize) const;
  22231. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22232. @see drawRoundedRectangle, Path::addRoundedRectangle
  22233. */
  22234. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  22235. float cornerSize) const;
  22236. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  22237. */
  22238. void fillCheckerBoard (const Rectangle<int>& area,
  22239. int checkWidth, int checkHeight,
  22240. const Colour& colour1, const Colour& colour2) const;
  22241. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22242. The lines are drawn inside the given rectangle, and greater line thicknesses
  22243. extend inwards.
  22244. @see fillRect
  22245. */
  22246. void drawRect (int x, int y, int width, int height,
  22247. int lineThickness = 1) const;
  22248. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22249. The lines are drawn inside the given rectangle, and greater line thicknesses
  22250. extend inwards.
  22251. @see fillRect
  22252. */
  22253. void drawRect (float x, float y, float width, float height,
  22254. float lineThickness = 1.0f) const;
  22255. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22256. The lines are drawn inside the given rectangle, and greater line thicknesses
  22257. extend inwards.
  22258. @see fillRect
  22259. */
  22260. void drawRect (const Rectangle<int>& rectangle,
  22261. int lineThickness = 1) const;
  22262. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22263. @see fillRoundedRectangle, Path::addRoundedRectangle
  22264. */
  22265. void drawRoundedRectangle (float x, float y, float width, float height,
  22266. float cornerSize, float lineThickness) const;
  22267. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22268. @see fillRoundedRectangle, Path::addRoundedRectangle
  22269. */
  22270. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  22271. float cornerSize, float lineThickness) const;
  22272. /** Draws a 3D raised (or indented) bevel using two colours.
  22273. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  22274. extend inwards.
  22275. The top-left colour is used for the top- and left-hand edges of the
  22276. bevel; the bottom-right colour is used for the bottom- and right-hand
  22277. edges.
  22278. If useGradient is true, then the bevel fades out to make it look more curved
  22279. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  22280. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  22281. the centre edges are sharp and it fades towards the outside.
  22282. */
  22283. void drawBevel (int x, int y, int width, int height,
  22284. int bevelThickness,
  22285. const Colour& topLeftColour = Colours::white,
  22286. const Colour& bottomRightColour = Colours::black,
  22287. bool useGradient = true,
  22288. bool sharpEdgeOnOutside = true) const;
  22289. /** Draws a pixel using the current colour or brush.
  22290. */
  22291. void setPixel (int x, int y) const;
  22292. /** Fills an ellipse with the current colour or brush.
  22293. The ellipse is drawn to fit inside the given rectangle.
  22294. @see drawEllipse, Path::addEllipse
  22295. */
  22296. void fillEllipse (float x, float y, float width, float height) const;
  22297. /** Draws an elliptical stroke using the current colour or brush.
  22298. @see fillEllipse, Path::addEllipse
  22299. */
  22300. void drawEllipse (float x, float y, float width, float height,
  22301. float lineThickness) const;
  22302. /** Draws a line between two points.
  22303. The line is 1 pixel wide and drawn with the current colour or brush.
  22304. */
  22305. void drawLine (float startX, float startY, float endX, float endY) const;
  22306. /** Draws a line between two points with a given thickness.
  22307. @see Path::addLineSegment
  22308. */
  22309. void drawLine (float startX, float startY, float endX, float endY,
  22310. float lineThickness) const;
  22311. /** Draws a line between two points.
  22312. The line is 1 pixel wide and drawn with the current colour or brush.
  22313. */
  22314. void drawLine (const Line<float>& line) const;
  22315. /** Draws a line between two points with a given thickness.
  22316. @see Path::addLineSegment
  22317. */
  22318. void drawLine (const Line<float>& line, float lineThickness) const;
  22319. /** Draws a dashed line using a custom set of dash-lengths.
  22320. @param line the line to draw
  22321. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  22322. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  22323. draw 6 pixels, skip 7 pixels, and then repeat.
  22324. @param numDashLengths the number of elements in the array (this must be an even number).
  22325. @param lineThickness the thickness of the line to draw
  22326. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  22327. @see PathStrokeType::createDashedStroke
  22328. */
  22329. void drawDashedLine (const Line<float>& line,
  22330. const float* dashLengths, int numDashLengths,
  22331. float lineThickness = 1.0f,
  22332. int dashIndexToStartFrom = 0) const;
  22333. /** Draws a vertical line of pixels at a given x position.
  22334. The x position is an integer, but the top and bottom of the line can be sub-pixel
  22335. positions, and these will be anti-aliased if necessary.
  22336. */
  22337. void drawVerticalLine (int x, float top, float bottom) const;
  22338. /** Draws a horizontal line of pixels at a given y position.
  22339. The y position is an integer, but the left and right ends of the line can be sub-pixel
  22340. positions, and these will be anti-aliased if necessary.
  22341. */
  22342. void drawHorizontalLine (int y, float left, float right) const;
  22343. /** Fills a path using the currently selected colour or brush.
  22344. */
  22345. void fillPath (const Path& path,
  22346. const AffineTransform& transform = AffineTransform::identity) const;
  22347. /** Draws a path's outline using the currently selected colour or brush.
  22348. */
  22349. void strokePath (const Path& path,
  22350. const PathStrokeType& strokeType,
  22351. const AffineTransform& transform = AffineTransform::identity) const;
  22352. /** Draws a line with an arrowhead at its end.
  22353. @param line the line to draw
  22354. @param lineThickness the thickness of the line
  22355. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  22356. @param arrowheadLength the length of the arrow head (along the length of the line)
  22357. */
  22358. void drawArrow (const Line<float>& line,
  22359. float lineThickness,
  22360. float arrowheadWidth,
  22361. float arrowheadLength) const;
  22362. /** Types of rendering quality that can be specified when drawing images.
  22363. @see blendImage, Graphics::setImageResamplingQuality
  22364. */
  22365. enum ResamplingQuality
  22366. {
  22367. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  22368. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  22369. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  22370. };
  22371. /** Changes the quality that will be used when resampling images.
  22372. By default a Graphics object will be set to mediumRenderingQuality.
  22373. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  22374. */
  22375. void setImageResamplingQuality (const ResamplingQuality newQuality);
  22376. /** Draws an image.
  22377. This will draw the whole of an image, positioning its top-left corner at the
  22378. given co-ordinates, and keeping its size the same. This is the simplest image
  22379. drawing method - the others give more control over the scaling and clipping
  22380. of the images.
  22381. Images are composited using the context's current opacity, so if you
  22382. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22383. (or setColour() with an opaque colour) before drawing images.
  22384. */
  22385. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  22386. bool fillAlphaChannelWithCurrentBrush = false) const;
  22387. /** Draws part of an image, rescaling it to fit in a given target region.
  22388. The specified area of the source image is rescaled and drawn to fill the
  22389. specifed destination rectangle.
  22390. Images are composited using the context's current opacity, so if you
  22391. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22392. (or setColour() with an opaque colour) before drawing images.
  22393. @param imageToDraw the image to overlay
  22394. @param destX the left of the destination rectangle
  22395. @param destY the top of the destination rectangle
  22396. @param destWidth the width of the destination rectangle
  22397. @param destHeight the height of the destination rectangle
  22398. @param sourceX the left of the rectangle to copy from the source image
  22399. @param sourceY the top of the rectangle to copy from the source image
  22400. @param sourceWidth the width of the rectangle to copy from the source image
  22401. @param sourceHeight the height of the rectangle to copy from the source image
  22402. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  22403. the source image's alpha channel is used as a mask with
  22404. which to fill the destination using the current colour
  22405. or brush. (If the source is has no alpha channel, then
  22406. it will just fill the target with a solid rectangle)
  22407. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  22408. */
  22409. void drawImage (const Image& imageToDraw,
  22410. int destX, int destY, int destWidth, int destHeight,
  22411. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  22412. bool fillAlphaChannelWithCurrentBrush = false) const;
  22413. /** Draws an image, having applied an affine transform to it.
  22414. This lets you throw the image around in some wacky ways, rotate it, shear,
  22415. scale it, etc.
  22416. Images are composited using the context's current opacity, so if you
  22417. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22418. (or setColour() with an opaque colour) before drawing images.
  22419. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  22420. are ignored and it is filled with the current brush, masked by its alpha channel.
  22421. If you want to render only a subsection of an image, use Image::getClippedImage() to
  22422. create the section that you need.
  22423. @see setImageResamplingQuality, drawImage
  22424. */
  22425. void drawImageTransformed (const Image& imageToDraw,
  22426. const AffineTransform& transform,
  22427. bool fillAlphaChannelWithCurrentBrush = false) const;
  22428. /** Draws an image to fit within a designated rectangle.
  22429. If the image is too big or too small for the space, it will be rescaled
  22430. to fit as nicely as it can do without affecting its aspect ratio. It will
  22431. then be placed within the target rectangle according to the justification flags
  22432. specified.
  22433. @param imageToDraw the source image to draw
  22434. @param destX top-left of the target rectangle to fit it into
  22435. @param destY top-left of the target rectangle to fit it into
  22436. @param destWidth size of the target rectangle to fit the image into
  22437. @param destHeight size of the target rectangle to fit the image into
  22438. @param placementWithinTarget this specifies how the image should be positioned
  22439. within the target rectangle - see the RectanglePlacement
  22440. class for more details about this.
  22441. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  22442. alpha channel will be used as a mask with which to
  22443. draw with the current brush or colour. This is
  22444. similar to fillAlphaMap(), and see also drawImage()
  22445. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  22446. */
  22447. void drawImageWithin (const Image& imageToDraw,
  22448. int destX, int destY, int destWidth, int destHeight,
  22449. const RectanglePlacement& placementWithinTarget,
  22450. bool fillAlphaChannelWithCurrentBrush = false) const;
  22451. /** Returns the position of the bounding box for the current clipping region.
  22452. @see getClipRegion, clipRegionIntersects
  22453. */
  22454. const Rectangle<int> getClipBounds() const;
  22455. /** Checks whether a rectangle overlaps the context's clipping region.
  22456. If this returns false, no part of the given area can be drawn onto, so this
  22457. method can be used to optimise a component's paint() method, by letting it
  22458. avoid drawing complex objects that aren't within the region being repainted.
  22459. */
  22460. bool clipRegionIntersects (const Rectangle<int>& area) const;
  22461. /** Intersects the current clipping region with another region.
  22462. @returns true if the resulting clipping region is non-zero in size
  22463. @see setOrigin, clipRegionIntersects
  22464. */
  22465. bool reduceClipRegion (int x, int y, int width, int height);
  22466. /** Intersects the current clipping region with another region.
  22467. @returns true if the resulting clipping region is non-zero in size
  22468. @see setOrigin, clipRegionIntersects
  22469. */
  22470. bool reduceClipRegion (const Rectangle<int>& area);
  22471. /** Intersects the current clipping region with a rectangle list region.
  22472. @returns true if the resulting clipping region is non-zero in size
  22473. @see setOrigin, clipRegionIntersects
  22474. */
  22475. bool reduceClipRegion (const RectangleList& clipRegion);
  22476. /** Intersects the current clipping region with a path.
  22477. @returns true if the resulting clipping region is non-zero in size
  22478. @see reduceClipRegion
  22479. */
  22480. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  22481. /** Intersects the current clipping region with an image's alpha-channel.
  22482. The current clipping path is intersected with the area covered by this image's
  22483. alpha-channel, after the image has been transformed by the specified matrix.
  22484. @param image the image whose alpha-channel should be used. If the image doesn't
  22485. have an alpha-channel, it is treated as entirely opaque.
  22486. @param transform a matrix to apply to the image
  22487. @returns true if the resulting clipping region is non-zero in size
  22488. @see reduceClipRegion
  22489. */
  22490. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  22491. /** Excludes a rectangle to stop it being drawn into. */
  22492. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  22493. /** Returns true if no drawing can be done because the clip region is zero. */
  22494. bool isClipEmpty() const;
  22495. /** Saves the current graphics state on an internal stack.
  22496. To restore the state, use restoreState().
  22497. @see ScopedSaveState
  22498. */
  22499. void saveState();
  22500. /** Restores a graphics state that was previously saved with saveState().
  22501. @see ScopedSaveState
  22502. */
  22503. void restoreState();
  22504. /** Uses RAII to save and restore the state of a graphics context.
  22505. On construction, this calls Graphics::saveState(), and on destruction it calls
  22506. Graphics::restoreState() on the Graphics object that you supply.
  22507. */
  22508. class ScopedSaveState
  22509. {
  22510. public:
  22511. ScopedSaveState (Graphics& g);
  22512. ~ScopedSaveState();
  22513. private:
  22514. Graphics& context;
  22515. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  22516. };
  22517. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  22518. context with the given opacity.
  22519. The context uses an internal stack of temporary image layers to do this. When you've
  22520. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  22521. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  22522. by a corresponding call to endTransparencyLayer()!
  22523. This call also saves the current state, and endTransparencyLayer() restores it.
  22524. */
  22525. void beginTransparencyLayer (float layerOpacity);
  22526. /** Completes a drawing operation to a temporary semi-transparent buffer.
  22527. See beginTransparencyLayer() for more details.
  22528. */
  22529. void endTransparencyLayer();
  22530. /** Moves the position of the context's origin.
  22531. This changes the position that the context considers to be (0, 0) to
  22532. the specified position.
  22533. So if you call setOrigin (100, 100), then the position that was previously
  22534. referred to as (100, 100) will subsequently be considered to be (0, 0).
  22535. @see reduceClipRegion, addTransform
  22536. */
  22537. void setOrigin (int newOriginX, int newOriginY);
  22538. /** Adds a transformation which will be performed on all the graphics operations that
  22539. the context subsequently performs.
  22540. After calling this, all the coordinates that are passed into the context will be
  22541. transformed by this matrix.
  22542. @see setOrigin
  22543. */
  22544. void addTransform (const AffineTransform& transform);
  22545. /** Resets the current colour, brush, and font to default settings. */
  22546. void resetToDefaultState();
  22547. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22548. bool isVectorDevice() const;
  22549. /** Create a graphics that uses a given low-level renderer.
  22550. For internal use only.
  22551. NB. The context will NOT be deleted by this object when it is deleted.
  22552. */
  22553. Graphics (LowLevelGraphicsContext* internalContext) noexcept;
  22554. /** @internal */
  22555. LowLevelGraphicsContext* getInternalContext() const noexcept { return context; }
  22556. private:
  22557. LowLevelGraphicsContext* const context;
  22558. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22559. bool saveStatePending;
  22560. void saveStateIfPending();
  22561. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22562. };
  22563. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22564. /*** End of inlined file: juce_Graphics.h ***/
  22565. /**
  22566. A graphical effect filter that can be applied to components.
  22567. An ImageEffectFilter can be applied to the image that a component
  22568. paints before it hits the screen.
  22569. This is used for adding effects like shadows, blurs, etc.
  22570. @see Component::setComponentEffect
  22571. */
  22572. class JUCE_API ImageEffectFilter
  22573. {
  22574. public:
  22575. /** Overridden to render the effect.
  22576. The implementation of this method must use the image that is passed in
  22577. as its source, and should render its output to the graphics context passed in.
  22578. @param sourceImage the image that the source component has just rendered with
  22579. its paint() method. The image may or may not have an alpha
  22580. channel, depending on whether the component is opaque.
  22581. @param destContext the graphics context to use to draw the resultant image.
  22582. @param alpha the alpha with which to draw the resultant image to the
  22583. target context
  22584. */
  22585. virtual void applyEffect (Image& sourceImage,
  22586. Graphics& destContext,
  22587. float alpha) = 0;
  22588. /** Destructor. */
  22589. virtual ~ImageEffectFilter() {}
  22590. };
  22591. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22592. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22593. /*** Start of inlined file: juce_Image.h ***/
  22594. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22595. #define __JUCE_IMAGE_JUCEHEADER__
  22596. /**
  22597. Holds a fixed-size bitmap.
  22598. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22599. To draw into an image, create a Graphics object for it.
  22600. e.g. @code
  22601. // create a transparent 500x500 image..
  22602. Image myImage (Image::RGB, 500, 500, true);
  22603. Graphics g (myImage);
  22604. g.setColour (Colours::red);
  22605. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22606. @endcode
  22607. Other useful ways to create an image are with the ImageCache class, or the
  22608. ImageFileFormat, which provides a way to load common image files.
  22609. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22610. */
  22611. class JUCE_API Image
  22612. {
  22613. public:
  22614. /**
  22615. */
  22616. enum PixelFormat
  22617. {
  22618. UnknownFormat,
  22619. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22620. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22621. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22622. };
  22623. /**
  22624. */
  22625. enum ImageType
  22626. {
  22627. SoftwareImage = 0,
  22628. NativeImage
  22629. };
  22630. /** Creates a null image. */
  22631. Image();
  22632. /** Creates an image with a specified size and format.
  22633. @param format the number of colour channels in the image
  22634. @param imageWidth the desired width of the image, in pixels - this value must be
  22635. greater than zero (otherwise a width of 1 will be used)
  22636. @param imageHeight the desired width of the image, in pixels - this value must be
  22637. greater than zero (otherwise a height of 1 will be used)
  22638. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22639. or transparent black (if it's ARGB). If false, the image may contain
  22640. junk initially, so you need to make sure you overwrite it thoroughly.
  22641. @param type the type of image - this lets you specify whether you want a purely
  22642. memory-based image, or one that may be managed by the OS if possible.
  22643. */
  22644. Image (PixelFormat format,
  22645. int imageWidth,
  22646. int imageHeight,
  22647. bool clearImage,
  22648. ImageType type = NativeImage);
  22649. /** Creates a shared reference to another image.
  22650. This won't create a duplicate of the image - when Image objects are copied, they simply
  22651. point to the same shared image data. To make sure that an Image object has its own unique,
  22652. unshared internal data, call duplicateIfShared().
  22653. */
  22654. Image (const Image& other);
  22655. /** Makes this image refer to the same underlying image as another object.
  22656. This won't create a duplicate of the image - when Image objects are copied, they simply
  22657. point to the same shared image data. To make sure that an Image object has its own unique,
  22658. unshared internal data, call duplicateIfShared().
  22659. */
  22660. Image& operator= (const Image&);
  22661. /** Destructor. */
  22662. ~Image();
  22663. /** Returns true if the two images are referring to the same internal, shared image. */
  22664. bool operator== (const Image& other) const noexcept { return image == other.image; }
  22665. /** Returns true if the two images are not referring to the same internal, shared image. */
  22666. bool operator!= (const Image& other) const noexcept { return image != other.image; }
  22667. /** Returns true if this image isn't null.
  22668. If you create an Image with the default constructor, it has no size or content, and is null
  22669. until you reassign it to an Image which contains some actual data.
  22670. The isNull() method is the opposite of isValid().
  22671. @see isNull
  22672. */
  22673. inline bool isValid() const noexcept { return image != nullptr; }
  22674. /** Returns true if this image is not valid.
  22675. If you create an Image with the default constructor, it has no size or content, and is null
  22676. until you reassign it to an Image which contains some actual data.
  22677. The isNull() method is the opposite of isValid().
  22678. @see isValid
  22679. */
  22680. inline bool isNull() const noexcept { return image == nullptr; }
  22681. /** A null Image object that can be used when you need to return an invalid image.
  22682. This object is the equivalient to an Image created with the default constructor.
  22683. */
  22684. static const Image null;
  22685. /** Returns the image's width (in pixels). */
  22686. int getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  22687. /** Returns the image's height (in pixels). */
  22688. int getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  22689. /** Returns a rectangle with the same size as this image.
  22690. The rectangle's origin is always (0, 0).
  22691. */
  22692. const Rectangle<int> getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22693. /** Returns the image's pixel format. */
  22694. PixelFormat getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->format; }
  22695. /** True if the image's format is ARGB. */
  22696. bool isARGB() const noexcept { return getFormat() == ARGB; }
  22697. /** True if the image's format is RGB. */
  22698. bool isRGB() const noexcept { return getFormat() == RGB; }
  22699. /** True if the image's format is a single-channel alpha map. */
  22700. bool isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  22701. /** True if the image contains an alpha-channel. */
  22702. bool hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  22703. /** Clears a section of the image with a given colour.
  22704. This won't do any alpha-blending - it just sets all pixels in the image to
  22705. the given colour (which may be non-opaque if the image has an alpha channel).
  22706. */
  22707. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22708. /** Returns a rescaled version of this image.
  22709. A new image is returned which is a copy of this one, rescaled to the given size.
  22710. Note that if the new size is identical to the existing image, this will just return
  22711. a reference to the original image, and won't actually create a duplicate.
  22712. */
  22713. const Image rescaled (int newWidth, int newHeight,
  22714. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22715. /** Returns a version of this image with a different image format.
  22716. A new image is returned which has been converted to the specified format.
  22717. Note that if the new format is no different to the current one, this will just return
  22718. a reference to the original image, and won't actually create a copy.
  22719. */
  22720. const Image convertedToFormat (PixelFormat newFormat) const;
  22721. /** Makes sure that no other Image objects share the same underlying data as this one.
  22722. If no other Image objects refer to the same shared data as this one, this method has no
  22723. effect. But if there are other references to the data, this will create a new copy of
  22724. the data internally.
  22725. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22726. affect any other code that may be sharing the same data.
  22727. @see getReferenceCount
  22728. */
  22729. void duplicateIfShared();
  22730. /** Returns an image which refers to a subsection of this image.
  22731. This will not make a copy of the original - the new image will keep a reference to it, so that
  22732. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22733. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22734. you use operator= to make the original Image object refer to something else, the subsection image
  22735. won't pick up this change, it'll remain pointing at the original.
  22736. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22737. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22738. */
  22739. const Image getClippedImage (const Rectangle<int>& area) const;
  22740. /** Returns the colour of one of the pixels in the image.
  22741. If the co-ordinates given are beyond the image's boundaries, this will
  22742. return Colours::transparentBlack.
  22743. @see setPixelAt, Image::BitmapData::getPixelColour
  22744. */
  22745. const Colour getPixelAt (int x, int y) const;
  22746. /** Sets the colour of one of the image's pixels.
  22747. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22748. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22749. with the given one. The colour's opacity will be ignored if this image doesn't have
  22750. an alpha-channel.
  22751. @see getPixelAt, Image::BitmapData::setPixelColour
  22752. */
  22753. void setPixelAt (int x, int y, const Colour& colour);
  22754. /** Changes the opacity of a pixel.
  22755. This only has an effect if the image has an alpha channel and if the
  22756. given co-ordinates are inside the image's boundary.
  22757. The multiplier must be in the range 0 to 1.0, and the current alpha
  22758. at the given co-ordinates will be multiplied by this value.
  22759. @see setPixelAt
  22760. */
  22761. void multiplyAlphaAt (int x, int y, float multiplier);
  22762. /** Changes the overall opacity of the image.
  22763. This will multiply the alpha value of each pixel in the image by the given
  22764. amount (limiting the resulting alpha values between 0 and 255). This allows
  22765. you to make an image more or less transparent.
  22766. If the image doesn't have an alpha channel, this won't have any effect.
  22767. */
  22768. void multiplyAllAlphas (float amountToMultiplyBy);
  22769. /** Changes all the colours to be shades of grey, based on their current luminosity.
  22770. */
  22771. void desaturate();
  22772. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  22773. You should only use this class as a last resort - messing about with the internals of
  22774. an image is only recommended for people who really know what they're doing!
  22775. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  22776. hanging around while the image is being used elsewhere.
  22777. Depending on the way the image class is implemented, this may create a temporary buffer
  22778. which is copied back to the image when the object is deleted, or it may just get a pointer
  22779. directly into the image's raw data.
  22780. You can use the stride and data values in this class directly, but don't alter them!
  22781. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  22782. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  22783. */
  22784. class BitmapData
  22785. {
  22786. public:
  22787. enum ReadWriteMode
  22788. {
  22789. readOnly,
  22790. writeOnly,
  22791. readWrite
  22792. };
  22793. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  22794. BitmapData (const Image& image, int x, int y, int w, int h);
  22795. BitmapData (const Image& image, ReadWriteMode mode);
  22796. ~BitmapData();
  22797. /** Returns a pointer to the start of a line in the image.
  22798. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  22799. sure it's not out-of-range.
  22800. */
  22801. inline uint8* getLinePointer (int y) const noexcept { return data + y * lineStride; }
  22802. /** Returns a pointer to a pixel in the image.
  22803. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  22804. not out-of-range.
  22805. */
  22806. inline uint8* getPixelPointer (int x, int y) const noexcept { return data + y * lineStride + x * pixelStride; }
  22807. /** Returns the colour of a given pixel.
  22808. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22809. repsonsibility to make sure they're within the image's size.
  22810. */
  22811. const Colour getPixelColour (int x, int y) const noexcept;
  22812. /** Sets the colour of a given pixel.
  22813. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22814. repsonsibility to make sure they're within the image's size.
  22815. */
  22816. void setPixelColour (int x, int y, const Colour& colour) const noexcept;
  22817. uint8* data;
  22818. PixelFormat pixelFormat;
  22819. int lineStride, pixelStride, width, height;
  22820. /** Used internally by custom image types to manage pixel data lifetime. */
  22821. class BitmapDataReleaser
  22822. {
  22823. protected:
  22824. BitmapDataReleaser() {}
  22825. public:
  22826. virtual ~BitmapDataReleaser() {}
  22827. };
  22828. ScopedPointer<BitmapDataReleaser> dataReleaser;
  22829. private:
  22830. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  22831. };
  22832. /** Copies some pixel values to a rectangle of the image.
  22833. The format of the pixel data must match that of the image itself, and the
  22834. rectangle supplied must be within the image's bounds.
  22835. */
  22836. void setPixelData (int destX, int destY, int destW, int destH,
  22837. const uint8* sourcePixelData, int sourceLineStride);
  22838. /** Copies a section of the image to somewhere else within itself. */
  22839. void moveImageSection (int destX, int destY,
  22840. int sourceX, int sourceY,
  22841. int width, int height);
  22842. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  22843. of the image.
  22844. @param result the list that will have the area added to it
  22845. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  22846. above this level will be considered opaque
  22847. */
  22848. void createSolidAreaMask (RectangleList& result,
  22849. float alphaThreshold = 0.5f) const;
  22850. /** Returns a NamedValueSet that is attached to the image and which can be used for
  22851. associating custom values with it.
  22852. If this is a null image, this will return a null pointer.
  22853. */
  22854. NamedValueSet* getProperties() const;
  22855. /** Creates a context suitable for drawing onto this image.
  22856. Don't call this method directly! It's used internally by the Graphics class.
  22857. */
  22858. LowLevelGraphicsContext* createLowLevelContext() const;
  22859. /** Returns the number of Image objects which are currently referring to the same internal
  22860. shared image data.
  22861. @see duplicateIfShared
  22862. */
  22863. int getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getReferenceCount(); }
  22864. /** This is a base class for task-specific types of image.
  22865. Don't use this class directly! It's used internally by the Image class.
  22866. */
  22867. class SharedImage : public ReferenceCountedObject
  22868. {
  22869. public:
  22870. SharedImage (PixelFormat format, int width, int height);
  22871. ~SharedImage();
  22872. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  22873. virtual SharedImage* clone() = 0;
  22874. virtual ImageType getType() const = 0;
  22875. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  22876. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  22877. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  22878. const PixelFormat getPixelFormat() const noexcept { return format; }
  22879. int getWidth() const noexcept { return width; }
  22880. int getHeight() const noexcept { return height; }
  22881. protected:
  22882. friend class Image;
  22883. friend class BitmapData;
  22884. const PixelFormat format;
  22885. const int width, height;
  22886. NamedValueSet userData;
  22887. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  22888. };
  22889. /** @internal */
  22890. SharedImage* getSharedImage() const noexcept { return image; }
  22891. /** @internal */
  22892. explicit Image (SharedImage* instance);
  22893. private:
  22894. friend class SharedImage;
  22895. friend class BitmapData;
  22896. ReferenceCountedObjectPtr<SharedImage> image;
  22897. JUCE_LEAK_DETECTOR (Image);
  22898. };
  22899. #endif // __JUCE_IMAGE_JUCEHEADER__
  22900. /*** End of inlined file: juce_Image.h ***/
  22901. /*** Start of inlined file: juce_RectangleList.h ***/
  22902. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  22903. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  22904. /**
  22905. Maintains a set of rectangles as a complex region.
  22906. This class allows a set of rectangles to be treated as a solid shape, and can
  22907. add and remove rectangular sections of it, and simplify overlapping or
  22908. adjacent rectangles.
  22909. @see Rectangle
  22910. */
  22911. class JUCE_API RectangleList
  22912. {
  22913. public:
  22914. /** Creates an empty RectangleList */
  22915. RectangleList() noexcept;
  22916. /** Creates a copy of another list */
  22917. RectangleList (const RectangleList& other);
  22918. /** Creates a list containing just one rectangle. */
  22919. RectangleList (const Rectangle<int>& rect);
  22920. /** Copies this list from another one. */
  22921. RectangleList& operator= (const RectangleList& other);
  22922. /** Destructor. */
  22923. ~RectangleList();
  22924. /** Returns true if the region is empty. */
  22925. bool isEmpty() const noexcept;
  22926. /** Returns the number of rectangles in the list. */
  22927. int getNumRectangles() const noexcept { return rects.size(); }
  22928. /** Returns one of the rectangles at a particular index.
  22929. @returns the rectangle at the index, or an empty rectangle if the
  22930. index is out-of-range.
  22931. */
  22932. const Rectangle<int> getRectangle (int index) const noexcept;
  22933. /** Removes all rectangles to leave an empty region. */
  22934. void clear();
  22935. /** Merges a new rectangle into the list.
  22936. The rectangle being added will first be clipped to remove any parts of it
  22937. that overlap existing rectangles in the list.
  22938. */
  22939. void add (int x, int y, int width, int height);
  22940. /** Merges a new rectangle into the list.
  22941. The rectangle being added will first be clipped to remove any parts of it
  22942. that overlap existing rectangles in the list, and adjacent rectangles will be
  22943. merged into it.
  22944. */
  22945. void add (const Rectangle<int>& rect);
  22946. /** Dumbly adds a rectangle to the list without checking for overlaps.
  22947. This simply adds the rectangle to the end, it doesn't merge it or remove
  22948. any overlapping bits.
  22949. */
  22950. void addWithoutMerging (const Rectangle<int>& rect);
  22951. /** Merges another rectangle list into this one.
  22952. Any overlaps between the two lists will be clipped, so that the result is
  22953. the union of both lists.
  22954. */
  22955. void add (const RectangleList& other);
  22956. /** Removes a rectangular region from the list.
  22957. Any rectangles in the list which overlap this will be clipped and subdivided
  22958. if necessary.
  22959. */
  22960. void subtract (const Rectangle<int>& rect);
  22961. /** Removes all areas in another RectangleList from this one.
  22962. Any rectangles in the list which overlap this will be clipped and subdivided
  22963. if necessary.
  22964. @returns true if the resulting list is non-empty.
  22965. */
  22966. bool subtract (const RectangleList& otherList);
  22967. /** Removes any areas of the region that lie outside a given rectangle.
  22968. Any rectangles in the list which overlap this will be clipped and subdivided
  22969. if necessary.
  22970. Returns true if the resulting region is not empty, false if it is empty.
  22971. @see getIntersectionWith
  22972. */
  22973. bool clipTo (const Rectangle<int>& rect);
  22974. /** Removes any areas of the region that lie outside a given rectangle list.
  22975. Any rectangles in this object which overlap the specified list will be clipped
  22976. and subdivided if necessary.
  22977. Returns true if the resulting region is not empty, false if it is empty.
  22978. @see getIntersectionWith
  22979. */
  22980. bool clipTo (const RectangleList& other);
  22981. /** Creates a region which is the result of clipping this one to a given rectangle.
  22982. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  22983. resulting region into the list whose reference is passed-in.
  22984. Returns true if the resulting region is not empty, false if it is empty.
  22985. @see clipTo
  22986. */
  22987. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  22988. /** Swaps the contents of this and another list.
  22989. This swaps their internal pointers, so is hugely faster than using copy-by-value
  22990. to swap them.
  22991. */
  22992. void swapWith (RectangleList& otherList) noexcept;
  22993. /** Checks whether the region contains a given point.
  22994. @returns true if the point lies within one of the rectangles in the list
  22995. */
  22996. bool containsPoint (int x, int y) const noexcept;
  22997. /** Checks whether the region contains the whole of a given rectangle.
  22998. @returns true all parts of the rectangle passed in lie within the region
  22999. defined by this object
  23000. @see intersectsRectangle, containsPoint
  23001. */
  23002. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  23003. /** Checks whether the region contains any part of a given rectangle.
  23004. @returns true if any part of the rectangle passed in lies within the region
  23005. defined by this object
  23006. @see containsRectangle
  23007. */
  23008. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const noexcept;
  23009. /** Checks whether this region intersects any part of another one.
  23010. @see intersectsRectangle
  23011. */
  23012. bool intersects (const RectangleList& other) const noexcept;
  23013. /** Returns the smallest rectangle that can enclose the whole of this region. */
  23014. const Rectangle<int> getBounds() const noexcept;
  23015. /** Optimises the list into a minimum number of constituent rectangles.
  23016. This will try to combine any adjacent rectangles into larger ones where
  23017. possible, to simplify lists that might have been fragmented by repeated
  23018. add/subtract calls.
  23019. */
  23020. void consolidate();
  23021. /** Adds an x and y value to all the co-ordinates. */
  23022. void offsetAll (int dx, int dy) noexcept;
  23023. /** Creates a Path object to represent this region. */
  23024. const Path toPath() const;
  23025. /** An iterator for accessing all the rectangles in a RectangleList. */
  23026. class JUCE_API Iterator
  23027. {
  23028. public:
  23029. Iterator (const RectangleList& list) noexcept;
  23030. ~Iterator();
  23031. /** Advances to the next rectangle, and returns true if it's not finished.
  23032. Call this before using getRectangle() to find the rectangle that was returned.
  23033. */
  23034. bool next() noexcept;
  23035. /** Returns the current rectangle. */
  23036. const Rectangle<int>* getRectangle() const noexcept { return current; }
  23037. private:
  23038. const Rectangle<int>* current;
  23039. const RectangleList& owner;
  23040. int index;
  23041. JUCE_DECLARE_NON_COPYABLE (Iterator);
  23042. };
  23043. private:
  23044. friend class Iterator;
  23045. Array <Rectangle<int> > rects;
  23046. JUCE_LEAK_DETECTOR (RectangleList);
  23047. };
  23048. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  23049. /*** End of inlined file: juce_RectangleList.h ***/
  23050. /*** Start of inlined file: juce_BorderSize.h ***/
  23051. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  23052. #define __JUCE_BORDERSIZE_JUCEHEADER__
  23053. /**
  23054. Specifies a set of gaps to be left around the sides of a rectangle.
  23055. This is basically the size of the spaces at the top, bottom, left and right of
  23056. a rectangle. It's used by various component classes to specify borders.
  23057. @see Rectangle
  23058. */
  23059. template <typename ValueType>
  23060. class BorderSize
  23061. {
  23062. public:
  23063. /** Creates a null border.
  23064. All sizes are left as 0.
  23065. */
  23066. BorderSize() noexcept
  23067. : top(), left(), bottom(), right()
  23068. {
  23069. }
  23070. /** Creates a copy of another border. */
  23071. BorderSize (const BorderSize& other) noexcept
  23072. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  23073. {
  23074. }
  23075. /** Creates a border with the given gaps. */
  23076. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) noexcept
  23077. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  23078. {
  23079. }
  23080. /** Creates a border with the given gap on all sides. */
  23081. explicit BorderSize (ValueType allGaps) noexcept
  23082. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  23083. {
  23084. }
  23085. /** Returns the gap that should be left at the top of the region. */
  23086. ValueType getTop() const noexcept { return top; }
  23087. /** Returns the gap that should be left at the top of the region. */
  23088. ValueType getLeft() const noexcept { return left; }
  23089. /** Returns the gap that should be left at the top of the region. */
  23090. ValueType getBottom() const noexcept { return bottom; }
  23091. /** Returns the gap that should be left at the top of the region. */
  23092. ValueType getRight() const noexcept { return right; }
  23093. /** Returns the sum of the top and bottom gaps. */
  23094. ValueType getTopAndBottom() const noexcept { return top + bottom; }
  23095. /** Returns the sum of the left and right gaps. */
  23096. ValueType getLeftAndRight() const noexcept { return left + right; }
  23097. /** Returns true if this border has no thickness along any edge. */
  23098. bool isEmpty() const noexcept { return left + right + top + bottom == ValueType(); }
  23099. /** Changes the top gap. */
  23100. void setTop (ValueType newTopGap) noexcept { top = newTopGap; }
  23101. /** Changes the left gap. */
  23102. void setLeft (ValueType newLeftGap) noexcept { left = newLeftGap; }
  23103. /** Changes the bottom gap. */
  23104. void setBottom (ValueType newBottomGap) noexcept { bottom = newBottomGap; }
  23105. /** Changes the right gap. */
  23106. void setRight (ValueType newRightGap) noexcept { right = newRightGap; }
  23107. /** Returns a rectangle with these borders removed from it. */
  23108. const Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const noexcept
  23109. {
  23110. return Rectangle<ValueType> (original.getX() + left,
  23111. original.getY() + top,
  23112. original.getWidth() - (left + right),
  23113. original.getHeight() - (top + bottom));
  23114. }
  23115. /** Removes this border from a given rectangle. */
  23116. void subtractFrom (Rectangle<ValueType>& rectangle) const noexcept
  23117. {
  23118. rectangle = subtractedFrom (rectangle);
  23119. }
  23120. /** Returns a rectangle with these borders added around it. */
  23121. const Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const noexcept
  23122. {
  23123. return Rectangle<ValueType> (original.getX() - left,
  23124. original.getY() - top,
  23125. original.getWidth() + (left + right),
  23126. original.getHeight() + (top + bottom));
  23127. }
  23128. /** Adds this border around a given rectangle. */
  23129. void addTo (Rectangle<ValueType>& rectangle) const noexcept
  23130. {
  23131. rectangle = addedTo (rectangle);
  23132. }
  23133. bool operator== (const BorderSize& other) const noexcept
  23134. {
  23135. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  23136. }
  23137. bool operator!= (const BorderSize& other) const noexcept
  23138. {
  23139. return ! operator== (other);
  23140. }
  23141. private:
  23142. ValueType top, left, bottom, right;
  23143. JUCE_LEAK_DETECTOR (BorderSize);
  23144. };
  23145. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  23146. /*** End of inlined file: juce_BorderSize.h ***/
  23147. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  23148. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23149. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23150. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  23151. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23152. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23153. /**
  23154. Classes derived from this will be automatically deleted when the application exits.
  23155. After JUCEApplication::shutdown() has been called, any objects derived from
  23156. DeletedAtShutdown which are still in existence will be deleted in the reverse
  23157. order to that in which they were created.
  23158. So if you've got a singleton and don't want to have to explicitly delete it, just
  23159. inherit from this and it'll be taken care of.
  23160. */
  23161. class JUCE_API DeletedAtShutdown
  23162. {
  23163. protected:
  23164. /** Creates a DeletedAtShutdown object. */
  23165. DeletedAtShutdown();
  23166. /** Destructor.
  23167. It's ok to delete these objects explicitly - it's only the ones left
  23168. dangling at the end that will be deleted automatically.
  23169. */
  23170. virtual ~DeletedAtShutdown();
  23171. public:
  23172. /** Deletes all extant objects.
  23173. This shouldn't be used by applications, as it's called automatically
  23174. in the shutdown code of the JUCEApplication class.
  23175. */
  23176. static void deleteAll();
  23177. private:
  23178. static Array <DeletedAtShutdown*>& getObjects();
  23179. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  23180. };
  23181. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23182. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  23183. /**
  23184. Manages the system's stack of modal components.
  23185. Normally you'll just use the Component methods to invoke modal states in components,
  23186. and won't have to deal with this class directly, but this is the singleton object that's
  23187. used internally to manage the stack.
  23188. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  23189. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  23190. */
  23191. class JUCE_API ModalComponentManager : public AsyncUpdater,
  23192. public DeletedAtShutdown
  23193. {
  23194. public:
  23195. /** Receives callbacks when a modal component is dismissed.
  23196. You can register a callback using Component::enterModalState() or
  23197. ModalComponentManager::attachCallback().
  23198. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  23199. @see ModalCallbackFunction
  23200. */
  23201. class Callback
  23202. {
  23203. public:
  23204. /** */
  23205. Callback() {}
  23206. /** Destructor. */
  23207. virtual ~Callback() {}
  23208. /** Called to indicate that a modal component has been dismissed.
  23209. You can register a callback using Component::enterModalState() or
  23210. ModalComponentManager::attachCallback().
  23211. The returnValue parameter is the value that was passed to Component::exitModalState()
  23212. when the component was dismissed.
  23213. The callback object will be deleted shortly after this method is called.
  23214. */
  23215. virtual void modalStateFinished (int returnValue) = 0;
  23216. };
  23217. /** Returns the number of components currently being shown modally.
  23218. @see getModalComponent
  23219. */
  23220. int getNumModalComponents() const;
  23221. /** Returns one of the components being shown modally.
  23222. An index of 0 is the most recently-shown, topmost component.
  23223. */
  23224. Component* getModalComponent (int index) const;
  23225. /** Returns true if the specified component is in a modal state. */
  23226. bool isModal (Component* component) const;
  23227. /** Returns true if the specified component is currently the topmost modal component. */
  23228. bool isFrontModalComponent (Component* component) const;
  23229. /** Adds a new callback that will be called when the specified modal component is dismissed.
  23230. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  23231. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  23232. called.
  23233. Each component can have any number of callbacks associated with it, and this one is added
  23234. to that list.
  23235. The object that is passed in will be deleted by the manager when it's no longer needed. If
  23236. the given component is not currently modal, the callback object is deleted immediately and
  23237. no action is taken.
  23238. */
  23239. void attachCallback (Component* component, Callback* callback);
  23240. /** Brings any modal components to the front. */
  23241. void bringModalComponentsToFront (bool topOneShouldGrabFocus = true);
  23242. #if JUCE_MODAL_LOOPS_PERMITTED
  23243. /** Runs the event loop until the currently topmost modal component is dismissed, and
  23244. returns the exit code for that component.
  23245. */
  23246. int runEventLoopForCurrentComponent();
  23247. #endif
  23248. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  23249. protected:
  23250. /** Creates a ModalComponentManager.
  23251. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  23252. */
  23253. ModalComponentManager();
  23254. /** Destructor. */
  23255. ~ModalComponentManager();
  23256. /** @internal */
  23257. void handleAsyncUpdate();
  23258. private:
  23259. class ModalItem;
  23260. class ReturnValueRetriever;
  23261. friend class Component;
  23262. friend class OwnedArray <ModalItem>;
  23263. OwnedArray <ModalItem> stack;
  23264. void startModal (Component* component);
  23265. void endModal (Component* component, int returnValue);
  23266. void endModal (Component* component);
  23267. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  23268. };
  23269. /**
  23270. This class provides some handy utility methods for creating ModalComponentManager::Callback
  23271. objects that will invoke a static function with some parameters when a modal component is dismissed.
  23272. */
  23273. class ModalCallbackFunction
  23274. {
  23275. public:
  23276. /** This is a utility function to create a ModalComponentManager::Callback that will
  23277. call a static function with a parameter.
  23278. The function that you supply must take two parameters - the first being an int, which is
  23279. the result code that was used when the modal component was dismissed, and the second
  23280. can be a custom type. Note that this custom value will be copied and stored, so it must
  23281. be a primitive type or a class that provides copy-by-value semantics.
  23282. E.g. @code
  23283. static void myCallbackFunction (int modalResult, double customValue)
  23284. {
  23285. if (modalResult == 1)
  23286. doSomethingWith (customValue);
  23287. }
  23288. Component* someKindOfComp;
  23289. ...
  23290. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  23291. @endcode
  23292. @see ModalComponentManager::Callback
  23293. */
  23294. template <typename ParamType>
  23295. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  23296. ParamType parameterValue)
  23297. {
  23298. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  23299. }
  23300. /** This is a utility function to create a ModalComponentManager::Callback that will
  23301. call a static function with two custom parameters.
  23302. The function that you supply must take three parameters - the first being an int, which is
  23303. the result code that was used when the modal component was dismissed, and the next two are
  23304. your custom types. Note that these custom values will be copied and stored, so they must
  23305. be primitive types or classes that provide copy-by-value semantics.
  23306. E.g. @code
  23307. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  23308. {
  23309. if (modalResult == 1)
  23310. doSomethingWith (customValue1, customValue2);
  23311. }
  23312. Component* someKindOfComp;
  23313. ...
  23314. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  23315. @endcode
  23316. @see ModalComponentManager::Callback
  23317. */
  23318. template <typename ParamType1, typename ParamType2>
  23319. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  23320. ParamType1 parameterValue1,
  23321. ParamType2 parameterValue2)
  23322. {
  23323. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  23324. }
  23325. /** This is a utility function to create a ModalComponentManager::Callback that will
  23326. call a static function with a component.
  23327. The function that you supply must take two parameters - the first being an int, which is
  23328. the result code that was used when the modal component was dismissed, and the second
  23329. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  23330. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  23331. E.g. @code
  23332. static void myCallbackFunction (int modalResult, Slider* mySlider)
  23333. {
  23334. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23335. mySlider->setValue (0.0);
  23336. }
  23337. Component* someKindOfComp;
  23338. Slider* mySlider;
  23339. ...
  23340. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  23341. @endcode
  23342. @see ModalComponentManager::Callback
  23343. */
  23344. template <class ComponentType>
  23345. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  23346. ComponentType* component)
  23347. {
  23348. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  23349. }
  23350. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  23351. The function that you supply must take three parameters - the first being an int, which is
  23352. the result code that was used when the modal component was dismissed, the second being a Component
  23353. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  23354. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  23355. invoked, the pointer that is passed into the function will be null.
  23356. E.g. @code
  23357. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  23358. {
  23359. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23360. mySlider->setName (customParam);
  23361. }
  23362. Component* someKindOfComp;
  23363. Slider* mySlider;
  23364. ...
  23365. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  23366. @endcode
  23367. @see ModalComponentManager::Callback
  23368. */
  23369. template <class ComponentType, typename ParamType>
  23370. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  23371. ComponentType* component,
  23372. ParamType param)
  23373. {
  23374. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  23375. }
  23376. private:
  23377. template <typename ParamType>
  23378. class FunctionCaller1 : public ModalComponentManager::Callback
  23379. {
  23380. public:
  23381. typedef void (*FunctionType) (int, ParamType);
  23382. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  23383. : function (function_), param (param_) {}
  23384. void modalStateFinished (int returnValue) { function (returnValue, param); }
  23385. private:
  23386. const FunctionType function;
  23387. ParamType param;
  23388. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  23389. };
  23390. template <typename ParamType1, typename ParamType2>
  23391. class FunctionCaller2 : public ModalComponentManager::Callback
  23392. {
  23393. public:
  23394. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  23395. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  23396. : function (function_), param1 (param1_), param2 (param2_) {}
  23397. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  23398. private:
  23399. const FunctionType function;
  23400. ParamType1 param1;
  23401. ParamType2 param2;
  23402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  23403. };
  23404. template <typename ComponentType>
  23405. class ComponentCaller1 : public ModalComponentManager::Callback
  23406. {
  23407. public:
  23408. typedef void (*FunctionType) (int, ComponentType*);
  23409. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  23410. : function (function_), comp (comp_) {}
  23411. void modalStateFinished (int returnValue)
  23412. {
  23413. function (returnValue, static_cast <ComponentType*> (comp.get()));
  23414. }
  23415. private:
  23416. const FunctionType function;
  23417. WeakReference<Component> comp;
  23418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  23419. };
  23420. template <typename ComponentType, typename ParamType1>
  23421. class ComponentCaller2 : public ModalComponentManager::Callback
  23422. {
  23423. public:
  23424. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  23425. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  23426. : function (function_), comp (comp_), param1 (param1_) {}
  23427. void modalStateFinished (int returnValue)
  23428. {
  23429. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  23430. }
  23431. private:
  23432. const FunctionType function;
  23433. WeakReference<Component> comp;
  23434. ParamType1 param1;
  23435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  23436. };
  23437. ModalCallbackFunction();
  23438. ~ModalCallbackFunction();
  23439. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  23440. };
  23441. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23442. /*** End of inlined file: juce_ModalComponentManager.h ***/
  23443. class LookAndFeel;
  23444. class MouseInputSource;
  23445. class MouseInputSourceInternal;
  23446. class ComponentPeer;
  23447. class MarkerList;
  23448. class RelativeRectangle;
  23449. /**
  23450. The base class for all JUCE user-interface objects.
  23451. */
  23452. class JUCE_API Component : public MouseListener
  23453. {
  23454. public:
  23455. /** Creates a component.
  23456. To get it to actually appear, you'll also need to:
  23457. - Either add it to a parent component or use the addToDesktop() method to
  23458. make it a desktop window
  23459. - Set its size and position to something sensible
  23460. - Use setVisible() to make it visible
  23461. And for it to serve any useful purpose, you'll need to write a
  23462. subclass of Component or use one of the other types of component from
  23463. the library.
  23464. */
  23465. Component();
  23466. /** Destructor.
  23467. Note that when a component is deleted, any child components it contains are NOT
  23468. automatically deleted. It's your responsibilty to manage their lifespan - you
  23469. may want to use helper methods like deleteAllChildren(), or less haphazard
  23470. approaches like using ScopedPointers or normal object aggregation to manage them.
  23471. If the component being deleted is currently the child of another one, then during
  23472. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  23473. callback. Any ComponentListener objects that have registered with it will also have their
  23474. ComponentListener::componentBeingDeleted() methods called.
  23475. */
  23476. virtual ~Component();
  23477. /** Creates a component, setting its name at the same time.
  23478. @see getName, setName
  23479. */
  23480. explicit Component (const String& componentName);
  23481. /** Returns the name of this component.
  23482. @see setName
  23483. */
  23484. const String& getName() const noexcept { return componentName; }
  23485. /** Sets the name of this component.
  23486. When the name changes, all registered ComponentListeners will receive a
  23487. ComponentListener::componentNameChanged() callback.
  23488. @see getName
  23489. */
  23490. virtual void setName (const String& newName);
  23491. /** Returns the ID string that was set by setComponentID().
  23492. @see setComponentID
  23493. */
  23494. const String& getComponentID() const noexcept { return componentID; }
  23495. /** Sets the component's ID string.
  23496. You can retrieve the ID using getComponentID().
  23497. @see getComponentID
  23498. */
  23499. void setComponentID (const String& newID);
  23500. /** Makes the component visible or invisible.
  23501. This method will show or hide the component.
  23502. Note that components default to being non-visible when first created.
  23503. Also note that visible components won't be seen unless all their parent components
  23504. are also visible.
  23505. This method will call visibilityChanged() and also componentVisibilityChanged()
  23506. for any component listeners that are interested in this component.
  23507. @param shouldBeVisible whether to show or hide the component
  23508. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  23509. */
  23510. virtual void setVisible (bool shouldBeVisible);
  23511. /** Tests whether the component is visible or not.
  23512. this doesn't necessarily tell you whether this comp is actually on the screen
  23513. because this depends on whether all the parent components are also visible - use
  23514. isShowing() to find this out.
  23515. @see isShowing, setVisible
  23516. */
  23517. bool isVisible() const noexcept { return flags.visibleFlag; }
  23518. /** Called when this component's visiblility changes.
  23519. @see setVisible, isVisible
  23520. */
  23521. virtual void visibilityChanged();
  23522. /** Tests whether this component and all its parents are visible.
  23523. @returns true only if this component and all its parents are visible.
  23524. @see isVisible
  23525. */
  23526. bool isShowing() const;
  23527. /** Makes this component appear as a window on the desktop.
  23528. Note that before calling this, you should make sure that the component's opacity is
  23529. set correctly using setOpaque(). If the component is non-opaque, the windowing
  23530. system will try to create a special transparent window for it, which will generally take
  23531. a lot more CPU to operate (and might not even be possible on some platforms).
  23532. If the component is inside a parent component at the time this method is called, it
  23533. will be first be removed from that parent. Likewise if a component on the desktop
  23534. is subsequently added to another component, it'll be removed from the desktop.
  23535. @param windowStyleFlags a combination of the flags specified in the
  23536. ComponentPeer::StyleFlags enum, which define the
  23537. window's characteristics.
  23538. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  23539. in which the juce component should place itself. On Windows,
  23540. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  23541. supported on all platforms, and best left as 0 unless you know
  23542. what you're doing
  23543. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23544. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23545. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23546. */
  23547. virtual void addToDesktop (int windowStyleFlags,
  23548. void* nativeWindowToAttachTo = nullptr);
  23549. /** If the component is currently showing on the desktop, this will hide it.
  23550. You can also use setVisible() to hide a desktop window temporarily, but
  23551. removeFromDesktop() will free any system resources that are being used up.
  23552. @see addToDesktop, isOnDesktop
  23553. */
  23554. void removeFromDesktop();
  23555. /** Returns true if this component is currently showing on the desktop.
  23556. @see addToDesktop, removeFromDesktop
  23557. */
  23558. bool isOnDesktop() const noexcept;
  23559. /** Returns the heavyweight window that contains this component.
  23560. If this component is itself on the desktop, this will return the window
  23561. object that it is using. Otherwise, it will return the window of
  23562. its top-level parent component.
  23563. This may return 0 if there isn't a desktop component.
  23564. @see addToDesktop, isOnDesktop
  23565. */
  23566. ComponentPeer* getPeer() const;
  23567. /** For components on the desktop, this is called if the system wants to close the window.
  23568. This is a signal that either the user or the system wants the window to close. The
  23569. default implementation of this method will trigger an assertion to warn you that your
  23570. component should do something about it, but you can override this to ignore the event
  23571. if you want.
  23572. */
  23573. virtual void userTriedToCloseWindow();
  23574. /** Called for a desktop component which has just been minimised or un-minimised.
  23575. This will only be called for components on the desktop.
  23576. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23577. */
  23578. virtual void minimisationStateChanged (bool isNowMinimised);
  23579. /** Brings the component to the front of its siblings.
  23580. If some of the component's siblings have had their 'always-on-top' flag set,
  23581. then they will still be kept in front of this one (unless of course this
  23582. one is also 'always-on-top').
  23583. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23584. to the component (see grabKeyboardFocus() for more details)
  23585. @see toBack, toBehind, setAlwaysOnTop
  23586. */
  23587. void toFront (bool shouldAlsoGainFocus);
  23588. /** Changes this component's z-order to be at the back of all its siblings.
  23589. If the component is set to be 'always-on-top', it will only be moved to the
  23590. back of the other other 'always-on-top' components.
  23591. @see toFront, toBehind, setAlwaysOnTop
  23592. */
  23593. void toBack();
  23594. /** Changes this component's z-order so that it's just behind another component.
  23595. @see toFront, toBack
  23596. */
  23597. void toBehind (Component* other);
  23598. /** Sets whether the component should always be kept at the front of its siblings.
  23599. @see isAlwaysOnTop
  23600. */
  23601. void setAlwaysOnTop (bool shouldStayOnTop);
  23602. /** Returns true if this component is set to always stay in front of its siblings.
  23603. @see setAlwaysOnTop
  23604. */
  23605. bool isAlwaysOnTop() const noexcept;
  23606. /** Returns the x coordinate of the component's left edge.
  23607. This is a distance in pixels from the left edge of the component's parent.
  23608. Note that if you've used setTransform() to apply a transform, then the component's
  23609. bounds will no longer be a direct reflection of the position at which it appears within
  23610. its parent, as the transform will be applied to its bounding box.
  23611. */
  23612. inline int getX() const noexcept { return bounds.getX(); }
  23613. /** Returns the y coordinate of the top of this component.
  23614. This is a distance in pixels from the top edge of the component's parent.
  23615. Note that if you've used setTransform() to apply a transform, then the component's
  23616. bounds will no longer be a direct reflection of the position at which it appears within
  23617. its parent, as the transform will be applied to its bounding box.
  23618. */
  23619. inline int getY() const noexcept { return bounds.getY(); }
  23620. /** Returns the component's width in pixels. */
  23621. inline int getWidth() const noexcept { return bounds.getWidth(); }
  23622. /** Returns the component's height in pixels. */
  23623. inline int getHeight() const noexcept { return bounds.getHeight(); }
  23624. /** Returns the x coordinate of the component's right-hand edge.
  23625. This is a distance in pixels from the left edge of the component's parent.
  23626. Note that if you've used setTransform() to apply a transform, then the component's
  23627. bounds will no longer be a direct reflection of the position at which it appears within
  23628. its parent, as the transform will be applied to its bounding box.
  23629. */
  23630. int getRight() const noexcept { return bounds.getRight(); }
  23631. /** Returns the component's top-left position as a Point. */
  23632. const Point<int> getPosition() const noexcept { return bounds.getPosition(); }
  23633. /** Returns the y coordinate of the bottom edge of this component.
  23634. This is a distance in pixels from the top edge of the component's parent.
  23635. Note that if you've used setTransform() to apply a transform, then the component's
  23636. bounds will no longer be a direct reflection of the position at which it appears within
  23637. its parent, as the transform will be applied to its bounding box.
  23638. */
  23639. int getBottom() const noexcept { return bounds.getBottom(); }
  23640. /** Returns this component's bounding box.
  23641. The rectangle returned is relative to the top-left of the component's parent.
  23642. Note that if you've used setTransform() to apply a transform, then the component's
  23643. bounds will no longer be a direct reflection of the position at which it appears within
  23644. its parent, as the transform will be applied to its bounding box.
  23645. */
  23646. const Rectangle<int>& getBounds() const noexcept { return bounds; }
  23647. /** Returns the component's bounds, relative to its own origin.
  23648. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23649. return a rectangle with position (0, 0), and the same size as this component.
  23650. */
  23651. const Rectangle<int> getLocalBounds() const noexcept;
  23652. /** Returns the area of this component's parent which this component covers.
  23653. The returned area is relative to the parent's coordinate space.
  23654. If the component has an affine transform specified, then the resulting area will be
  23655. the smallest rectangle that fully covers the component's transformed bounding box.
  23656. If this component has no parent, the return value will simply be the same as getBounds().
  23657. */
  23658. const Rectangle<int> getBoundsInParent() const noexcept;
  23659. /** Returns the region of this component that's not obscured by other, opaque components.
  23660. The RectangleList that is returned represents the area of this component
  23661. which isn't covered by opaque child components.
  23662. If includeSiblings is true, it will also take into account any siblings
  23663. that may be overlapping the component.
  23664. */
  23665. void getVisibleArea (RectangleList& result,
  23666. bool includeSiblings) const;
  23667. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23668. @see getX, localPointToGlobal
  23669. */
  23670. int getScreenX() const;
  23671. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23672. @see getY, localPointToGlobal
  23673. */
  23674. int getScreenY() const;
  23675. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23676. @see getScreenBounds
  23677. */
  23678. const Point<int> getScreenPosition() const;
  23679. /** Returns the bounds of this component, relative to the screen's top-left.
  23680. @see getScreenPosition
  23681. */
  23682. const Rectangle<int> getScreenBounds() const;
  23683. /** Converts a point to be relative to this component's coordinate space.
  23684. This takes a point relative to a different component, and returns its position relative to this
  23685. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23686. screen coordinate.
  23687. */
  23688. const Point<int> getLocalPoint (const Component* sourceComponent,
  23689. const Point<int>& pointRelativeToSourceComponent) const;
  23690. /** Converts a rectangle to be relative to this component's coordinate space.
  23691. This takes a rectangle that is relative to a different component, and returns its position relative
  23692. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23693. a screen coordinate.
  23694. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23695. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23696. the smallest rectangle that fully contains the transformed area.
  23697. */
  23698. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  23699. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23700. /** Converts a point relative to this component's top-left into a screen coordinate.
  23701. @see getLocalPoint, localAreaToGlobal
  23702. */
  23703. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23704. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23705. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23706. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23707. the smallest rectangle that fully contains the transformed area.
  23708. @see getLocalPoint, localPointToGlobal
  23709. */
  23710. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23711. /** Moves the component to a new position.
  23712. Changes the component's top-left position (without changing its size).
  23713. The position is relative to the top-left of the component's parent.
  23714. If the component actually moves, this method will make a synchronous call to moved().
  23715. Note that if you've used setTransform() to apply a transform, then the component's
  23716. bounds will no longer be a direct reflection of the position at which it appears within
  23717. its parent, as the transform will be applied to whatever bounds you set for it.
  23718. @see setBounds, ComponentListener::componentMovedOrResized
  23719. */
  23720. void setTopLeftPosition (int x, int y);
  23721. /** Moves the component to a new position.
  23722. Changes the position of the component's top-right corner (keeping it the same size).
  23723. The position is relative to the top-left of the component's parent.
  23724. If the component actually moves, this method will make a synchronous call to moved().
  23725. Note that if you've used setTransform() to apply a transform, then the component's
  23726. bounds will no longer be a direct reflection of the position at which it appears within
  23727. its parent, as the transform will be applied to whatever bounds you set for it.
  23728. */
  23729. void setTopRightPosition (int x, int y);
  23730. /** Changes the size of the component.
  23731. A synchronous call to resized() will be occur if the size actually changes.
  23732. Note that if you've used setTransform() to apply a transform, then the component's
  23733. bounds will no longer be a direct reflection of the position at which it appears within
  23734. its parent, as the transform will be applied to whatever bounds you set for it.
  23735. */
  23736. void setSize (int newWidth, int newHeight);
  23737. /** Changes the component's position and size.
  23738. The coordinates are relative to the top-left of the component's parent, or relative
  23739. to the origin of the screen is the component is on the desktop.
  23740. If this method changes the component's top-left position, it will make a synchronous
  23741. call to moved(). If it changes the size, it will also make a call to resized().
  23742. Note that if you've used setTransform() to apply a transform, then the component's
  23743. bounds will no longer be a direct reflection of the position at which it appears within
  23744. its parent, as the transform will be applied to whatever bounds you set for it.
  23745. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23746. */
  23747. void setBounds (int x, int y, int width, int height);
  23748. /** Changes the component's position and size.
  23749. The coordinates are relative to the top-left of the component's parent, or relative
  23750. to the origin of the screen is the component is on the desktop.
  23751. If this method changes the component's top-left position, it will make a synchronous
  23752. call to moved(). If it changes the size, it will also make a call to resized().
  23753. Note that if you've used setTransform() to apply a transform, then the component's
  23754. bounds will no longer be a direct reflection of the position at which it appears within
  23755. its parent, as the transform will be applied to whatever bounds you set for it.
  23756. @see setBounds
  23757. */
  23758. void setBounds (const Rectangle<int>& newBounds);
  23759. /** Changes the component's position and size.
  23760. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23761. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23762. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23763. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  23764. for more details.
  23765. When using relative expressions, the following symbols are available:
  23766. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  23767. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  23768. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  23769. the identifier of one of this component's siblings. A component's identifier is set with
  23770. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  23771. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  23772. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  23773. any other component, these values are relative to their component's parent, so "parent.right" won't be
  23774. very useful for positioning a component because it refers to a position with the parent's parent.. but
  23775. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  23776. component which remains 1 pixel away from its parent's bottom-right, you could use
  23777. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  23778. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  23779. used, the parent component must implement its Component::getMarkers() method, and return at least one
  23780. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  23781. marker called "foobar", you'd set it to "foobar + 10".
  23782. See the Expression class for details about the operators that are supported, but for example
  23783. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  23784. you could express it as:
  23785. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  23786. @endcode
  23787. ..or an alternative way to achieve the same thing:
  23788. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  23789. @endcode
  23790. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  23791. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  23792. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  23793. @endcode
  23794. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  23795. be thrown!
  23796. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  23797. */
  23798. void setBounds (const RelativeRectangle& newBounds);
  23799. /** Sets the component's bounds with an expression.
  23800. The string is parsed as a RelativeRectangle expression - see the notes for
  23801. Component::setBounds (const RelativeRectangle&) for more information. This method is
  23802. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  23803. */
  23804. void setBounds (const String& newBoundsExpression);
  23805. /** Changes the component's position and size in terms of fractions of its parent's size.
  23806. The values are factors of the parent's size, so for example
  23807. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  23808. width and height of the parent, with its top-left position 20% of
  23809. the way across and down the parent.
  23810. @see setBounds
  23811. */
  23812. void setBoundsRelative (float proportionalX, float proportionalY,
  23813. float proportionalWidth, float proportionalHeight);
  23814. /** Changes the component's position and size based on the amount of space to leave around it.
  23815. This will position the component within its parent, leaving the specified number of
  23816. pixels around each edge.
  23817. @see setBounds
  23818. */
  23819. void setBoundsInset (const BorderSize<int>& borders);
  23820. /** Positions the component within a given rectangle, keeping its proportions
  23821. unchanged.
  23822. If onlyReduceInSize is false, the component will be resized to fill as much of the
  23823. rectangle as possible without changing its aspect ratio (the component's
  23824. current size is used to determine its aspect ratio, so a zero-size component
  23825. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  23826. too big to fit inside the rectangle.
  23827. It will then be positioned within the rectangle according to the justification flags
  23828. specified.
  23829. @see setBounds
  23830. */
  23831. void setBoundsToFit (int x, int y, int width, int height,
  23832. const Justification& justification,
  23833. bool onlyReduceInSize);
  23834. /** Changes the position of the component's centre.
  23835. Leaves the component's size unchanged, but sets the position of its centre
  23836. relative to its parent's top-left.
  23837. @see setBounds
  23838. */
  23839. void setCentrePosition (int x, int y);
  23840. /** Changes the position of the component's centre.
  23841. Leaves the position unchanged, but positions its centre relative to its
  23842. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  23843. its parent.
  23844. */
  23845. void setCentreRelative (float x, float y);
  23846. /** Changes the component's size and centres it within its parent.
  23847. After changing the size, the component will be moved so that it's
  23848. centred within its parent. If the component is on the desktop (or has no
  23849. parent component), then it'll be centred within the main monitor area.
  23850. */
  23851. void centreWithSize (int width, int height);
  23852. /** Sets a transform matrix to be applied to this component.
  23853. If you set a transform for a component, the component's position will be warped by it, relative to
  23854. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  23855. longer reflect the actual area within the parent that the component covers, as the bounds will be
  23856. transformed and the component will probably end up actually appearing somewhere else within its parent.
  23857. When using transforms you need to be extremely careful when converting coordinates between the
  23858. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  23859. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  23860. convert it between different components (but I'm sure you would never have done that anyway...).
  23861. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  23862. put a component on the desktop.
  23863. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  23864. */
  23865. void setTransform (const AffineTransform& transform);
  23866. /** Returns the transform that is currently being applied to this component.
  23867. For more details about transforms, see setTransform().
  23868. @see setTransform
  23869. */
  23870. const AffineTransform getTransform() const;
  23871. /** Returns true if a non-identity transform is being applied to this component.
  23872. For more details about transforms, see setTransform().
  23873. @see setTransform
  23874. */
  23875. bool isTransformed() const noexcept;
  23876. /** Returns a proportion of the component's width.
  23877. This is a handy equivalent of (getWidth() * proportion).
  23878. */
  23879. int proportionOfWidth (float proportion) const noexcept;
  23880. /** Returns a proportion of the component's height.
  23881. This is a handy equivalent of (getHeight() * proportion).
  23882. */
  23883. int proportionOfHeight (float proportion) const noexcept;
  23884. /** Returns the width of the component's parent.
  23885. If the component has no parent (i.e. if it's on the desktop), this will return
  23886. the width of the screen.
  23887. */
  23888. int getParentWidth() const noexcept;
  23889. /** Returns the height of the component's parent.
  23890. If the component has no parent (i.e. if it's on the desktop), this will return
  23891. the height of the screen.
  23892. */
  23893. int getParentHeight() const noexcept;
  23894. /** Returns the screen coordinates of the monitor that contains this component.
  23895. If there's only one monitor, this will return its size - if there are multiple
  23896. monitors, it will return the area of the monitor that contains the component's
  23897. centre.
  23898. */
  23899. const Rectangle<int> getParentMonitorArea() const;
  23900. /** Returns the number of child components that this component contains.
  23901. @see getChildComponent, getIndexOfChildComponent
  23902. */
  23903. int getNumChildComponents() const noexcept;
  23904. /** Returns one of this component's child components, by it index.
  23905. The component with index 0 is at the back of the z-order, the one at the
  23906. front will have index (getNumChildComponents() - 1).
  23907. If the index is out-of-range, this will return a null pointer.
  23908. @see getNumChildComponents, getIndexOfChildComponent
  23909. */
  23910. Component* getChildComponent (int index) const noexcept;
  23911. /** Returns the index of this component in the list of child components.
  23912. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  23913. values are further towards the front.
  23914. Returns -1 if the component passed-in is not a child of this component.
  23915. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  23916. */
  23917. int getIndexOfChildComponent (const Component* child) const noexcept;
  23918. /** Adds a child component to this one.
  23919. Adding a child component does not mean that the component will own or delete the child - it's
  23920. your responsibility to delete the component. Note that it's safe to delete a component
  23921. without first removing it from its parent - doing so will automatically remove it and
  23922. send out the appropriate notifications before the deletion completes.
  23923. If the child is already a child of this component, then no action will be taken, and its
  23924. z-order will be left unchanged.
  23925. @param child the new component to add. If the component passed-in is already
  23926. the child of another component, it'll first be removed from it current parent.
  23927. @param zOrder The index in the child-list at which this component should be inserted.
  23928. A value of -1 will insert it in front of the others, 0 is the back.
  23929. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  23930. */
  23931. void addChildComponent (Component* child, int zOrder = -1);
  23932. /** Adds a child component to this one, and also makes the child visible if it isn't.
  23933. Quite a useful function, this is just the same as calling setVisible (true) on the child
  23934. and then addChildComponent(). See addChildComponent() for more details.
  23935. */
  23936. void addAndMakeVisible (Component* child, int zOrder = -1);
  23937. /** Removes one of this component's child-components.
  23938. If the child passed-in isn't actually a child of this component (either because
  23939. it's invalid or is the child of a different parent), then no action is taken.
  23940. Note that removing a child will not delete it! But it's ok to delete a component
  23941. without first removing it - doing so will automatically remove it and send out the
  23942. appropriate notifications before the deletion completes.
  23943. @see addChildComponent, ComponentListener::componentChildrenChanged
  23944. */
  23945. void removeChildComponent (Component* childToRemove);
  23946. /** Removes one of this component's child-components by index.
  23947. This will return a pointer to the component that was removed, or null if
  23948. the index was out-of-range.
  23949. Note that removing a child will not delete it! But it's ok to delete a component
  23950. without first removing it - doing so will automatically remove it and send out the
  23951. appropriate notifications before the deletion completes.
  23952. @see addChildComponent, ComponentListener::componentChildrenChanged
  23953. */
  23954. Component* removeChildComponent (int childIndexToRemove);
  23955. /** Removes all this component's children.
  23956. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  23957. */
  23958. void removeAllChildren();
  23959. /** Removes all this component's children, and deletes them.
  23960. @see removeAllChildren
  23961. */
  23962. void deleteAllChildren();
  23963. /** Returns the component which this component is inside.
  23964. If this is the highest-level component or hasn't yet been added to
  23965. a parent, this will return null.
  23966. */
  23967. Component* getParentComponent() const noexcept { return parentComponent; }
  23968. /** Searches the parent components for a component of a specified class.
  23969. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  23970. component that can be dynamically cast to a MyComp, or will return 0 if none
  23971. of the parents are suitable.
  23972. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  23973. */
  23974. template <class TargetClass>
  23975. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = nullptr) const
  23976. {
  23977. (void) dummyParameter;
  23978. Component* p = parentComponent;
  23979. while (p != nullptr)
  23980. {
  23981. TargetClass* target = dynamic_cast <TargetClass*> (p);
  23982. if (target != nullptr)
  23983. return target;
  23984. p = p->parentComponent;
  23985. }
  23986. return nullptr;
  23987. }
  23988. /** Returns the highest-level component which contains this one or its parents.
  23989. This will search upwards in the parent-hierarchy from this component, until it
  23990. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  23991. not yet added to a parent), and will return that.
  23992. */
  23993. Component* getTopLevelComponent() const noexcept;
  23994. /** Checks whether a component is anywhere inside this component or its children.
  23995. This will recursively check through this component's children to see if the
  23996. given component is anywhere inside.
  23997. */
  23998. bool isParentOf (const Component* possibleChild) const noexcept;
  23999. /** Called to indicate that the component's parents have changed.
  24000. When a component is added or removed from its parent, this method will
  24001. be called on all of its children (recursively - so all children of its
  24002. children will also be called as well).
  24003. Subclasses can override this if they need to react to this in some way.
  24004. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  24005. */
  24006. virtual void parentHierarchyChanged();
  24007. /** Subclasses can use this callback to be told when children are added or removed.
  24008. @see parentHierarchyChanged
  24009. */
  24010. virtual void childrenChanged();
  24011. /** Tests whether a given point inside the component.
  24012. Overriding this method allows you to create components which only intercept
  24013. mouse-clicks within a user-defined area.
  24014. This is called to find out whether a particular x, y coordinate is
  24015. considered to be inside the component or not, and is used by methods such
  24016. as contains() and getComponentAt() to work out which component
  24017. the mouse is clicked on.
  24018. Components with custom shapes will probably want to override it to perform
  24019. some more complex hit-testing.
  24020. The default implementation of this method returns either true or false,
  24021. depending on the value that was set by calling setInterceptsMouseClicks() (true
  24022. is the default return value).
  24023. Note that the hit-test region is not related to the opacity with which
  24024. areas of a component are painted.
  24025. Applications should never call hitTest() directly - instead use the
  24026. contains() method, because this will also test for occlusion by the
  24027. component's parent.
  24028. Note that for components on the desktop, this method will be ignored, because it's
  24029. not always possible to implement this behaviour on all platforms.
  24030. @param x the x coordinate to test, relative to the left hand edge of this
  24031. component. This value is guaranteed to be greater than or equal to
  24032. zero, and less than the component's width
  24033. @param y the y coordinate to test, relative to the top edge of this
  24034. component. This value is guaranteed to be greater than or equal to
  24035. zero, and less than the component's height
  24036. @returns true if the click is considered to be inside the component
  24037. @see setInterceptsMouseClicks, contains
  24038. */
  24039. virtual bool hitTest (int x, int y);
  24040. /** Changes the default return value for the hitTest() method.
  24041. Setting this to false is an easy way to make a component pass its mouse-clicks
  24042. through to the components behind it.
  24043. When a component is created, the default setting for this is true.
  24044. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  24045. return false (or true for child components if allowClicksOnChildComponents
  24046. is true)
  24047. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  24048. components can be clicked on as normal but clicks on this component pass
  24049. straight through; if this is false and allowClicksOnThisComponent
  24050. is false, then neither this component nor any child components can
  24051. be clicked on
  24052. @see hitTest, getInterceptsMouseClicks
  24053. */
  24054. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  24055. bool allowClicksOnChildComponents) noexcept;
  24056. /** Retrieves the current state of the mouse-click interception flags.
  24057. On return, the two parameters are set to the state used in the last call to
  24058. setInterceptsMouseClicks().
  24059. @see setInterceptsMouseClicks
  24060. */
  24061. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  24062. bool& allowsClicksOnChildComponents) const noexcept;
  24063. /** Returns true if a given point lies within this component or one of its children.
  24064. Never override this method! Use hitTest to create custom hit regions.
  24065. @param localPoint the coordinate to test, relative to this component's top-left.
  24066. @returns true if the point is within the component's hit-test area, but only if
  24067. that part of the component isn't clipped by its parent component. Note
  24068. that this won't take into account any overlapping sibling components
  24069. which might be in the way - for that, see reallyContains()
  24070. @see hitTest, reallyContains, getComponentAt
  24071. */
  24072. bool contains (const Point<int>& localPoint);
  24073. /** Returns true if a given point lies in this component, taking any overlapping
  24074. siblings into account.
  24075. @param localPoint the coordinate to test, relative to this component's top-left.
  24076. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  24077. this determines whether that is counted as a hit.
  24078. @see contains, getComponentAt
  24079. */
  24080. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  24081. /** Returns the component at a certain point within this one.
  24082. @param x the x coordinate to test, relative to this component's left edge.
  24083. @param y the y coordinate to test, relative to this component's top edge.
  24084. @returns the component that is at this position - which may be 0, this component,
  24085. or one of its children. Note that overlapping siblings that might actually
  24086. be in the way are not taken into account by this method - to account for these,
  24087. instead call getComponentAt on the top-level parent of this component.
  24088. @see hitTest, contains, reallyContains
  24089. */
  24090. Component* getComponentAt (int x, int y);
  24091. /** Returns the component at a certain point within this one.
  24092. @param position the coordinate to test, relative to this component's top-left.
  24093. @returns the component that is at this position - which may be 0, this component,
  24094. or one of its children. Note that overlapping siblings that might actually
  24095. be in the way are not taken into account by this method - to account for these,
  24096. instead call getComponentAt on the top-level parent of this component.
  24097. @see hitTest, contains, reallyContains
  24098. */
  24099. Component* getComponentAt (const Point<int>& position);
  24100. /** Marks the whole component as needing to be redrawn.
  24101. Calling this will not do any repainting immediately, but will mark the component
  24102. as 'dirty'. At some point in the near future the operating system will send a paint
  24103. message, which will redraw all the dirty regions of all components.
  24104. There's no guarantee about how soon after calling repaint() the redraw will actually
  24105. happen, and other queued events may be delivered before a redraw is done.
  24106. If the setBufferedToImage() method has been used to cause this component
  24107. to use a buffer, the repaint() call will invalidate the component's buffer.
  24108. To redraw just a subsection of the component rather than the whole thing,
  24109. use the repaint (int, int, int, int) method.
  24110. @see paint
  24111. */
  24112. void repaint();
  24113. /** Marks a subsection of this component as needing to be redrawn.
  24114. Calling this will not do any repainting immediately, but will mark the given region
  24115. of the component as 'dirty'. At some point in the near future the operating system
  24116. will send a paint message, which will redraw all the dirty regions of all components.
  24117. There's no guarantee about how soon after calling repaint() the redraw will actually
  24118. happen, and other queued events may be delivered before a redraw is done.
  24119. The region that is passed in will be clipped to keep it within the bounds of this
  24120. component.
  24121. @see repaint()
  24122. */
  24123. void repaint (int x, int y, int width, int height);
  24124. /** Marks a subsection of this component as needing to be redrawn.
  24125. Calling this will not do any repainting immediately, but will mark the given region
  24126. of the component as 'dirty'. At some point in the near future the operating system
  24127. will send a paint message, which will redraw all the dirty regions of all components.
  24128. There's no guarantee about how soon after calling repaint() the redraw will actually
  24129. happen, and other queued events may be delivered before a redraw is done.
  24130. The region that is passed in will be clipped to keep it within the bounds of this
  24131. component.
  24132. @see repaint()
  24133. */
  24134. void repaint (const Rectangle<int>& area);
  24135. /** Makes the component use an internal buffer to optimise its redrawing.
  24136. Setting this flag to true will cause the component to allocate an
  24137. internal buffer into which it paints itself, so that when asked to
  24138. redraw itself, it can use this buffer rather than actually calling the
  24139. paint() method.
  24140. The buffer is kept until the repaint() method is called directly on
  24141. this component (or until it is resized), when the image is invalidated
  24142. and then redrawn the next time the component is painted.
  24143. Note that only the drawing that happens within the component's paint()
  24144. method is drawn into the buffer, it's child components are not buffered, and
  24145. nor is the paintOverChildren() method.
  24146. @see repaint, paint, createComponentSnapshot
  24147. */
  24148. void setBufferedToImage (bool shouldBeBuffered);
  24149. /** Generates a snapshot of part of this component.
  24150. This will return a new Image, the size of the rectangle specified,
  24151. containing a snapshot of the specified area of the component and all
  24152. its children.
  24153. The image may or may not have an alpha-channel, depending on whether the
  24154. image is opaque or not.
  24155. If the clipImageToComponentBounds parameter is true and the area is greater than
  24156. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  24157. then parts of the component beyond its bounds can be drawn.
  24158. @see paintEntireComponent
  24159. */
  24160. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  24161. bool clipImageToComponentBounds = true);
  24162. /** Draws this component and all its subcomponents onto the specified graphics
  24163. context.
  24164. You should very rarely have to use this method, it's simply there in case you need
  24165. to draw a component with a custom graphics context for some reason, e.g. for
  24166. creating a snapshot of the component.
  24167. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  24168. on its children in order to render the entire tree.
  24169. The graphics context may be left in an undefined state after this method returns,
  24170. so you may need to reset it if you're going to use it again.
  24171. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  24172. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  24173. an alpha of 1.0 will be used.
  24174. */
  24175. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  24176. /** This allows you to indicate that this component doesn't require its graphics
  24177. context to be clipped when it is being painted.
  24178. Most people will never need to use this setting, but in situations where you have a very large
  24179. number of simple components being rendered, and where they are guaranteed never to do any drawing
  24180. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  24181. the graphics context that gets passed to the component's paint() callback.
  24182. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  24183. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  24184. artifacts. Your component also can't have any child components that may be placed beyond its
  24185. bounds.
  24186. */
  24187. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept;
  24188. /** Adds an effect filter to alter the component's appearance.
  24189. When a component has an effect filter set, then this is applied to the
  24190. results of its paint() method. There are a few preset effects, such as
  24191. a drop-shadow or glow, but they can be user-defined as well.
  24192. The effect that is passed in will not be deleted by the component - the
  24193. caller must take care of deleting it.
  24194. To remove an effect from a component, pass a null pointer in as the parameter.
  24195. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  24196. */
  24197. void setComponentEffect (ImageEffectFilter* newEffect);
  24198. /** Returns the current component effect.
  24199. @see setComponentEffect
  24200. */
  24201. ImageEffectFilter* getComponentEffect() const noexcept { return effect; }
  24202. /** Finds the appropriate look-and-feel to use for this component.
  24203. If the component hasn't had a look-and-feel explicitly set, this will
  24204. return the parent's look-and-feel, or just the default one if there's no
  24205. parent.
  24206. @see setLookAndFeel, lookAndFeelChanged
  24207. */
  24208. LookAndFeel& getLookAndFeel() const noexcept;
  24209. /** Sets the look and feel to use for this component.
  24210. This will also change the look and feel for any child components that haven't
  24211. had their look set explicitly.
  24212. The object passed in will not be deleted by the component, so it's the caller's
  24213. responsibility to manage it. It may be used at any time until this component
  24214. has been deleted.
  24215. Calling this method will also invoke the sendLookAndFeelChange() method.
  24216. @see getLookAndFeel, lookAndFeelChanged
  24217. */
  24218. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  24219. /** Called to let the component react to a change in the look-and-feel setting.
  24220. When the look-and-feel is changed for a component, this will be called in
  24221. all its child components, recursively.
  24222. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  24223. an application uses a LookAndFeel class that might have changed internally.
  24224. @see sendLookAndFeelChange, getLookAndFeel
  24225. */
  24226. virtual void lookAndFeelChanged();
  24227. /** Calls the lookAndFeelChanged() method in this component and all its children.
  24228. This will recurse through the children and their children, calling lookAndFeelChanged()
  24229. on them all.
  24230. @see lookAndFeelChanged
  24231. */
  24232. void sendLookAndFeelChange();
  24233. /** Indicates whether any parts of the component might be transparent.
  24234. Components that always paint all of their contents with solid colour and
  24235. thus completely cover any components behind them should use this method
  24236. to tell the repaint system that they are opaque.
  24237. This information is used to optimise drawing, because it means that
  24238. objects underneath opaque windows don't need to be painted.
  24239. By default, components are considered transparent, unless this is used to
  24240. make it otherwise.
  24241. @see isOpaque, getVisibleArea
  24242. */
  24243. void setOpaque (bool shouldBeOpaque);
  24244. /** Returns true if no parts of this component are transparent.
  24245. @returns the value that was set by setOpaque, (the default being false)
  24246. @see setOpaque
  24247. */
  24248. bool isOpaque() const noexcept;
  24249. /** Indicates whether the component should be brought to the front when clicked.
  24250. Setting this flag to true will cause the component to be brought to the front
  24251. when the mouse is clicked somewhere inside it or its child components.
  24252. Note that a top-level desktop window might still be brought to the front by the
  24253. operating system when it's clicked, depending on how the OS works.
  24254. By default this is set to false.
  24255. @see setMouseClickGrabsKeyboardFocus
  24256. */
  24257. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept;
  24258. /** Indicates whether the component should be brought to the front when clicked-on.
  24259. @see setBroughtToFrontOnMouseClick
  24260. */
  24261. bool isBroughtToFrontOnMouseClick() const noexcept;
  24262. // Keyboard focus methods
  24263. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  24264. By default components aren't actually interested in gaining the
  24265. focus, but this method can be used to turn this on.
  24266. See the grabKeyboardFocus() method for details about the way a component
  24267. is chosen to receive the focus.
  24268. @see grabKeyboardFocus, getWantsKeyboardFocus
  24269. */
  24270. void setWantsKeyboardFocus (bool wantsFocus) noexcept;
  24271. /** Returns true if the component is interested in getting keyboard focus.
  24272. This returns the flag set by setWantsKeyboardFocus(). The default
  24273. setting is false.
  24274. @see setWantsKeyboardFocus
  24275. */
  24276. bool getWantsKeyboardFocus() const noexcept;
  24277. /** Chooses whether a click on this component automatically grabs the focus.
  24278. By default this is set to true, but you might want a component which can
  24279. be focused, but where you don't want the user to be able to affect it directly
  24280. by clicking.
  24281. */
  24282. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  24283. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  24284. See setMouseClickGrabsKeyboardFocus() for more info.
  24285. */
  24286. bool getMouseClickGrabsKeyboardFocus() const noexcept;
  24287. /** Tries to give keyboard focus to this component.
  24288. When the user clicks on a component or its grabKeyboardFocus()
  24289. method is called, the following procedure is used to work out which
  24290. component should get it:
  24291. - if the component that was clicked on actually wants focus (as indicated
  24292. by calling getWantsKeyboardFocus), it gets it.
  24293. - if the component itself doesn't want focus, it will try to pass it
  24294. on to whichever of its children is the default component, as determined by
  24295. KeyboardFocusTraverser::getDefaultComponent()
  24296. - if none of its children want focus at all, it will pass it up to its
  24297. parent instead, unless it's a top-level component without a parent,
  24298. in which case it just takes the focus itself.
  24299. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  24300. getCurrentlyFocusedComponent, focusGained, focusLost,
  24301. keyPressed, keyStateChanged
  24302. */
  24303. void grabKeyboardFocus();
  24304. /** Returns true if this component currently has the keyboard focus.
  24305. @param trueIfChildIsFocused if this is true, then the method returns true if
  24306. either this component or any of its children (recursively)
  24307. have the focus. If false, the method only returns true if
  24308. this component has the focus.
  24309. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  24310. focusGained, focusLost
  24311. */
  24312. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  24313. /** Returns the component that currently has the keyboard focus.
  24314. @returns the focused component, or null if nothing is focused.
  24315. */
  24316. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() noexcept;
  24317. /** Tries to move the keyboard focus to one of this component's siblings.
  24318. This will try to move focus to either the next or previous component. (This
  24319. is the method that is used when shifting focus by pressing the tab key).
  24320. Components for which getWantsKeyboardFocus() returns false are not looked at.
  24321. @param moveToNext if true, the focus will move forwards; if false, it will
  24322. move backwards
  24323. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  24324. */
  24325. void moveKeyboardFocusToSibling (bool moveToNext);
  24326. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  24327. which focus should be passed from this component.
  24328. The default implementation of this method will return a default
  24329. KeyboardFocusTraverser if this component is a focus container (as determined
  24330. by the setFocusContainer() method). If the component isn't a focus
  24331. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  24332. If you overrride this to return a custom KeyboardFocusTraverser, then
  24333. this component and all its sub-components will use the new object to
  24334. make their focusing decisions.
  24335. The method should return a new object, which the caller is required to
  24336. delete when no longer needed.
  24337. */
  24338. virtual KeyboardFocusTraverser* createFocusTraverser();
  24339. /** Returns the focus order of this component, if one has been specified.
  24340. By default components don't have a focus order - in that case, this
  24341. will return 0. Lower numbers indicate that the component will be
  24342. earlier in the focus traversal order.
  24343. To change the order, call setExplicitFocusOrder().
  24344. The focus order may be used by the KeyboardFocusTraverser class as part of
  24345. its algorithm for deciding the order in which components should be traversed.
  24346. See the KeyboardFocusTraverser class for more details on this.
  24347. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  24348. */
  24349. int getExplicitFocusOrder() const;
  24350. /** Sets the index used in determining the order in which focusable components
  24351. should be traversed.
  24352. A value of 0 or less is taken to mean that no explicit order is wanted, and
  24353. that traversal should use other factors, like the component's position.
  24354. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  24355. */
  24356. void setExplicitFocusOrder (int newFocusOrderIndex);
  24357. /** Indicates whether this component is a parent for components that can have
  24358. their focus traversed.
  24359. This flag is used by the default implementation of the createFocusTraverser()
  24360. method, which uses the flag to find the first parent component (of the currently
  24361. focused one) which wants to be a focus container.
  24362. So using this method to set the flag to 'true' causes this component to
  24363. act as the top level within which focus is passed around.
  24364. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  24365. */
  24366. void setFocusContainer (bool shouldBeFocusContainer) noexcept;
  24367. /** Returns true if this component has been marked as a focus container.
  24368. See setFocusContainer() for more details.
  24369. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  24370. */
  24371. bool isFocusContainer() const noexcept;
  24372. /** Returns true if the component (and all its parents) are enabled.
  24373. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  24374. what difference this makes to the component depends on the type. E.g. buttons
  24375. and sliders will choose to draw themselves differently, etc.
  24376. Note that if one of this component's parents is disabled, this will always
  24377. return false, even if this component itself is enabled.
  24378. @see setEnabled, enablementChanged
  24379. */
  24380. bool isEnabled() const noexcept;
  24381. /** Enables or disables this component.
  24382. Disabling a component will also cause all of its child components to become
  24383. disabled.
  24384. Similarly, enabling a component which is inside a disabled parent
  24385. component won't make any difference until the parent is re-enabled.
  24386. @see isEnabled, enablementChanged
  24387. */
  24388. void setEnabled (bool shouldBeEnabled);
  24389. /** Callback to indicate that this component has been enabled or disabled.
  24390. This can be triggered by one of the component's parent components
  24391. being enabled or disabled, as well as changes to the component itself.
  24392. The default implementation of this method does nothing; your class may
  24393. wish to repaint itself or something when this happens.
  24394. @see setEnabled, isEnabled
  24395. */
  24396. virtual void enablementChanged();
  24397. /** Changes the transparency of this component.
  24398. When painted, the entire component and all its children will be rendered
  24399. with this as the overall opacity level, where 0 is completely invisible, and
  24400. 1.0 is fully opaque (i.e. normal).
  24401. @see getAlpha
  24402. */
  24403. void setAlpha (float newAlpha);
  24404. /** Returns the component's current transparancy level.
  24405. See setAlpha() for more details.
  24406. */
  24407. float getAlpha() const;
  24408. /** Changes the mouse cursor shape to use when the mouse is over this component.
  24409. Note that the cursor set by this method can be overridden by the getMouseCursor
  24410. method.
  24411. @see MouseCursor
  24412. */
  24413. void setMouseCursor (const MouseCursor& cursorType);
  24414. /** Returns the mouse cursor shape to use when the mouse is over this component.
  24415. The default implementation will return the cursor that was set by setCursor()
  24416. but can be overridden for more specialised purposes, e.g. returning different
  24417. cursors depending on the mouse position.
  24418. @see MouseCursor
  24419. */
  24420. virtual const MouseCursor getMouseCursor();
  24421. /** Forces the current mouse cursor to be updated.
  24422. If you're overriding the getMouseCursor() method to control which cursor is
  24423. displayed, then this will only be checked each time the user moves the mouse. So
  24424. if you want to force the system to check that the cursor being displayed is
  24425. up-to-date (even if the mouse is just sitting there), call this method.
  24426. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  24427. calling this).
  24428. */
  24429. void updateMouseCursor() const;
  24430. /** Components can override this method to draw their content.
  24431. The paint() method gets called when a region of a component needs redrawing,
  24432. either because the component's repaint() method has been called, or because
  24433. something has happened on the screen that means a section of a window needs
  24434. to be redrawn.
  24435. Any child components will draw themselves over whatever this method draws. If
  24436. you need to paint over the top of your child components, you can also implement
  24437. the paintOverChildren() method to do this.
  24438. If you want to cause a component to redraw itself, this is done asynchronously -
  24439. calling the repaint() method marks a region of the component as "dirty", and the
  24440. paint() method will automatically be called sometime later, by the message thread,
  24441. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  24442. you never redraw something synchronously.
  24443. You should never need to call this method directly - to take a snapshot of the
  24444. component you could use createComponentSnapshot() or paintEntireComponent().
  24445. @param g the graphics context that must be used to do the drawing operations.
  24446. @see repaint, paintOverChildren, Graphics
  24447. */
  24448. virtual void paint (Graphics& g);
  24449. /** Components can override this method to draw over the top of their children.
  24450. For most drawing operations, it's better to use the normal paint() method,
  24451. but if you need to overlay something on top of the children, this can be
  24452. used.
  24453. @see paint, Graphics
  24454. */
  24455. virtual void paintOverChildren (Graphics& g);
  24456. /** Called when the mouse moves inside this component.
  24457. If the mouse button isn't pressed and the mouse moves over a component,
  24458. this will be called to let the component react to this.
  24459. A component will always get a mouseEnter callback before a mouseMove.
  24460. @param e details about the position and status of the mouse event
  24461. @see mouseEnter, mouseExit, mouseDrag, contains
  24462. */
  24463. virtual void mouseMove (const MouseEvent& e);
  24464. /** Called when the mouse first enters this component.
  24465. If the mouse button isn't pressed and the mouse moves into a component,
  24466. this will be called to let the component react to this.
  24467. When the mouse button is pressed and held down while being moved in
  24468. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  24469. mouseDrag messages are sent to the component that the mouse was originally
  24470. clicked on, until the button is released.
  24471. If you're writing a component that needs to repaint itself when the mouse
  24472. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24473. method.
  24474. @param e details about the position and status of the mouse event
  24475. @see mouseExit, mouseDrag, mouseMove, contains
  24476. */
  24477. virtual void mouseEnter (const MouseEvent& e);
  24478. /** Called when the mouse moves out of this component.
  24479. This will be called when the mouse moves off the edge of this
  24480. component.
  24481. If the mouse button was pressed, and it was then dragged off the
  24482. edge of the component and released, then this callback will happen
  24483. when the button is released, after the mouseUp callback.
  24484. If you're writing a component that needs to repaint itself when the mouse
  24485. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24486. method.
  24487. @param e details about the position and status of the mouse event
  24488. @see mouseEnter, mouseDrag, mouseMove, contains
  24489. */
  24490. virtual void mouseExit (const MouseEvent& e);
  24491. /** Called when a mouse button is pressed while it's over this component.
  24492. The MouseEvent object passed in contains lots of methods for finding out
  24493. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24494. were held down at the time.
  24495. Once a button is held down, the mouseDrag method will be called when the
  24496. mouse moves, until the button is released.
  24497. @param e details about the position and status of the mouse event
  24498. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  24499. */
  24500. virtual void mouseDown (const MouseEvent& e);
  24501. /** Called when the mouse is moved while a button is held down.
  24502. When a mouse button is pressed inside a component, that component
  24503. receives mouseDrag callbacks each time the mouse moves, even if the
  24504. mouse strays outside the component's bounds.
  24505. If you want to be able to drag things off the edge of a component
  24506. and have the component scroll when you get to the edges, the
  24507. beginDragAutoRepeat() method might be useful.
  24508. @param e details about the position and status of the mouse event
  24509. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  24510. */
  24511. virtual void mouseDrag (const MouseEvent& e);
  24512. /** Called when a mouse button is released.
  24513. A mouseUp callback is sent to the component in which a button was pressed
  24514. even if the mouse is actually over a different component when the
  24515. button is released.
  24516. The MouseEvent object passed in contains lots of methods for finding out
  24517. which buttons were down just before they were released.
  24518. @param e details about the position and status of the mouse event
  24519. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  24520. */
  24521. virtual void mouseUp (const MouseEvent& e);
  24522. /** Called when a mouse button has been double-clicked in this component.
  24523. The MouseEvent object passed in contains lots of methods for finding out
  24524. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24525. were held down at the time.
  24526. For altering the time limit used to detect double-clicks,
  24527. see MouseEvent::setDoubleClickTimeout.
  24528. @param e details about the position and status of the mouse event
  24529. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  24530. MouseEvent::getDoubleClickTimeout
  24531. */
  24532. virtual void mouseDoubleClick (const MouseEvent& e);
  24533. /** Called when the mouse-wheel is moved.
  24534. This callback is sent to the component that the mouse is over when the
  24535. wheel is moved.
  24536. If not overridden, the component will forward this message to its parent, so
  24537. that parent components can collect mouse-wheel messages that happen to
  24538. child components which aren't interested in them.
  24539. @param e details about the position and status of the mouse event
  24540. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  24541. value means the wheel has been pushed to the right, negative means it
  24542. was pushed to the left
  24543. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24544. value means the wheel has been pushed upwards, negative means it
  24545. was pushed downwards
  24546. */
  24547. virtual void mouseWheelMove (const MouseEvent& e,
  24548. float wheelIncrementX,
  24549. float wheelIncrementY);
  24550. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24551. current mouse-drag operation.
  24552. This allows you to make sure that mouseDrag() events are sent continuously, even
  24553. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24554. components when the mouse is near an edge.
  24555. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24556. minimum interval between consecutive mouse drag callbacks. The callbacks
  24557. will continue until the mouse is released, and then the interval will be reset,
  24558. so you need to make sure it's called every time you begin a drag event.
  24559. Passing an interval of 0 or less will cancel the auto-repeat.
  24560. @see mouseDrag, Desktop::beginDragAutoRepeat
  24561. */
  24562. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24563. /** Causes automatic repaints when the mouse enters or exits this component.
  24564. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24565. on the component, it will trigger a repaint.
  24566. This is handy for things like buttons that need to draw themselves differently when
  24567. the mouse moves over them, and it avoids having to override all the different mouse
  24568. callbacks and call repaint().
  24569. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24570. */
  24571. void setRepaintsOnMouseActivity (bool shouldRepaint) noexcept;
  24572. /** Registers a listener to be told when mouse events occur in this component.
  24573. If you need to get informed about mouse events in a component but can't or
  24574. don't want to override its methods, you can attach any number of listeners
  24575. to the component, and these will get told about the events in addition to
  24576. the component's own callbacks being called.
  24577. Note that a MouseListener can also be attached to more than one component.
  24578. @param newListener the listener to register
  24579. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24580. for events that happen to any child component
  24581. within this component, including deeply-nested
  24582. child components. If false, it will only be
  24583. told about events that this component handles.
  24584. @see MouseListener, removeMouseListener
  24585. */
  24586. void addMouseListener (MouseListener* newListener,
  24587. bool wantsEventsForAllNestedChildComponents);
  24588. /** Deregisters a mouse listener.
  24589. @see addMouseListener, MouseListener
  24590. */
  24591. void removeMouseListener (MouseListener* listenerToRemove);
  24592. /** Adds a listener that wants to hear about keypresses that this component receives.
  24593. The listeners that are registered with a component are called by its keyPressed() or
  24594. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24595. If you add an object as a key listener, be careful to remove it when the object
  24596. is deleted, or the component will be left with a dangling pointer.
  24597. @see keyPressed, keyStateChanged, removeKeyListener
  24598. */
  24599. void addKeyListener (KeyListener* newListener);
  24600. /** Removes a previously-registered key listener.
  24601. @see addKeyListener
  24602. */
  24603. void removeKeyListener (KeyListener* listenerToRemove);
  24604. /** Called when a key is pressed.
  24605. When a key is pressed, the component that has the keyboard focus will have this
  24606. method called. Remember that a component will only be given the focus if its
  24607. setWantsKeyboardFocus() method has been used to enable this.
  24608. If your implementation returns true, the event will be consumed and not passed
  24609. on to any other listeners. If it returns false, the key will be passed to any
  24610. KeyListeners that have been registered with this component. As soon as one of these
  24611. returns true, the process will stop, but if they all return false, the event will
  24612. be passed upwards to this component's parent, and so on.
  24613. The default implementation of this method does nothing and returns false.
  24614. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24615. */
  24616. virtual bool keyPressed (const KeyPress& key);
  24617. /** Called when a key is pressed or released.
  24618. Whenever a key on the keyboard is pressed or released (including modifier keys
  24619. like shift and ctrl), this method will be called on the component that currently
  24620. has the keyboard focus. Remember that a component will only be given the focus if
  24621. its setWantsKeyboardFocus() method has been used to enable this.
  24622. If your implementation returns true, the event will be consumed and not passed
  24623. on to any other listeners. If it returns false, then any KeyListeners that have
  24624. been registered with this component will have their keyStateChanged methods called.
  24625. As soon as one of these returns true, the process will stop, but if they all return
  24626. false, the event will be passed upwards to this component's parent, and so on.
  24627. The default implementation of this method does nothing and returns false.
  24628. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24629. method.
  24630. @param isKeyDown true if a key has been pressed; false if it has been released
  24631. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24632. */
  24633. virtual bool keyStateChanged (bool isKeyDown);
  24634. /** Called when a modifier key is pressed or released.
  24635. Whenever the shift, control, alt or command keys are pressed or released,
  24636. this method will be called on the component that currently has the keyboard focus.
  24637. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24638. method has been used to enable this.
  24639. The default implementation of this method actually calls its parent's modifierKeysChanged
  24640. method, so that focused components which aren't interested in this will give their
  24641. parents a chance to act on the event instead.
  24642. @see keyStateChanged, ModifierKeys
  24643. */
  24644. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24645. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24646. enum FocusChangeType
  24647. {
  24648. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24649. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24650. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24651. };
  24652. /** Called to indicate that this component has just acquired the keyboard focus.
  24653. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24654. */
  24655. virtual void focusGained (FocusChangeType cause);
  24656. /** Called to indicate that this component has just lost the keyboard focus.
  24657. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24658. */
  24659. virtual void focusLost (FocusChangeType cause);
  24660. /** Called to indicate that one of this component's children has been focused or unfocused.
  24661. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24662. changed. It happens when focus moves from one of this component's children (at any depth)
  24663. to a component that isn't contained in this one, (or vice-versa).
  24664. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24665. */
  24666. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24667. /** Returns true if the mouse is currently over this component.
  24668. If the mouse isn't over the component, this will return false, even if the
  24669. mouse is currently being dragged - so you can use this in your mouseDrag
  24670. method to find out whether it's really over the component or not.
  24671. Note that when the mouse button is being held down, then the only component
  24672. for which this method will return true is the one that was originally
  24673. clicked on.
  24674. If includeChildren is true, then this will also return true if the mouse is over
  24675. any of the component's children (recursively) as well as the component itself.
  24676. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24677. */
  24678. bool isMouseOver (bool includeChildren = false) const;
  24679. /** Returns true if the mouse button is currently held down in this component.
  24680. Note that this is a test to see whether the mouse is being pressed in this
  24681. component, so it'll return false if called on component A when the mouse
  24682. is actually being dragged in component B.
  24683. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24684. */
  24685. bool isMouseButtonDown() const noexcept;
  24686. /** True if the mouse is over this component, or if it's being dragged in this component.
  24687. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24688. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24689. */
  24690. bool isMouseOverOrDragging() const noexcept;
  24691. /** Returns true if a mouse button is currently down.
  24692. Unlike isMouseButtonDown, this will test the current state of the
  24693. buttons without regard to which component (if any) it has been
  24694. pressed in.
  24695. @see isMouseButtonDown, ModifierKeys
  24696. */
  24697. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() noexcept;
  24698. /** Returns the mouse's current position, relative to this component.
  24699. The return value is relative to the component's top-left corner.
  24700. */
  24701. const Point<int> getMouseXYRelative() const;
  24702. /** Called when this component's size has been changed.
  24703. A component can implement this method to do things such as laying out its
  24704. child components when its width or height changes.
  24705. The method is called synchronously as a result of the setBounds or setSize
  24706. methods, so repeatedly changing a components size will repeatedly call its
  24707. resized method (unlike things like repainting, where multiple calls to repaint
  24708. are coalesced together).
  24709. If the component is a top-level window on the desktop, its size could also
  24710. be changed by operating-system factors beyond the application's control.
  24711. @see moved, setSize
  24712. */
  24713. virtual void resized();
  24714. /** Called when this component's position has been changed.
  24715. This is called when the position relative to its parent changes, not when
  24716. its absolute position on the screen changes (so it won't be called for
  24717. all child components when a parent component is moved).
  24718. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24719. or any of the other repositioning methods, and like resized(), it will be
  24720. called each time those methods are called.
  24721. If the component is a top-level window on the desktop, its position could also
  24722. be changed by operating-system factors beyond the application's control.
  24723. @see resized, setBounds
  24724. */
  24725. virtual void moved();
  24726. /** Called when one of this component's children is moved or resized.
  24727. If the parent wants to know about changes to its immediate children (not
  24728. to children of its children), this is the method to override.
  24729. @see moved, resized, parentSizeChanged
  24730. */
  24731. virtual void childBoundsChanged (Component* child);
  24732. /** Called when this component's immediate parent has been resized.
  24733. If the component is a top-level window, this indicates that the screen size
  24734. has changed.
  24735. @see childBoundsChanged, moved, resized
  24736. */
  24737. virtual void parentSizeChanged();
  24738. /** Called when this component has been moved to the front of its siblings.
  24739. The component may have been brought to the front by the toFront() method, or
  24740. by the operating system if it's a top-level window.
  24741. @see toFront
  24742. */
  24743. virtual void broughtToFront();
  24744. /** Adds a listener to be told about changes to the component hierarchy or position.
  24745. Component listeners get called when this component's size, position or children
  24746. change - see the ComponentListener class for more details.
  24747. @param newListener the listener to register - if this is already registered, it
  24748. will be ignored.
  24749. @see ComponentListener, removeComponentListener
  24750. */
  24751. void addComponentListener (ComponentListener* newListener);
  24752. /** Removes a component listener.
  24753. @see addComponentListener
  24754. */
  24755. void removeComponentListener (ComponentListener* listenerToRemove);
  24756. /** Dispatches a numbered message to this component.
  24757. This is a quick and cheap way of allowing simple asynchronous messages to
  24758. be sent to components. It's also safe, because if the component that you
  24759. send the message to is a null or dangling pointer, this won't cause an error.
  24760. The command ID is later delivered to the component's handleCommandMessage() method by
  24761. the application's message queue.
  24762. @see handleCommandMessage
  24763. */
  24764. void postCommandMessage (int commandId);
  24765. /** Called to handle a command that was sent by postCommandMessage().
  24766. This is called by the message thread when a command message arrives, and
  24767. the component can override this method to process it in any way it needs to.
  24768. @see postCommandMessage
  24769. */
  24770. virtual void handleCommandMessage (int commandId);
  24771. /** Runs a component modally, waiting until the loop terminates.
  24772. This method first makes the component visible, brings it to the front and
  24773. gives it the keyboard focus.
  24774. It then runs a loop, dispatching messages from the system message queue, but
  24775. blocking all mouse or keyboard messages from reaching any components other
  24776. than this one and its children.
  24777. This loop continues until the component's exitModalState() method is called (or
  24778. the component is deleted), and then this method returns, returning the value
  24779. passed into exitModalState().
  24780. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  24781. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  24782. */
  24783. #if JUCE_MODAL_LOOPS_PERMITTED
  24784. int runModalLoop();
  24785. #endif
  24786. /** Puts the component into a modal state.
  24787. This makes the component modal, so that messages are blocked from reaching
  24788. any components other than this one and its children, but unlike runModalLoop(),
  24789. this method returns immediately.
  24790. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  24791. get the focus, which is usually what you'll want it to do. If not, it will leave
  24792. the focus unchanged.
  24793. The callback is an optional object which will receive a callback when the modal
  24794. component loses its modal status, either by being hidden or when exitModalState()
  24795. is called. If you pass an object in here, the system will take care of deleting it
  24796. later, after making the callback
  24797. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  24798. deleted and then the callback will be called. (This will safely handle the situation
  24799. where the component is deleted before its exitModalState() method is called).
  24800. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  24801. */
  24802. void enterModalState (bool takeKeyboardFocus = true,
  24803. ModalComponentManager::Callback* callback = nullptr,
  24804. bool deleteWhenDismissed = false);
  24805. /** Ends a component's modal state.
  24806. If this component is currently modal, this will turn of its modalness, and return
  24807. a value to the runModalLoop() method that might have be running its modal loop.
  24808. @see runModalLoop, enterModalState, isCurrentlyModal
  24809. */
  24810. void exitModalState (int returnValue);
  24811. /** Returns true if this component is the modal one.
  24812. It's possible to have nested modal components, e.g. a pop-up dialog box
  24813. that launches another pop-up, but this will only return true for
  24814. the one at the top of the stack.
  24815. @see getCurrentlyModalComponent
  24816. */
  24817. bool isCurrentlyModal() const noexcept;
  24818. /** Returns the number of components that are currently in a modal state.
  24819. @see getCurrentlyModalComponent
  24820. */
  24821. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() noexcept;
  24822. /** Returns one of the components that are currently modal.
  24823. The index specifies which of the possible modal components to return. The order
  24824. of the components in this list is the reverse of the order in which they became
  24825. modal - so the component at index 0 is always the active component, and the others
  24826. are progressively earlier ones that are themselves now blocked by later ones.
  24827. @returns the modal component, or null if no components are modal (or if the
  24828. index is out of range)
  24829. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  24830. */
  24831. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) noexcept;
  24832. /** Checks whether there's a modal component somewhere that's stopping this one
  24833. from receiving messages.
  24834. If there is a modal component, its canModalEventBeSentToComponent() method
  24835. will be called to see if it will still allow this component to receive events.
  24836. @see runModalLoop, getCurrentlyModalComponent
  24837. */
  24838. bool isCurrentlyBlockedByAnotherModalComponent() const;
  24839. /** When a component is modal, this callback allows it to choose which other
  24840. components can still receive events.
  24841. When a modal component is active and the user clicks on a non-modal component,
  24842. this method is called on the modal component, and if it returns true, the
  24843. event is allowed to reach its target. If it returns false, the event is blocked
  24844. and the inputAttemptWhenModal() callback is made.
  24845. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  24846. implementation just returns false in all cases.
  24847. */
  24848. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  24849. /** Called when the user tries to click on a component that is blocked by another
  24850. modal component.
  24851. When a component is modal and the user clicks on one of the other components,
  24852. the modal component will receive this callback.
  24853. The default implementation of this method will play a beep, and bring the currently
  24854. modal component to the front, but it can be overridden to do other tasks.
  24855. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  24856. */
  24857. virtual void inputAttemptWhenModal();
  24858. /** Returns the set of properties that belong to this component.
  24859. Each component has a NamedValueSet object which you can use to attach arbitrary
  24860. items of data to it.
  24861. */
  24862. NamedValueSet& getProperties() noexcept { return properties; }
  24863. /** Returns the set of properties that belong to this component.
  24864. Each component has a NamedValueSet object which you can use to attach arbitrary
  24865. items of data to it.
  24866. */
  24867. const NamedValueSet& getProperties() const noexcept { return properties; }
  24868. /** Looks for a colour that has been registered with the given colour ID number.
  24869. If a colour has been set for this ID number using setColour(), then it is
  24870. returned. If none has been set, the method will try calling the component's
  24871. LookAndFeel class's findColour() method. If none has been registered with the
  24872. look-and-feel either, it will just return black.
  24873. The colour IDs for various purposes are stored as enums in the components that
  24874. they are relevent to - for an example, see Slider::ColourIds,
  24875. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  24876. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24877. */
  24878. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  24879. /** Registers a colour to be used for a particular purpose.
  24880. Changing a colour will cause a synchronous callback to the colourChanged()
  24881. method, which your component can override if it needs to do something when
  24882. colours are altered.
  24883. For more details about colour IDs, see the comments for findColour().
  24884. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24885. */
  24886. void setColour (int colourId, const Colour& colour);
  24887. /** If a colour has been set with setColour(), this will remove it.
  24888. This allows you to make a colour revert to its default state.
  24889. */
  24890. void removeColour (int colourId);
  24891. /** Returns true if the specified colour ID has been explicitly set for this
  24892. component using the setColour() method.
  24893. */
  24894. bool isColourSpecified (int colourId) const;
  24895. /** This looks for any colours that have been specified for this component,
  24896. and copies them to the specified target component.
  24897. */
  24898. void copyAllExplicitColoursTo (Component& target) const;
  24899. /** This method is called when a colour is changed by the setColour() method.
  24900. @see setColour, findColour
  24901. */
  24902. virtual void colourChanged();
  24903. /** Components can implement this method to provide a MarkerList.
  24904. The default implementation of this method returns 0, but you can override it to
  24905. return a pointer to the component's marker list. If xAxis is true, it should
  24906. return the X marker list; if false, it should return the Y markers.
  24907. */
  24908. virtual MarkerList* getMarkers (bool xAxis);
  24909. /** Returns the underlying native window handle for this component.
  24910. This is platform-dependent and strictly for power-users only!
  24911. */
  24912. void* getWindowHandle() const;
  24913. /** Holds a pointer to some type of Component, which automatically becomes null if
  24914. the component is deleted.
  24915. If you're using a component which may be deleted by another event that's outside
  24916. of your control, use a SafePointer instead of a normal pointer to refer to it,
  24917. and you can test whether it's null before using it to see if something has deleted
  24918. it.
  24919. The ComponentType typedef must be Component, or some subclass of Component.
  24920. You may also want to use a WeakReference<Component> object for the same purpose.
  24921. */
  24922. template <class ComponentType>
  24923. class SafePointer
  24924. {
  24925. public:
  24926. /** Creates a null SafePointer. */
  24927. SafePointer() noexcept {}
  24928. /** Creates a SafePointer that points at the given component. */
  24929. SafePointer (ComponentType* const component) : weakRef (component) {}
  24930. /** Creates a copy of another SafePointer. */
  24931. SafePointer (const SafePointer& other) noexcept : weakRef (other.weakRef) {}
  24932. /** Copies another pointer to this one. */
  24933. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  24934. /** Copies another pointer to this one. */
  24935. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  24936. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24937. ComponentType* getComponent() const noexcept { return dynamic_cast <ComponentType*> (weakRef.get()); }
  24938. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24939. operator ComponentType*() const noexcept { return getComponent(); }
  24940. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24941. ComponentType* operator->() noexcept { return getComponent(); }
  24942. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24943. const ComponentType* operator->() const noexcept { return getComponent(); }
  24944. /** If the component is valid, this deletes it and sets this pointer to null. */
  24945. void deleteAndZero() { delete getComponent(); jassert (getComponent() == nullptr); }
  24946. bool operator== (ComponentType* component) const noexcept { return weakRef == component; }
  24947. bool operator!= (ComponentType* component) const noexcept { return weakRef != component; }
  24948. private:
  24949. WeakReference<Component> weakRef;
  24950. };
  24951. /** A class to keep an eye on a component and check for it being deleted.
  24952. This is designed for use with the ListenerList::callChecked() methods, to allow
  24953. the list iterator to stop cleanly if the component is deleted by a listener callback
  24954. while the list is still being iterated.
  24955. */
  24956. class JUCE_API BailOutChecker
  24957. {
  24958. public:
  24959. /** Creates a checker that watches one component. */
  24960. BailOutChecker (Component* component);
  24961. /** Returns true if either of the two components have been deleted since this object was created. */
  24962. bool shouldBailOut() const noexcept;
  24963. private:
  24964. const WeakReference<Component> safePointer;
  24965. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  24966. };
  24967. /**
  24968. Base class for objects that can be used to automatically position a component according to
  24969. some kind of algorithm.
  24970. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  24971. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  24972. it might choose to watch some kind of value and move the component when the value changes).
  24973. */
  24974. class JUCE_API Positioner
  24975. {
  24976. public:
  24977. /** Creates a Positioner which can control the specified component. */
  24978. explicit Positioner (Component& component) noexcept;
  24979. /** Destructor. */
  24980. virtual ~Positioner() {}
  24981. /** Returns the component that this positioner controls. */
  24982. Component& getComponent() const noexcept { return component; }
  24983. /** Attempts to set the component's position to the given rectangle.
  24984. Unlike simply calling Component::setBounds(), this may involve the positioner
  24985. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  24986. positioner may try to reverse the expressions used to make them fit these new coordinates.
  24987. */
  24988. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  24989. private:
  24990. Component& component;
  24991. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  24992. };
  24993. /** Returns the Positioner object that has been set for this component.
  24994. @see setPositioner()
  24995. */
  24996. Positioner* getPositioner() const noexcept;
  24997. /** Sets a new Positioner object for this component.
  24998. If there's currently another positioner set, it will be deleted. The object that is passed in
  24999. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  25000. to clear the current positioner.
  25001. @see getPositioner()
  25002. */
  25003. void setPositioner (Positioner* newPositioner);
  25004. #ifndef DOXYGEN
  25005. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  25006. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  25007. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  25008. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  25009. #endif
  25010. private:
  25011. friend class ComponentPeer;
  25012. friend class MouseInputSource;
  25013. friend class MouseInputSourceInternal;
  25014. #ifndef DOXYGEN
  25015. static Component* currentlyFocusedComponent;
  25016. String componentName, componentID;
  25017. Component* parentComponent;
  25018. Rectangle<int> bounds;
  25019. ScopedPointer <Positioner> positioner;
  25020. ScopedPointer <AffineTransform> affineTransform;
  25021. Array <Component*> childComponentList;
  25022. LookAndFeel* lookAndFeel;
  25023. MouseCursor cursor;
  25024. ImageEffectFilter* effect;
  25025. Image bufferedImage;
  25026. class MouseListenerList;
  25027. friend class MouseListenerList;
  25028. friend class ScopedPointer <MouseListenerList>;
  25029. ScopedPointer <MouseListenerList> mouseListeners;
  25030. ScopedPointer <Array <KeyListener*> > keyListeners;
  25031. ListenerList <ComponentListener> componentListeners;
  25032. NamedValueSet properties;
  25033. friend class WeakReference<Component>;
  25034. WeakReference<Component>::Master weakReferenceMaster;
  25035. const WeakReference<Component>::SharedRef& getWeakReference();
  25036. struct ComponentFlags
  25037. {
  25038. bool hasHeavyweightPeerFlag : 1;
  25039. bool visibleFlag : 1;
  25040. bool opaqueFlag : 1;
  25041. bool ignoresMouseClicksFlag : 1;
  25042. bool allowChildMouseClicksFlag : 1;
  25043. bool wantsFocusFlag : 1;
  25044. bool isFocusContainerFlag : 1;
  25045. bool dontFocusOnMouseClickFlag : 1;
  25046. bool alwaysOnTopFlag : 1;
  25047. bool bufferToImageFlag : 1;
  25048. bool bringToFrontOnClickFlag : 1;
  25049. bool repaintOnMouseActivityFlag : 1;
  25050. bool mouseDownFlag : 1;
  25051. bool mouseOverFlag : 1;
  25052. bool mouseInsideFlag : 1;
  25053. bool currentlyModalFlag : 1;
  25054. bool isDisabledFlag : 1;
  25055. bool childCompFocusedFlag : 1;
  25056. bool dontClipGraphicsFlag : 1;
  25057. #if JUCE_DEBUG
  25058. bool isInsidePaintCall : 1;
  25059. #endif
  25060. };
  25061. union
  25062. {
  25063. uint32 componentFlags;
  25064. ComponentFlags flags;
  25065. };
  25066. uint8 componentTransparency;
  25067. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25068. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25069. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25070. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  25071. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25072. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25073. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  25074. void internalBroughtToFront();
  25075. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  25076. void internalFocusGain (const FocusChangeType cause);
  25077. void internalFocusLoss (const FocusChangeType cause);
  25078. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  25079. void internalModalInputAttempt();
  25080. void internalModifierKeysChanged();
  25081. void internalChildrenChanged();
  25082. void internalHierarchyChanged();
  25083. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  25084. void moveChildInternal (int sourceIndex, int destIndex);
  25085. void paintComponentAndChildren (Graphics& g);
  25086. void paintComponent (Graphics& g);
  25087. void paintWithinParentContext (Graphics& g);
  25088. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  25089. void repaintParent();
  25090. void sendFakeMouseMove() const;
  25091. void takeKeyboardFocus (const FocusChangeType cause);
  25092. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  25093. static void giveAwayFocus (bool sendFocusLossEvent);
  25094. void sendEnablementChangeMessage();
  25095. void sendVisibilityChangeMessage();
  25096. class ComponentHelpers;
  25097. friend class ComponentHelpers;
  25098. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  25099. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  25100. */
  25101. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  25102. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25103. // This is included here just to cause a compile error if your code is still handling
  25104. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  25105. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  25106. // implement its methods instead of this Component method).
  25107. virtual void filesDropped (const StringArray&, int, int) {}
  25108. // This is included here to cause an error if you use or overload it - it has been deprecated in
  25109. // favour of contains (const Point<int>&)
  25110. void contains (int, int);
  25111. #endif
  25112. protected:
  25113. /** @internal */
  25114. virtual void internalRepaint (int x, int y, int w, int h);
  25115. /** @internal */
  25116. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  25117. #endif
  25118. };
  25119. #endif // __JUCE_COMPONENT_JUCEHEADER__
  25120. /*** End of inlined file: juce_Component.h ***/
  25121. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  25122. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25123. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25124. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  25125. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25126. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25127. /** A type used to hold the unique ID for an application command.
  25128. This is a numeric type, so it can be stored as an integer.
  25129. @see ApplicationCommandInfo, ApplicationCommandManager,
  25130. ApplicationCommandTarget, KeyPressMappingSet
  25131. */
  25132. typedef int CommandID;
  25133. /** A set of general-purpose application command IDs.
  25134. Because these commands are likely to be used in most apps, they're defined
  25135. here to help different apps to use the same numeric values for them.
  25136. Of course you don't have to use these, but some of them are used internally by
  25137. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  25138. @see ApplicationCommandInfo, ApplicationCommandManager,
  25139. ApplicationCommandTarget, KeyPressMappingSet
  25140. */
  25141. namespace StandardApplicationCommandIDs
  25142. {
  25143. /** This command ID should be used to send a "Quit the App" command.
  25144. This command is recognised by the JUCEApplication class, so if it is invoked
  25145. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  25146. object will catch it and call JUCEApplication::systemRequestedQuit().
  25147. */
  25148. static const CommandID quit = 0x1001;
  25149. /** The command ID that should be used to send a "Delete" command. */
  25150. static const CommandID del = 0x1002;
  25151. /** The command ID that should be used to send a "Cut" command. */
  25152. static const CommandID cut = 0x1003;
  25153. /** The command ID that should be used to send a "Copy to clipboard" command. */
  25154. static const CommandID copy = 0x1004;
  25155. /** The command ID that should be used to send a "Paste from clipboard" command. */
  25156. static const CommandID paste = 0x1005;
  25157. /** The command ID that should be used to send a "Select all" command. */
  25158. static const CommandID selectAll = 0x1006;
  25159. /** The command ID that should be used to send a "Deselect all" command. */
  25160. static const CommandID deselectAll = 0x1007;
  25161. }
  25162. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25163. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  25164. /**
  25165. Holds information describing an application command.
  25166. This object is used to pass information about a particular command, such as its
  25167. name, description and other usage flags.
  25168. When an ApplicationCommandTarget is asked to provide information about the commands
  25169. it can perform, this is the structure gets filled-in to describe each one.
  25170. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  25171. ApplicationCommandManager
  25172. */
  25173. struct JUCE_API ApplicationCommandInfo
  25174. {
  25175. explicit ApplicationCommandInfo (CommandID commandID) noexcept;
  25176. /** Sets a number of the structures values at once.
  25177. The meanings of each of the parameters is described below, in the appropriate
  25178. member variable's description.
  25179. */
  25180. void setInfo (const String& shortName,
  25181. const String& description,
  25182. const String& categoryName,
  25183. int flags) noexcept;
  25184. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  25185. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  25186. is false, the bit is set.
  25187. */
  25188. void setActive (bool isActive) noexcept;
  25189. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  25190. */
  25191. void setTicked (bool isTicked) noexcept;
  25192. /** Handy method for adding a keypress to the defaultKeypresses array.
  25193. This is just so you can write things like:
  25194. @code
  25195. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  25196. @endcode
  25197. instead of
  25198. @code
  25199. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  25200. @endcode
  25201. */
  25202. void addDefaultKeypress (int keyCode,
  25203. const ModifierKeys& modifiers) noexcept;
  25204. /** The command's unique ID number.
  25205. */
  25206. CommandID commandID;
  25207. /** A short name to describe the command.
  25208. This should be suitable for use in menus, on buttons that trigger the command, etc.
  25209. You can use the setInfo() method to quickly set this and some of the command's
  25210. other properties.
  25211. */
  25212. String shortName;
  25213. /** A longer description of the command.
  25214. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  25215. pop-up tooltip describing what the command does.
  25216. You can use the setInfo() method to quickly set this and some of the command's
  25217. other properties.
  25218. */
  25219. String description;
  25220. /** A named category that the command fits into.
  25221. You can give your commands any category you like, and these will be displayed in
  25222. contexts such as the KeyMappingEditorComponent, where the category is used to group
  25223. commands together.
  25224. You can use the setInfo() method to quickly set this and some of the command's
  25225. other properties.
  25226. */
  25227. String categoryName;
  25228. /** A list of zero or more keypresses that should be used as the default keys for
  25229. this command.
  25230. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  25231. this list to initialise the default set of key-to-command mappings.
  25232. @see addDefaultKeypress
  25233. */
  25234. Array <KeyPress> defaultKeypresses;
  25235. /** Flags describing the ways in which this command should be used.
  25236. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  25237. variable.
  25238. */
  25239. enum CommandFlags
  25240. {
  25241. /** Indicates that the command can't currently be performed.
  25242. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  25243. not currently permissable to perform the command. If the flag is set, then
  25244. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  25245. command or show themselves as not being enabled.
  25246. @see ApplicationCommandInfo::setActive
  25247. */
  25248. isDisabled = 1 << 0,
  25249. /** Indicates that the command should have a tick next to it on a menu.
  25250. If your command is shown on a menu and this is set, it'll show a tick next to
  25251. it. Other components such as buttons may also use this flag to indicate that it
  25252. is a value that can be toggled, and is currently in the 'on' state.
  25253. @see ApplicationCommandInfo::setTicked
  25254. */
  25255. isTicked = 1 << 1,
  25256. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  25257. it will call the command twice, once on key-down and again on key-up.
  25258. @see ApplicationCommandTarget::InvocationInfo
  25259. */
  25260. wantsKeyUpDownCallbacks = 1 << 2,
  25261. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  25262. command in its list.
  25263. */
  25264. hiddenFromKeyEditor = 1 << 3,
  25265. /** If this flag is present, then a KeyMappingEditorComponent will display the
  25266. command in its list, but won't allow the assigned keypress to be changed.
  25267. */
  25268. readOnlyInKeyEditor = 1 << 4,
  25269. /** If this flag is present and the command is invoked from a keypress, then any
  25270. buttons or menus that are also connected to the command will not flash to
  25271. indicate that they've been triggered.
  25272. */
  25273. dontTriggerVisualFeedback = 1 << 5
  25274. };
  25275. /** A bitwise-OR of the values specified in the CommandFlags enum.
  25276. You can use the setInfo() method to quickly set this and some of the command's
  25277. other properties.
  25278. */
  25279. int flags;
  25280. };
  25281. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25282. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  25283. /*** Start of inlined file: juce_MessageListener.h ***/
  25284. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  25285. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  25286. /**
  25287. MessageListener subclasses can post and receive Message objects.
  25288. @see Message, MessageManager, ActionListener, ChangeListener
  25289. */
  25290. class JUCE_API MessageListener
  25291. {
  25292. protected:
  25293. /** Creates a MessageListener. */
  25294. MessageListener() noexcept;
  25295. public:
  25296. /** Destructor.
  25297. When a MessageListener is deleted, it removes itself from a global list
  25298. of registered listeners, so that the isValidMessageListener() method
  25299. will no longer return true.
  25300. */
  25301. virtual ~MessageListener();
  25302. /** This is the callback method that receives incoming messages.
  25303. This is called by the MessageManager from its dispatch loop.
  25304. @see postMessage
  25305. */
  25306. virtual void handleMessage (const Message& message) = 0;
  25307. /** Sends a message to the message queue, for asynchronous delivery to this listener
  25308. later on.
  25309. This method can be called safely by any thread.
  25310. @param message the message object to send - this will be deleted
  25311. automatically by the message queue, so don't keep any
  25312. references to it after calling this method.
  25313. @see handleMessage
  25314. */
  25315. void postMessage (Message* message) const noexcept;
  25316. /** Checks whether this MessageListener has been deleted.
  25317. Although not foolproof, this method is safe to call on dangling or null
  25318. pointers. A list of active MessageListeners is kept internally, so this
  25319. checks whether the object is on this list or not.
  25320. Note that it's possible to get a false-positive here, if an object is
  25321. deleted and another is subsequently created that happens to be at the
  25322. exact same memory location, but I can't think of a good way of avoiding
  25323. this.
  25324. */
  25325. bool isValidMessageListener() const noexcept;
  25326. };
  25327. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  25328. /*** End of inlined file: juce_MessageListener.h ***/
  25329. /**
  25330. A command target publishes a list of command IDs that it can perform.
  25331. An ApplicationCommandManager despatches commands to targets, which must be
  25332. able to provide information about what commands they can handle.
  25333. To create a target, you'll need to inherit from this class, implementing all of
  25334. its pure virtual methods.
  25335. For info about how a target is chosen to receive a command, see
  25336. ApplicationCommandManager::getFirstCommandTarget().
  25337. @see ApplicationCommandManager, ApplicationCommandInfo
  25338. */
  25339. class JUCE_API ApplicationCommandTarget
  25340. {
  25341. public:
  25342. /** Creates a command target. */
  25343. ApplicationCommandTarget();
  25344. /** Destructor. */
  25345. virtual ~ApplicationCommandTarget();
  25346. /**
  25347. */
  25348. struct JUCE_API InvocationInfo
  25349. {
  25350. InvocationInfo (const CommandID commandID);
  25351. /** The UID of the command that should be performed. */
  25352. CommandID commandID;
  25353. /** The command's flags.
  25354. See ApplicationCommandInfo for a description of these flag values.
  25355. */
  25356. int commandFlags;
  25357. /** The types of context in which the command might be called. */
  25358. enum InvocationMethod
  25359. {
  25360. direct = 0, /**< The command is being invoked directly by a piece of code. */
  25361. fromKeyPress, /**< The command is being invoked by a key-press. */
  25362. fromMenu, /**< The command is being invoked by a menu selection. */
  25363. fromButton /**< The command is being invoked by a button click. */
  25364. };
  25365. /** The type of event that triggered this command. */
  25366. InvocationMethod invocationMethod;
  25367. /** If triggered by a keypress or menu, this will be the component that had the
  25368. keyboard focus at the time.
  25369. If triggered by a button, it may be set to that component, or it may be null.
  25370. */
  25371. Component* originatingComponent;
  25372. /** The keypress that was used to invoke it.
  25373. Note that this will be an invalid keypress if the command was invoked
  25374. by some other means than a keyboard shortcut.
  25375. */
  25376. KeyPress keyPress;
  25377. /** True if the callback is being invoked when the key is pressed,
  25378. false if the key is being released.
  25379. @see KeyPressMappingSet::addCommand()
  25380. */
  25381. bool isKeyDown;
  25382. /** If the key is being released, this indicates how long it had been held
  25383. down for.
  25384. (Only relevant if isKeyDown is false.)
  25385. */
  25386. int millisecsSinceKeyPressed;
  25387. };
  25388. /** This must return the next target to try after this one.
  25389. When a command is being sent, and the first target can't handle
  25390. that command, this method is used to determine the next target that should
  25391. be tried.
  25392. It may return 0 if it doesn't know of another target.
  25393. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  25394. method to return a parent component that might want to handle it.
  25395. @see invoke
  25396. */
  25397. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  25398. /** This must return a complete list of commands that this target can handle.
  25399. Your target should add all the command IDs that it handles to the array that is
  25400. passed-in.
  25401. */
  25402. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  25403. /** This must provide details about one of the commands that this target can perform.
  25404. This will be called with one of the command IDs that the target provided in its
  25405. getAllCommands() methods.
  25406. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  25407. suitable information about the command. (The commandID field will already have been filled-in
  25408. by the caller).
  25409. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  25410. set all the fields at once.
  25411. If the command is currently inactive for some reason, this method must use
  25412. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  25413. bit of the ApplicationCommandInfo::flags field).
  25414. Any default key-presses for the command should be appended to the
  25415. ApplicationCommandInfo::defaultKeypresses field.
  25416. Note that if you change something that affects the status of the commands
  25417. that would be returned by this method (e.g. something that makes some commands
  25418. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  25419. to cause the manager to refresh its status.
  25420. */
  25421. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  25422. /** This must actually perform the specified command.
  25423. If this target is able to perform the command specified by the commandID field of the
  25424. InvocationInfo structure, then it should do so, and must return true.
  25425. If it can't handle this command, it should return false, which tells the caller to pass
  25426. the command on to the next target in line.
  25427. @see invoke, ApplicationCommandManager::invoke
  25428. */
  25429. virtual bool perform (const InvocationInfo& info) = 0;
  25430. /** Makes this target invoke a command.
  25431. Your code can call this method to invoke a command on this target, but normally
  25432. you'd call it indirectly via ApplicationCommandManager::invoke() or
  25433. ApplicationCommandManager::invokeDirectly().
  25434. If this target can perform the given command, it will call its perform() method to
  25435. do so. If not, then getNextCommandTarget() will be used to determine the next target
  25436. to try, and the command will be passed along to it.
  25437. @param invocationInfo this must be correctly filled-in, describing the context for
  25438. the invocation.
  25439. @param asynchronously if false, the command will be performed before this method returns.
  25440. If true, a message will be posted so that the command will be performed
  25441. later on the message thread, and this method will return immediately.
  25442. @see perform, ApplicationCommandManager::invoke
  25443. */
  25444. bool invoke (const InvocationInfo& invocationInfo,
  25445. const bool asynchronously);
  25446. /** Invokes a given command directly on this target.
  25447. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25448. structure.
  25449. */
  25450. bool invokeDirectly (const CommandID commandID,
  25451. const bool asynchronously);
  25452. /** Searches this target and all subsequent ones for the first one that can handle
  25453. the specified command.
  25454. This will use getNextCommandTarget() to determine the chain of targets to try
  25455. after this one.
  25456. */
  25457. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  25458. /** Checks whether this command can currently be performed by this target.
  25459. This will return true only if a call to getCommandInfo() doesn't set the
  25460. isDisabled flag to indicate that the command is inactive.
  25461. */
  25462. bool isCommandActive (const CommandID commandID);
  25463. /** If this object is a Component, this method will seach upwards in its current
  25464. UI hierarchy for the next parent component that implements the
  25465. ApplicationCommandTarget class.
  25466. If your target is a Component, this is a very handy method to use in your
  25467. getNextCommandTarget() implementation.
  25468. */
  25469. ApplicationCommandTarget* findFirstTargetParentComponent();
  25470. private:
  25471. // (for async invocation of commands)
  25472. class CommandTargetMessageInvoker : public MessageListener
  25473. {
  25474. public:
  25475. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  25476. ~CommandTargetMessageInvoker();
  25477. void handleMessage (const Message& message);
  25478. private:
  25479. ApplicationCommandTarget* const owner;
  25480. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  25481. };
  25482. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  25483. friend class CommandTargetMessageInvoker;
  25484. bool tryToInvoke (const InvocationInfo& info, bool async);
  25485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  25486. };
  25487. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25488. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  25489. /*** Start of inlined file: juce_ActionListener.h ***/
  25490. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  25491. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  25492. /**
  25493. Receives callbacks to indicate that some kind of event has occurred.
  25494. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  25495. about something that's happened.
  25496. @see ActionBroadcaster, ChangeListener
  25497. */
  25498. class JUCE_API ActionListener
  25499. {
  25500. public:
  25501. /** Destructor. */
  25502. virtual ~ActionListener() {}
  25503. /** Overridden by your subclass to receive the callback.
  25504. @param message the string that was specified when the event was triggered
  25505. by a call to ActionBroadcaster::sendActionMessage()
  25506. */
  25507. virtual void actionListenerCallback (const String& message) = 0;
  25508. };
  25509. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  25510. /*** End of inlined file: juce_ActionListener.h ***/
  25511. /**
  25512. An instance of this class is used to specify initialisation and shutdown
  25513. code for the application.
  25514. An application that wants to run in the JUCE framework needs to declare a
  25515. subclass of JUCEApplication and implement its various pure virtual methods.
  25516. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  25517. to declare an instance of this class and generate a suitable platform-specific
  25518. main() function.
  25519. e.g. @code
  25520. class MyJUCEApp : public JUCEApplication
  25521. {
  25522. public:
  25523. MyJUCEApp()
  25524. {
  25525. }
  25526. ~MyJUCEApp()
  25527. {
  25528. }
  25529. void initialise (const String& commandLine)
  25530. {
  25531. myMainWindow = new MyApplicationWindow();
  25532. myMainWindow->setBounds (100, 100, 400, 500);
  25533. myMainWindow->setVisible (true);
  25534. }
  25535. void shutdown()
  25536. {
  25537. myMainWindow = 0;
  25538. }
  25539. const String getApplicationName()
  25540. {
  25541. return "Super JUCE-o-matic";
  25542. }
  25543. const String getApplicationVersion()
  25544. {
  25545. return "1.0";
  25546. }
  25547. private:
  25548. ScopedPointer <MyApplicationWindow> myMainWindow;
  25549. };
  25550. // this creates wrapper code to actually launch the app properly.
  25551. START_JUCE_APPLICATION (MyJUCEApp)
  25552. @endcode
  25553. @see MessageManager, DeletedAtShutdown
  25554. */
  25555. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  25556. private ActionListener
  25557. {
  25558. protected:
  25559. /** Constructs a JUCE app object.
  25560. If subclasses implement a constructor or destructor, they shouldn't call any
  25561. JUCE code in there - put your startup/shutdown code in initialise() and
  25562. shutdown() instead.
  25563. */
  25564. JUCEApplication();
  25565. public:
  25566. /** Destructor.
  25567. If subclasses implement a constructor or destructor, they shouldn't call any
  25568. JUCE code in there - put your startup/shutdown code in initialise() and
  25569. shutdown() instead.
  25570. */
  25571. virtual ~JUCEApplication();
  25572. /** Returns the global instance of the application object being run. */
  25573. static JUCEApplication* getInstance() noexcept { return appInstance; }
  25574. /** Called when the application starts.
  25575. This will be called once to let the application do whatever initialisation
  25576. it needs, create its windows, etc.
  25577. After the method returns, the normal event-dispatch loop will be run,
  25578. until the quit() method is called, at which point the shutdown()
  25579. method will be called to let the application clear up anything it needs
  25580. to delete.
  25581. If during the initialise() method, the application decides not to start-up
  25582. after all, it can just call the quit() method and the event loop won't be run.
  25583. @param commandLineParameters the line passed in does not include the
  25584. name of the executable, just the parameter list.
  25585. @see shutdown, quit
  25586. */
  25587. virtual void initialise (const String& commandLineParameters) = 0;
  25588. /** Returns true if the application hasn't yet completed its initialise() method
  25589. and entered the main event loop.
  25590. This is handy for things like splash screens to know when the app's up-and-running
  25591. properly.
  25592. */
  25593. bool isInitialising() const noexcept { return stillInitialising; }
  25594. /* Called to allow the application to clear up before exiting.
  25595. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25596. terminate, and this method will get called to allow the app to sort itself
  25597. out.
  25598. Be careful that nothing happens in this method that might rely on messages
  25599. being sent, or any kind of window activity, because the message loop is no
  25600. longer running at this point.
  25601. @see DeletedAtShutdown
  25602. */
  25603. virtual void shutdown() = 0;
  25604. /** Returns the application's name.
  25605. An application must implement this to name itself.
  25606. */
  25607. virtual const String getApplicationName() = 0;
  25608. /** Returns the application's version number.
  25609. */
  25610. virtual const String getApplicationVersion() = 0;
  25611. /** Checks whether multiple instances of the app are allowed.
  25612. If you application class returns true for this, more than one instance is
  25613. permitted to run (except on the Mac where this isn't possible).
  25614. If it's false, the second instance won't start, but it you will still get a
  25615. callback to anotherInstanceStarted() to tell you about this - which
  25616. gives you a chance to react to what the user was trying to do.
  25617. */
  25618. virtual bool moreThanOneInstanceAllowed();
  25619. /** Indicates that the user has tried to start up another instance of the app.
  25620. This will get called even if moreThanOneInstanceAllowed() is false.
  25621. */
  25622. virtual void anotherInstanceStarted (const String& commandLine);
  25623. /** Called when the operating system is trying to close the application.
  25624. The default implementation of this method is to call quit(), but it may
  25625. be overloaded to ignore the request or do some other special behaviour
  25626. instead. For example, you might want to offer the user the chance to save
  25627. their changes before quitting, and give them the chance to cancel.
  25628. If you want to send a quit signal to your app, this is the correct method
  25629. to call, because it means that requests that come from the system get handled
  25630. in the same way as those from your own application code. So e.g. you'd
  25631. call this method from a "quit" item on a menu bar.
  25632. */
  25633. virtual void systemRequestedQuit();
  25634. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25635. callback will be triggered, in case you want to log them or do some other
  25636. type of error-handling.
  25637. If the type of exception is derived from the std::exception class, the pointer
  25638. passed-in will be valid. If the exception is of unknown type, this pointer
  25639. will be null.
  25640. */
  25641. virtual void unhandledException (const std::exception* e,
  25642. const String& sourceFilename,
  25643. int lineNumber);
  25644. /** Signals that the main message loop should stop and the application should terminate.
  25645. This isn't synchronous, it just posts a quit message to the main queue, and
  25646. when this message arrives, the message loop will stop, the shutdown() method
  25647. will be called, and the app will exit.
  25648. Note that this will cause an unconditional quit to happen, so if you need an
  25649. extra level before this, e.g. to give the user the chance to save their work
  25650. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25651. method - see that method's help for more info.
  25652. @see MessageManager, DeletedAtShutdown
  25653. */
  25654. static void quit();
  25655. /** Sets the value that should be returned as the application's exit code when the
  25656. app quits.
  25657. This is the value that's returned by the main() function. Normally you'd leave this
  25658. as 0 unless you want to indicate an error code.
  25659. @see getApplicationReturnValue
  25660. */
  25661. void setApplicationReturnValue (int newReturnValue) noexcept;
  25662. /** Returns the value that has been set as the application's exit code.
  25663. @see setApplicationReturnValue
  25664. */
  25665. int getApplicationReturnValue() const noexcept { return appReturnValue; }
  25666. /** Returns the application's command line params.
  25667. */
  25668. const String getCommandLineParameters() const noexcept { return commandLineParameters; }
  25669. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  25670. /** @internal */
  25671. static int main (const String& commandLine);
  25672. /** @internal */
  25673. static int main (int argc, const char* argv[]);
  25674. /** @internal */
  25675. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25676. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25677. or other kind of shared library. */
  25678. static inline bool isStandaloneApp() noexcept { return createInstance != 0; }
  25679. /** @internal */
  25680. ApplicationCommandTarget* getNextCommandTarget();
  25681. /** @internal */
  25682. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25683. /** @internal */
  25684. void getAllCommands (Array <CommandID>& commands);
  25685. /** @internal */
  25686. bool perform (const InvocationInfo& info);
  25687. /** @internal */
  25688. void actionListenerCallback (const String& message);
  25689. /** @internal */
  25690. bool initialiseApp (const String& commandLine);
  25691. /** @internal */
  25692. int shutdownApp();
  25693. /** @internal */
  25694. static void appWillTerminateByForce();
  25695. /** @internal */
  25696. typedef JUCEApplication* (*CreateInstanceFunction)();
  25697. /** @internal */
  25698. static CreateInstanceFunction createInstance;
  25699. private:
  25700. String commandLineParameters;
  25701. int appReturnValue;
  25702. bool stillInitialising;
  25703. ScopedPointer<InterProcessLock> appLock;
  25704. static JUCEApplication* appInstance;
  25705. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25706. };
  25707. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25708. /*** End of inlined file: juce_Application.h ***/
  25709. #endif
  25710. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25711. #endif
  25712. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25713. #endif
  25714. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25715. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25716. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25717. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25718. /*** Start of inlined file: juce_Desktop.h ***/
  25719. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25720. #define __JUCE_DESKTOP_JUCEHEADER__
  25721. /*** Start of inlined file: juce_Timer.h ***/
  25722. #ifndef __JUCE_TIMER_JUCEHEADER__
  25723. #define __JUCE_TIMER_JUCEHEADER__
  25724. class InternalTimerThread;
  25725. /**
  25726. Makes repeated callbacks to a virtual method at a specified time interval.
  25727. A Timer's timerCallback() method will be repeatedly called at a given
  25728. interval. When you create a Timer object, it will do nothing until the
  25729. startTimer() method is called, which will cause the message thread to
  25730. start making callbacks at the specified interval, until stopTimer() is called
  25731. or the object is deleted.
  25732. The time interval isn't guaranteed to be precise to any more than maybe
  25733. 10-20ms, and the intervals may end up being much longer than requested if the
  25734. system is busy. Because the callbacks are made by the main message thread,
  25735. anything that blocks the message queue for a period of time will also prevent
  25736. any timers from running until it can carry on.
  25737. If you need to have a single callback that is shared by multiple timers with
  25738. different frequencies, then the MultiTimer class allows you to do that - its
  25739. structure is very similar to the Timer class, but contains multiple timers
  25740. internally, each one identified by an ID number.
  25741. @see MultiTimer
  25742. */
  25743. class JUCE_API Timer
  25744. {
  25745. protected:
  25746. /** Creates a Timer.
  25747. When created, the timer is stopped, so use startTimer() to get it going.
  25748. */
  25749. Timer() noexcept;
  25750. /** Creates a copy of another timer.
  25751. Note that this timer won't be started, even if the one you're copying
  25752. is running.
  25753. */
  25754. Timer (const Timer& other) noexcept;
  25755. public:
  25756. /** Destructor. */
  25757. virtual ~Timer();
  25758. /** The user-defined callback routine that actually gets called periodically.
  25759. It's perfectly ok to call startTimer() or stopTimer() from within this
  25760. callback to change the subsequent intervals.
  25761. */
  25762. virtual void timerCallback() = 0;
  25763. /** Starts the timer and sets the length of interval required.
  25764. If the timer is already started, this will reset it, so the
  25765. time between calling this method and the next timer callback
  25766. will not be less than the interval length passed in.
  25767. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25768. rounded up to 1)
  25769. */
  25770. void startTimer (int intervalInMilliseconds) noexcept;
  25771. /** Stops the timer.
  25772. No more callbacks will be made after this method returns.
  25773. If this is called from a different thread, any callbacks that may
  25774. be currently executing may be allowed to finish before the method
  25775. returns.
  25776. */
  25777. void stopTimer() noexcept;
  25778. /** Checks if the timer has been started.
  25779. @returns true if the timer is running.
  25780. */
  25781. bool isTimerRunning() const noexcept { return periodMs > 0; }
  25782. /** Returns the timer's interval.
  25783. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  25784. */
  25785. int getTimerInterval() const noexcept { return periodMs; }
  25786. private:
  25787. friend class InternalTimerThread;
  25788. int countdownMs, periodMs;
  25789. Timer* previous;
  25790. Timer* next;
  25791. Timer& operator= (const Timer&);
  25792. };
  25793. #endif // __JUCE_TIMER_JUCEHEADER__
  25794. /*** End of inlined file: juce_Timer.h ***/
  25795. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  25796. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25797. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25798. /**
  25799. Animates a set of components, moving them to a new position and/or fading their
  25800. alpha levels.
  25801. To animate a component, create a ComponentAnimator instance or (preferably) use the
  25802. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  25803. method to commence the movement.
  25804. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  25805. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  25806. destinations.
  25807. It's ok to delete components while they're being animated - the animator will detect this
  25808. and safely stop using them.
  25809. The class is a ChangeBroadcaster and sends a notification when any components
  25810. start or finish being animated.
  25811. @see Desktop::getAnimator
  25812. */
  25813. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  25814. private Timer
  25815. {
  25816. public:
  25817. /** Creates a ComponentAnimator. */
  25818. ComponentAnimator();
  25819. /** Destructor. */
  25820. ~ComponentAnimator();
  25821. /** Starts a component moving from its current position to a specified position.
  25822. If the component is already in the middle of an animation, that will be abandoned,
  25823. and a new animation will begin, moving the component from its current location.
  25824. The start and end speed parameters let you apply some acceleration to the component's
  25825. movement.
  25826. @param component the component to move
  25827. @param finalBounds the destination bounds to which the component should move. To leave the
  25828. component in the same place, just pass component->getBounds() for this value
  25829. @param finalAlpha the alpha value that the component should have at the end of the animation
  25830. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  25831. @param useProxyComponent if true, this means the component should be replaced by an internally
  25832. managed temporary component which is a snapshot of the original component.
  25833. This avoids the component having to paint itself as it moves, so may
  25834. be more efficient. This option also allows you to delete the original
  25835. component immediately after starting the animation, because the animation
  25836. can proceed without it. If you use a proxy, the original component will be
  25837. made invisible by this call, and then will become visible again at the end
  25838. of the animation. It'll also mean that the proxy component will be temporarily
  25839. added to the component's parent, so avoid it if this might confuse the parent
  25840. component, or if there's a chance the parent might decide to delete its children.
  25841. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  25842. the component will start by accelerating from rest; higher values mean that it
  25843. will have an initial speed greater than zero. If the value if greater than 1, it
  25844. will decelerate towards the middle of its journey. To move the component at a
  25845. constant rate for its entire animation, set both the start and end speeds to 1.0
  25846. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  25847. If this is 0, the component will decelerate to a standstill at its final position;
  25848. higher values mean the component will still be moving when it stops. To move the component
  25849. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  25850. */
  25851. void animateComponent (Component* component,
  25852. const Rectangle<int>& finalBounds,
  25853. float finalAlpha,
  25854. int animationDurationMilliseconds,
  25855. bool useProxyComponent,
  25856. double startSpeed,
  25857. double endSpeed);
  25858. /** Begins a fade-out of this components alpha level.
  25859. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  25860. a proxy. You're safe to delete the component after calling this method, and this won't
  25861. interfere with the animation's progress.
  25862. */
  25863. void fadeOut (Component* component, int millisecondsToTake);
  25864. /** Begins a fade-in of a component.
  25865. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  25866. */
  25867. void fadeIn (Component* component, int millisecondsToTake);
  25868. /** Stops a component if it's currently being animated.
  25869. If moveComponentToItsFinalPosition is true, then the component will
  25870. be immediately moved to its destination position and size. If false, it will be
  25871. left in whatever location it currently occupies.
  25872. */
  25873. void cancelAnimation (Component* component,
  25874. bool moveComponentToItsFinalPosition);
  25875. /** Clears all of the active animations.
  25876. If moveComponentsToTheirFinalPositions is true, all the components will
  25877. be immediately set to their final positions. If false, they will be
  25878. left in whatever locations they currently occupy.
  25879. */
  25880. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  25881. /** Returns the destination position for a component.
  25882. If the component is being animated, this will return the target position that
  25883. was specified when animateComponent() was called.
  25884. If the specified component isn't currently being animated, this method will just
  25885. return its current position.
  25886. */
  25887. const Rectangle<int> getComponentDestination (Component* component);
  25888. /** Returns true if the specified component is currently being animated. */
  25889. bool isAnimating (Component* component) const;
  25890. private:
  25891. class AnimationTask;
  25892. OwnedArray <AnimationTask> tasks;
  25893. uint32 lastTime;
  25894. AnimationTask* findTaskFor (Component* component) const;
  25895. void timerCallback();
  25896. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  25897. };
  25898. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25899. /*** End of inlined file: juce_ComponentAnimator.h ***/
  25900. class MouseInputSource;
  25901. class MouseInputSourceInternal;
  25902. class MouseListener;
  25903. /**
  25904. Classes can implement this interface and register themselves with the Desktop class
  25905. to receive callbacks when the currently focused component changes.
  25906. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  25907. */
  25908. class JUCE_API FocusChangeListener
  25909. {
  25910. public:
  25911. /** Destructor. */
  25912. virtual ~FocusChangeListener() {}
  25913. /** Callback to indicate that the currently focused component has changed. */
  25914. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  25915. };
  25916. /**
  25917. Describes and controls aspects of the computer's desktop.
  25918. */
  25919. class JUCE_API Desktop : private DeletedAtShutdown,
  25920. private Timer,
  25921. private AsyncUpdater
  25922. {
  25923. public:
  25924. /** There's only one dektop object, and this method will return it.
  25925. */
  25926. static Desktop& JUCE_CALLTYPE getInstance();
  25927. /** Returns a list of the positions of all the monitors available.
  25928. The first rectangle in the list will be the main monitor area.
  25929. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25930. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25931. */
  25932. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const;
  25933. /** Returns the position and size of the main monitor.
  25934. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25935. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25936. */
  25937. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const noexcept;
  25938. /** Returns the position and size of the monitor which contains this co-ordinate.
  25939. If none of the monitors contains the point, this will just return the
  25940. main monitor.
  25941. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25942. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25943. */
  25944. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  25945. /** Returns the mouse position.
  25946. The co-ordinates are relative to the top-left of the main monitor.
  25947. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  25948. you should only resort to grabbing the global mouse position if there's really no
  25949. way to get the coordinates via a mouse event callback instead.
  25950. */
  25951. static const Point<int> getMousePosition();
  25952. /** Makes the mouse pointer jump to a given location.
  25953. The co-ordinates are relative to the top-left of the main monitor.
  25954. */
  25955. static void setMousePosition (const Point<int>& newPosition);
  25956. /** Returns the last position at which a mouse button was pressed.
  25957. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  25958. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  25959. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  25960. if possible, and only ever call this as a last resort.
  25961. */
  25962. static const Point<int> getLastMouseDownPosition();
  25963. /** Returns the number of times the mouse button has been clicked since the
  25964. app started.
  25965. Each mouse-down event increments this number by 1.
  25966. */
  25967. static int getMouseButtonClickCounter();
  25968. /** This lets you prevent the screensaver from becoming active.
  25969. Handy if you're running some sort of presentation app where having a screensaver
  25970. appear would be annoying.
  25971. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  25972. won't enable a screensaver unless the user has actually set one up).
  25973. The disablement will only happen while the Juce application is the foreground
  25974. process - if another task is running in front of it, then the screensaver will
  25975. be unaffected.
  25976. @see isScreenSaverEnabled
  25977. */
  25978. static void setScreenSaverEnabled (bool isEnabled);
  25979. /** Returns true if the screensaver has not been turned off.
  25980. This will return the last value passed into setScreenSaverEnabled(). Note that
  25981. it won't tell you whether the user is actually using a screen saver, just
  25982. whether this app is deliberately preventing one from running.
  25983. @see setScreenSaverEnabled
  25984. */
  25985. static bool isScreenSaverEnabled();
  25986. /** Registers a MouseListener that will receive all mouse events that occur on
  25987. any component.
  25988. @see removeGlobalMouseListener
  25989. */
  25990. void addGlobalMouseListener (MouseListener* listener);
  25991. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  25992. method.
  25993. @see addGlobalMouseListener
  25994. */
  25995. void removeGlobalMouseListener (MouseListener* listener);
  25996. /** Registers a MouseListener that will receive a callback whenever the focused
  25997. component changes.
  25998. */
  25999. void addFocusChangeListener (FocusChangeListener* listener);
  26000. /** Unregisters a listener that was added with addFocusChangeListener(). */
  26001. void removeFocusChangeListener (FocusChangeListener* listener);
  26002. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  26003. The component must already be on the desktop for this method to work. It will
  26004. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  26005. etc will be hidden.
  26006. To exit kiosk mode, just call setKioskModeComponent (nullptr). When this is called,
  26007. the component that's currently being used will be resized back to the size
  26008. and position it was in before being put into this mode.
  26009. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  26010. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  26011. to hide as much on-screen paraphenalia as possible.
  26012. */
  26013. void setKioskModeComponent (Component* componentToUse,
  26014. bool allowMenusAndBars = true);
  26015. /** Returns the component that is currently being used in kiosk-mode.
  26016. This is the component that was last set by setKioskModeComponent(). If none
  26017. has been set, this returns 0.
  26018. */
  26019. Component* getKioskModeComponent() const noexcept { return kioskModeComponent; }
  26020. /** Returns the number of components that are currently active as top-level
  26021. desktop windows.
  26022. @see getComponent, Component::addToDesktop
  26023. */
  26024. int getNumComponents() const noexcept;
  26025. /** Returns one of the top-level desktop window components.
  26026. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  26027. index is out-of-range.
  26028. @see getNumComponents, Component::addToDesktop
  26029. */
  26030. Component* getComponent (int index) const noexcept;
  26031. /** Finds the component at a given screen location.
  26032. This will drill down into top-level windows to find the child component at
  26033. the given position.
  26034. Returns 0 if the co-ordinates are inside a non-Juce window.
  26035. */
  26036. Component* findComponentAt (const Point<int>& screenPosition) const;
  26037. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  26038. your animations.
  26039. Having a single shared ComponentAnimator object makes it more efficient when multiple
  26040. components are being moved around simultaneously. It's also more convenient than having
  26041. to manage your own instance of one.
  26042. @see ComponentAnimator
  26043. */
  26044. ComponentAnimator& getAnimator() noexcept { return animator; }
  26045. /** Returns the number of MouseInputSource objects the system has at its disposal.
  26046. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26047. system, there could be one input source per potential finger.
  26048. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  26049. @see getMouseSource
  26050. */
  26051. int getNumMouseSources() const noexcept { return mouseSources.size(); }
  26052. /** Returns one of the system's MouseInputSource objects.
  26053. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  26054. a null pointer.
  26055. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26056. system, there could be one input source per potential finger.
  26057. */
  26058. MouseInputSource* getMouseSource (int index) const noexcept { return mouseSources [index]; }
  26059. /** Returns the main mouse input device that the system is using.
  26060. @see getNumMouseSources()
  26061. */
  26062. MouseInputSource& getMainMouseSource() const noexcept { return *mouseSources.getUnchecked(0); }
  26063. /** Returns the number of mouse-sources that are currently being dragged.
  26064. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  26065. juce component has the button down on it. In a multi-touch system, this could
  26066. be any number from 0 to the number of simultaneous touches that can be detected.
  26067. */
  26068. int getNumDraggingMouseSources() const noexcept;
  26069. /** Returns one of the mouse sources that's currently being dragged.
  26070. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  26071. out of range, or if no mice or fingers are down, this will return a null pointer.
  26072. */
  26073. MouseInputSource* getDraggingMouseSource (int index) const noexcept;
  26074. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  26075. current mouse-drag operation.
  26076. This allows you to make sure that mouseDrag() events are sent continuously, even
  26077. when the mouse isn't moving. This can be useful for things like auto-scrolling
  26078. components when the mouse is near an edge.
  26079. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  26080. minimum interval between consecutive mouse drag callbacks. The callbacks
  26081. will continue until the mouse is released, and then the interval will be reset,
  26082. so you need to make sure it's called every time you begin a drag event.
  26083. Passing an interval of 0 or less will cancel the auto-repeat.
  26084. @see mouseDrag
  26085. */
  26086. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  26087. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  26088. enum DisplayOrientation
  26089. {
  26090. upright = 1, /**< Indicates that the display is the normal way up. */
  26091. upsideDown = 2, /**< Indicates that the display is upside-down. */
  26092. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  26093. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  26094. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  26095. };
  26096. /** In a tablet device which can be turned around, this returns the current orientation. */
  26097. DisplayOrientation getCurrentOrientation() const;
  26098. /** Sets which orientations the display is allowed to auto-rotate to.
  26099. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  26100. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  26101. set bit.
  26102. */
  26103. void setOrientationsEnabled (int allowedOrientations);
  26104. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  26105. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  26106. */
  26107. bool isOrientationEnabled (DisplayOrientation orientation) const noexcept;
  26108. /** Tells this object to refresh its idea of what the screen resolution is.
  26109. (Called internally by the native code).
  26110. */
  26111. void refreshMonitorSizes();
  26112. /** True if the OS supports semitransparent windows */
  26113. static bool canUseSemiTransparentWindows() noexcept;
  26114. private:
  26115. static Desktop* instance;
  26116. friend class Component;
  26117. friend class ComponentPeer;
  26118. friend class MouseInputSource;
  26119. friend class MouseInputSourceInternal;
  26120. friend class DeletedAtShutdown;
  26121. friend class TopLevelWindowManager;
  26122. OwnedArray <MouseInputSource> mouseSources;
  26123. void createMouseInputSources();
  26124. ListenerList <MouseListener> mouseListeners;
  26125. ListenerList <FocusChangeListener> focusListeners;
  26126. Array <Component*> desktopComponents;
  26127. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  26128. Point<int> lastFakeMouseMove;
  26129. void sendMouseMove();
  26130. int mouseClickCounter;
  26131. void incrementMouseClickCounter() noexcept;
  26132. ScopedPointer<Timer> dragRepeater;
  26133. Component* kioskModeComponent;
  26134. Rectangle<int> kioskComponentOriginalBounds;
  26135. int allowedOrientations;
  26136. ComponentAnimator animator;
  26137. void timerCallback();
  26138. void resetTimer();
  26139. int getNumDisplayMonitors() const noexcept;
  26140. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const noexcept;
  26141. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  26142. void addDesktopComponent (Component* c);
  26143. void removeDesktopComponent (Component* c);
  26144. void componentBroughtToFront (Component* c);
  26145. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  26146. void triggerFocusCallback();
  26147. void handleAsyncUpdate();
  26148. Desktop();
  26149. ~Desktop();
  26150. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  26151. };
  26152. #endif // __JUCE_DESKTOP_JUCEHEADER__
  26153. /*** End of inlined file: juce_Desktop.h ***/
  26154. class KeyPressMappingSet;
  26155. class ApplicationCommandManagerListener;
  26156. /**
  26157. One of these objects holds a list of all the commands your app can perform,
  26158. and despatches these commands when needed.
  26159. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  26160. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  26161. to invoke automatically, which means you don't have to handle the result of a menu
  26162. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  26163. which can choose which events they want to handle.
  26164. This architecture also allows for nested ApplicationCommandTargets, so that for example
  26165. you could have two different objects, one inside the other, both of which can respond to
  26166. a "delete" command. Depending on which one has focus, the command will be sent to the
  26167. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  26168. method.
  26169. To set up your app to use commands, you'll need to do the following:
  26170. - Create a global ApplicationCommandManager to hold the list of all possible
  26171. commands. (This will also manage a set of key-mappings for them).
  26172. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  26173. This allows the object to provide a list of commands that it can perform, and
  26174. to handle them.
  26175. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  26176. or ApplicationCommandManager::registerCommand().
  26177. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  26178. method to access the key-mapper object, which you will need to register as a key-listener
  26179. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  26180. about setting this up.
  26181. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  26182. cause these commands to be invoked automatically.
  26183. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  26184. When a command is invoked, the ApplicationCommandManager will try to choose the best
  26185. ApplicationCommandTarget to receive the specified command. To do this it will use the
  26186. current keyboard focus to see which component might be interested, and will search the
  26187. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  26188. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  26189. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  26190. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  26191. point if the command still hasn't been performed, it will be passed to the current
  26192. JUCEApplication object (which is itself an ApplicationCommandTarget).
  26193. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  26194. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  26195. the object yourself.
  26196. @see ApplicationCommandTarget, ApplicationCommandInfo
  26197. */
  26198. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  26199. private FocusChangeListener
  26200. {
  26201. public:
  26202. /** Creates an ApplicationCommandManager.
  26203. Once created, you'll need to register all your app's commands with it, using
  26204. ApplicationCommandManager::registerAllCommandsForTarget() or
  26205. ApplicationCommandManager::registerCommand().
  26206. */
  26207. ApplicationCommandManager();
  26208. /** Destructor.
  26209. Make sure that you don't delete this if pointers to it are still being used by
  26210. objects such as PopupMenus or Buttons.
  26211. */
  26212. virtual ~ApplicationCommandManager();
  26213. /** Clears the current list of all commands.
  26214. Note that this will also clear the contents of the KeyPressMappingSet.
  26215. */
  26216. void clearCommands();
  26217. /** Adds a command to the list of registered commands.
  26218. @see registerAllCommandsForTarget
  26219. */
  26220. void registerCommand (const ApplicationCommandInfo& newCommand);
  26221. /** Adds all the commands that this target publishes to the manager's list.
  26222. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  26223. to get details about all the commands that this target can do, and will call
  26224. registerCommand() to add each one to the manger's list.
  26225. @see registerCommand
  26226. */
  26227. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  26228. /** Removes the command with a specified ID.
  26229. Note that this will also remove any key mappings that are mapped to the command.
  26230. */
  26231. void removeCommand (CommandID commandID);
  26232. /** This should be called to tell the manager that one of its registered commands may have changed
  26233. its active status.
  26234. Because the command manager only finds out whether a command is active or inactive by querying
  26235. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  26236. allows things like buttons to update their enablement, etc.
  26237. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  26238. for any registered listeners.
  26239. */
  26240. void commandStatusChanged();
  26241. /** Returns the number of commands that have been registered.
  26242. @see registerCommand
  26243. */
  26244. int getNumCommands() const noexcept { return commands.size(); }
  26245. /** Returns the details about one of the registered commands.
  26246. The index is between 0 and (getNumCommands() - 1).
  26247. */
  26248. const ApplicationCommandInfo* getCommandForIndex (int index) const noexcept { return commands [index]; }
  26249. /** Returns the details about a given command ID.
  26250. This will search the list of registered commands for one with the given command
  26251. ID number, and return its associated info. If no matching command is found, this
  26252. will return 0.
  26253. */
  26254. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const noexcept;
  26255. /** Returns the name field for a command.
  26256. An empty string is returned if no command with this ID has been registered.
  26257. @see getDescriptionOfCommand
  26258. */
  26259. const String getNameOfCommand (CommandID commandID) const noexcept;
  26260. /** Returns the description field for a command.
  26261. An empty string is returned if no command with this ID has been registered. If the
  26262. command has no description, this will return its short name field instead.
  26263. @see getNameOfCommand
  26264. */
  26265. const String getDescriptionOfCommand (CommandID commandID) const noexcept;
  26266. /** Returns the list of categories.
  26267. This will go through all registered commands, and return a list of all the distict
  26268. categoryName values from their ApplicationCommandInfo structure.
  26269. @see getCommandsInCategory()
  26270. */
  26271. const StringArray getCommandCategories() const;
  26272. /** Returns a list of all the command UIDs in a particular category.
  26273. @see getCommandCategories()
  26274. */
  26275. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  26276. /** Returns the manager's internal set of key mappings.
  26277. This object can be used to edit the keypresses. To actually link this object up
  26278. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  26279. class.
  26280. @see KeyPressMappingSet
  26281. */
  26282. KeyPressMappingSet* getKeyMappings() const noexcept { return keyMappings; }
  26283. /** Invokes the given command directly, sending it to the default target.
  26284. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  26285. structure.
  26286. */
  26287. bool invokeDirectly (CommandID commandID, bool asynchronously);
  26288. /** Sends a command to the default target.
  26289. This will choose a target using getFirstCommandTarget(), and send the specified command
  26290. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  26291. first target can't handle the command, it will be passed on to targets further down the
  26292. chain (see ApplicationCommandTarget::invoke() for more info).
  26293. @param invocationInfo this must be correctly filled-in, describing the context for
  26294. the invocation.
  26295. @param asynchronously if false, the command will be performed before this method returns.
  26296. If true, a message will be posted so that the command will be performed
  26297. later on the message thread, and this method will return immediately.
  26298. @see ApplicationCommandTarget::invoke
  26299. */
  26300. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  26301. bool asynchronously);
  26302. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  26303. Whenever the manager needs to know which target a command should be sent to, it calls
  26304. this method to determine the first one to try.
  26305. By default, this method will return the target that was set by calling setFirstCommandTarget().
  26306. If no target is set, it will return the result of findDefaultComponentTarget().
  26307. If you need to make sure all commands go via your own custom target, then you can
  26308. either use setFirstCommandTarget() to specify a single target, or override this method
  26309. if you need more complex logic to choose one.
  26310. It may return 0 if no targets are available.
  26311. @see getTargetForCommand, invoke, invokeDirectly
  26312. */
  26313. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  26314. /** Sets a target to be returned by getFirstCommandTarget().
  26315. If this is set to 0, then getFirstCommandTarget() will by default return the
  26316. result of findDefaultComponentTarget().
  26317. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  26318. deleting the target object.
  26319. */
  26320. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) noexcept;
  26321. /** Tries to find the best target to use to perform a given command.
  26322. This will call getFirstCommandTarget() to find the preferred target, and will
  26323. check whether that target can handle the given command. If it can't, then it'll use
  26324. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  26325. so on until no more are available.
  26326. If no targets are found that can perform the command, this method will return 0.
  26327. If a target is found, then it will get the target to fill-in the upToDateInfo
  26328. structure with the latest info about that command, so that the caller can see
  26329. whether the command is disabled, ticked, etc.
  26330. */
  26331. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  26332. ApplicationCommandInfo& upToDateInfo);
  26333. /** Registers a listener that will be called when various events occur. */
  26334. void addListener (ApplicationCommandManagerListener* listener);
  26335. /** Deregisters a previously-added listener. */
  26336. void removeListener (ApplicationCommandManagerListener* listener);
  26337. /** Looks for a suitable command target based on which Components have the keyboard focus.
  26338. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  26339. but is exposed here in case it's useful.
  26340. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  26341. windows, etc., and using the findTargetForComponent() method.
  26342. */
  26343. static ApplicationCommandTarget* findDefaultComponentTarget();
  26344. /** Examines this component and all its parents in turn, looking for the first one
  26345. which is a ApplicationCommandTarget.
  26346. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  26347. that class.
  26348. */
  26349. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  26350. private:
  26351. OwnedArray <ApplicationCommandInfo> commands;
  26352. ListenerList <ApplicationCommandManagerListener> listeners;
  26353. ScopedPointer <KeyPressMappingSet> keyMappings;
  26354. ApplicationCommandTarget* firstTarget;
  26355. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  26356. void handleAsyncUpdate();
  26357. void globalFocusChanged (Component*);
  26358. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  26359. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  26360. // version of this method.
  26361. virtual short getFirstCommandTarget() { return 0; }
  26362. #endif
  26363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  26364. };
  26365. /**
  26366. A listener that receives callbacks from an ApplicationCommandManager when
  26367. commands are invoked or the command list is changed.
  26368. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  26369. */
  26370. class JUCE_API ApplicationCommandManagerListener
  26371. {
  26372. public:
  26373. /** Destructor. */
  26374. virtual ~ApplicationCommandManagerListener() {}
  26375. /** Called when an app command is about to be invoked. */
  26376. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  26377. /** Called when commands are registered or deregistered from the
  26378. command manager, or when commands are made active or inactive.
  26379. Note that if you're using this to watch for changes to whether a command is disabled,
  26380. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  26381. whenever the status of your command might have changed.
  26382. */
  26383. virtual void applicationCommandListChanged() = 0;
  26384. };
  26385. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  26386. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  26387. #endif
  26388. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  26389. #endif
  26390. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26391. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  26392. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26393. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26394. /*** Start of inlined file: juce_PropertiesFile.h ***/
  26395. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  26396. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  26397. /** Wrapper on a file that stores a list of key/value data pairs.
  26398. Useful for storing application settings, etc. See the PropertySet class for
  26399. the interfaces that read and write values.
  26400. Not designed for very large amounts of data, as it keeps all the values in
  26401. memory and writes them out to disk lazily when they are changed.
  26402. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  26403. with it, and these will be signalled when a value changes.
  26404. @see PropertySet
  26405. */
  26406. class JUCE_API PropertiesFile : public PropertySet,
  26407. public ChangeBroadcaster,
  26408. private Timer
  26409. {
  26410. public:
  26411. enum FileFormatOptions
  26412. {
  26413. ignoreCaseOfKeyNames = 1,
  26414. storeAsBinary = 2,
  26415. storeAsCompressedBinary = 4,
  26416. storeAsXML = 8
  26417. };
  26418. /**
  26419. Creates a PropertiesFile object.
  26420. @param file the file to use
  26421. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  26422. is changed, the object will wait for this amount
  26423. of time and then save the file. If zero, the file
  26424. will be written to disk immediately on being changed
  26425. (which might be slow, as it'll re-write synchronously
  26426. each time a value-change method is called). If it is
  26427. less than zero, the file won't be saved until
  26428. save() or saveIfNeeded() are explicitly called.
  26429. @param optionFlags a combination of the flags in the FileFormatOptions
  26430. enum, which specify the type of file to save, and other
  26431. options.
  26432. @param processLock an optional InterprocessLock object that will be used to
  26433. prevent multiple threads or processes from writing to the file
  26434. at the same time. The PropertiesFile will keep a pointer to
  26435. this object but will not take ownership of it - the caller is
  26436. responsible for making sure that the lock doesn't get deleted
  26437. before the PropertiesFile has been deleted.
  26438. */
  26439. PropertiesFile (const File& file,
  26440. int millisecondsBeforeSaving,
  26441. int optionFlags,
  26442. InterProcessLock* processLock = nullptr);
  26443. /** Destructor.
  26444. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  26445. */
  26446. ~PropertiesFile();
  26447. /** Returns true if this file was created from a valid (or non-existent) file.
  26448. If the file failed to load correctly because it was corrupt or had insufficient
  26449. access, this will be false.
  26450. */
  26451. bool isValidFile() const noexcept { return loadedOk; }
  26452. /** This will flush all the values to disk if they've changed since the last
  26453. time they were saved.
  26454. Returns false if it fails to write to the file for some reason (maybe because
  26455. it's read-only or the directory doesn't exist or something).
  26456. @see save
  26457. */
  26458. bool saveIfNeeded();
  26459. /** This will force a write-to-disk of the current values, regardless of whether
  26460. anything has changed since the last save.
  26461. Returns false if it fails to write to the file for some reason (maybe because
  26462. it's read-only or the directory doesn't exist or something).
  26463. @see saveIfNeeded
  26464. */
  26465. bool save();
  26466. /** Returns true if the properties have been altered since the last time they were saved.
  26467. The file is flagged as needing to be saved when you change a value, but you can
  26468. explicitly set this flag with setNeedsToBeSaved().
  26469. */
  26470. bool needsToBeSaved() const;
  26471. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  26472. @see needsToBeSaved
  26473. */
  26474. void setNeedsToBeSaved (bool needsToBeSaved);
  26475. /** Returns the file that's being used. */
  26476. const File getFile() const { return file; }
  26477. /** Handy utility to create a properties file in whatever the standard OS-specific
  26478. location is for these things.
  26479. This uses getDefaultAppSettingsFile() to decide what file to create, then
  26480. creates a PropertiesFile object with the specified properties. See
  26481. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  26482. what the parameters do.
  26483. @see getDefaultAppSettingsFile
  26484. */
  26485. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  26486. const String& fileNameSuffix,
  26487. const String& folderName,
  26488. bool commonToAllUsers,
  26489. int millisecondsBeforeSaving,
  26490. int propertiesFileOptions,
  26491. InterProcessLock* processLock = nullptr);
  26492. /** Handy utility to choose a file in the standard OS-dependent location for application
  26493. settings files.
  26494. So on a Mac, this will return a file called:
  26495. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  26496. On Windows it'll return something like:
  26497. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  26498. On Linux it'll return
  26499. ~/.[folderName]/[applicationName].[fileNameSuffix]
  26500. If you pass an empty string as the folder name, it'll use the app name for this (or
  26501. omit the folder name on the Mac).
  26502. If commonToAllUsers is true, then this will return the same file for all users of the
  26503. computer, regardless of the current user. If it is false, the file will be specific to
  26504. only the current user. Use this to choose whether you're saving settings that are common
  26505. or user-specific.
  26506. */
  26507. static const File getDefaultAppSettingsFile (const String& applicationName,
  26508. const String& fileNameSuffix,
  26509. const String& folderName,
  26510. bool commonToAllUsers);
  26511. protected:
  26512. virtual void propertyChanged();
  26513. private:
  26514. File file;
  26515. int timerInterval;
  26516. const int options;
  26517. bool loadedOk, needsWriting;
  26518. InterProcessLock* processLock;
  26519. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  26520. InterProcessLock::ScopedLockType* createProcessLock() const;
  26521. void timerCallback();
  26522. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  26523. };
  26524. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  26525. /*** End of inlined file: juce_PropertiesFile.h ***/
  26526. /**
  26527. Manages a collection of properties.
  26528. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  26529. as a singleton.
  26530. It holds two different PropertiesFile objects internally, one for user-specific
  26531. settings (stored in your user directory), and one for settings that are common to
  26532. all users (stored in a folder accessible to all users).
  26533. The class manages the creation of these files on-demand, allowing access via the
  26534. getUserSettings() and getCommonSettings() methods. It also has a few handy
  26535. methods like testWriteAccess() to check that the files can be saved.
  26536. If you're using one of these as a singleton, then your app's start-up code should
  26537. first of all call setStorageParameters() to tell it the parameters to use to create
  26538. the properties files.
  26539. @see PropertiesFile
  26540. */
  26541. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26542. {
  26543. public:
  26544. /**
  26545. Creates an ApplicationProperties object.
  26546. Before using it, you must call setStorageParameters() to give it the info
  26547. it needs to create the property files.
  26548. */
  26549. ApplicationProperties();
  26550. /** Destructor. */
  26551. ~ApplicationProperties();
  26552. juce_DeclareSingleton (ApplicationProperties, false)
  26553. /** Gives the object the information it needs to create the appropriate properties files.
  26554. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  26555. info about how these parameters are used.
  26556. */
  26557. void setStorageParameters (const String& applicationName,
  26558. const String& fileNameSuffix,
  26559. const String& folderName,
  26560. int millisecondsBeforeSaving,
  26561. int propertiesFileOptions,
  26562. InterProcessLock* processLock = nullptr);
  26563. /** Tests whether the files can be successfully written to, and can show
  26564. an error message if not.
  26565. Returns true if none of the tests fail.
  26566. @param testUserSettings if true, the user settings file will be tested
  26567. @param testCommonSettings if true, the common settings file will be tested
  26568. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26569. message box if either of the tests fail
  26570. */
  26571. bool testWriteAccess (bool testUserSettings,
  26572. bool testCommonSettings,
  26573. bool showWarningDialogOnFailure);
  26574. /** Returns the user settings file.
  26575. The first time this is called, it will create and load the properties file.
  26576. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26577. the common settings are used as a second-chance place to look. This is done via the
  26578. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26579. to the fallback for the user settings.
  26580. @see getCommonSettings
  26581. */
  26582. PropertiesFile* getUserSettings();
  26583. /** Returns the common settings file.
  26584. The first time this is called, it will create and load the properties file.
  26585. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26586. read-only (e.g. because the user doesn't have permission to write
  26587. to shared files), then this will return the user settings instead,
  26588. (like getUserSettings() would do). This is handy if you'd like to
  26589. write a value to the common settings, but if that's no possible,
  26590. then you'd rather write to the user settings than none at all.
  26591. If returnUserPropsIfReadOnly is false, this method will always return
  26592. the common settings, even if any changes to them can't be saved.
  26593. @see getUserSettings
  26594. */
  26595. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26596. /** Saves both files if they need to be saved.
  26597. @see PropertiesFile::saveIfNeeded
  26598. */
  26599. bool saveIfNeeded();
  26600. /** Flushes and closes both files if they are open.
  26601. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26602. and closes both files. They will then be re-opened the next time getUserSettings()
  26603. or getCommonSettings() is called.
  26604. */
  26605. void closeFiles();
  26606. private:
  26607. ScopedPointer <PropertiesFile> userProps, commonProps;
  26608. String appName, fileSuffix, folderName;
  26609. int msBeforeSaving, options;
  26610. int commonSettingsAreReadOnly;
  26611. InterProcessLock* processLock;
  26612. void openFiles();
  26613. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26614. };
  26615. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26616. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26617. #endif
  26618. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26619. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26620. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26621. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26622. /*** Start of inlined file: juce_AudioFormat.h ***/
  26623. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26624. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26625. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26626. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26627. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26628. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26629. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26630. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26631. /**
  26632. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26633. audio sample format class.
  26634. @see AudioData::Pointer.
  26635. */
  26636. class JUCE_API AudioData
  26637. {
  26638. public:
  26639. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26640. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26641. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26642. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26643. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26644. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26645. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26646. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26647. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26648. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26649. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26650. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26651. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26652. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26653. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26654. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26655. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26656. #ifndef DOXYGEN
  26657. class BigEndian
  26658. {
  26659. public:
  26660. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatBE(); }
  26661. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatBE (newValue); }
  26662. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32BE(); }
  26663. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32BE (newValue); }
  26664. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromBE (source); }
  26665. enum { isBigEndian = 1 };
  26666. };
  26667. class LittleEndian
  26668. {
  26669. public:
  26670. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatLE(); }
  26671. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatLE (newValue); }
  26672. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32LE(); }
  26673. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32LE (newValue); }
  26674. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromLE (source); }
  26675. enum { isBigEndian = 0 };
  26676. };
  26677. #if JUCE_BIG_ENDIAN
  26678. class NativeEndian : public BigEndian {};
  26679. #else
  26680. class NativeEndian : public LittleEndian {};
  26681. #endif
  26682. class Int8
  26683. {
  26684. public:
  26685. inline Int8 (void* data_) noexcept : data (static_cast <int8*> (data_)) {}
  26686. inline void advance() noexcept { ++data; }
  26687. inline void skip (int numSamples) noexcept { data += numSamples; }
  26688. inline float getAsFloatLE() const noexcept { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26689. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26690. inline void setAsFloatLE (float newValue) noexcept { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26691. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26692. inline int32 getAsInt32LE() const noexcept { return (int) (*data << 24); }
  26693. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26694. inline void setAsInt32LE (int newValue) noexcept { *data = (int8) (newValue >> 24); }
  26695. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26696. inline void clear() noexcept { *data = 0; }
  26697. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26698. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26699. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26700. inline void copyFromSameType (Int8& source) noexcept { *data = *source.data; }
  26701. int8* data;
  26702. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26703. };
  26704. class UInt8
  26705. {
  26706. public:
  26707. inline UInt8 (void* data_) noexcept : data (static_cast <uint8*> (data_)) {}
  26708. inline void advance() noexcept { ++data; }
  26709. inline void skip (int numSamples) noexcept { data += numSamples; }
  26710. inline float getAsFloatLE() const noexcept { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26711. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26712. inline void setAsFloatLE (float newValue) noexcept { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26713. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26714. inline int32 getAsInt32LE() const noexcept { return (int) ((*data - 128) << 24); }
  26715. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26716. inline void setAsInt32LE (int newValue) noexcept { *data = (uint8) (128 + (newValue >> 24)); }
  26717. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26718. inline void clear() noexcept { *data = 128; }
  26719. inline void clearMultiple (int num) noexcept { memset (data, 128, num) ;}
  26720. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26721. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26722. inline void copyFromSameType (UInt8& source) noexcept { *data = *source.data; }
  26723. uint8* data;
  26724. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26725. };
  26726. class Int16
  26727. {
  26728. public:
  26729. inline Int16 (void* data_) noexcept : data (static_cast <uint16*> (data_)) {}
  26730. inline void advance() noexcept { ++data; }
  26731. inline void skip (int numSamples) noexcept { data += numSamples; }
  26732. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26733. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26734. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26735. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26736. inline int32 getAsInt32LE() const noexcept { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26737. inline int32 getAsInt32BE() const noexcept { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26738. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26739. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26740. inline void clear() noexcept { *data = 0; }
  26741. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26742. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26743. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26744. inline void copyFromSameType (Int16& source) noexcept { *data = *source.data; }
  26745. uint16* data;
  26746. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26747. };
  26748. class Int24
  26749. {
  26750. public:
  26751. inline Int24 (void* data_) noexcept : data (static_cast <char*> (data_)) {}
  26752. inline void advance() noexcept { data += 3; }
  26753. inline void skip (int numSamples) noexcept { data += 3 * numSamples; }
  26754. inline float getAsFloatLE() const noexcept { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26755. inline float getAsFloatBE() const noexcept { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26756. inline void setAsFloatLE (float newValue) noexcept { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26757. inline void setAsFloatBE (float newValue) noexcept { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26758. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  26759. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  26760. inline void setAsInt32LE (int32 newValue) noexcept { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  26761. inline void setAsInt32BE (int32 newValue) noexcept { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  26762. inline void clear() noexcept { data[0] = 0; data[1] = 0; data[2] = 0; }
  26763. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26764. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26765. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26766. inline void copyFromSameType (Int24& source) noexcept { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  26767. char* data;
  26768. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  26769. };
  26770. class Int32
  26771. {
  26772. public:
  26773. inline Int32 (void* data_) noexcept : data (static_cast <uint32*> (data_)) {}
  26774. inline void advance() noexcept { ++data; }
  26775. inline void skip (int numSamples) noexcept { data += numSamples; }
  26776. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  26777. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  26778. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26779. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26780. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data); }
  26781. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  26782. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  26783. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  26784. inline void clear() noexcept { *data = 0; }
  26785. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26786. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26787. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26788. inline void copyFromSameType (Int32& source) noexcept { *data = *source.data; }
  26789. uint32* data;
  26790. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  26791. };
  26792. class Float32
  26793. {
  26794. public:
  26795. inline Float32 (void* data_) noexcept : data (static_cast <float*> (data_)) {}
  26796. inline void advance() noexcept { ++data; }
  26797. inline void skip (int numSamples) noexcept { data += numSamples; }
  26798. #if JUCE_BIG_ENDIAN
  26799. inline float getAsFloatBE() const noexcept { return *data; }
  26800. inline void setAsFloatBE (float newValue) noexcept { *data = newValue; }
  26801. inline float getAsFloatLE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26802. inline void setAsFloatLE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26803. #else
  26804. inline float getAsFloatLE() const noexcept { return *data; }
  26805. inline void setAsFloatLE (float newValue) noexcept { *data = newValue; }
  26806. inline float getAsFloatBE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26807. inline void setAsFloatBE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26808. #endif
  26809. inline int32 getAsInt32LE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
  26810. inline int32 getAsInt32BE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
  26811. inline void setAsInt32LE (int32 newValue) noexcept { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26812. inline void setAsInt32BE (int32 newValue) noexcept { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26813. inline void clear() noexcept { *data = 0; }
  26814. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26815. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsFloatLE (source.getAsFloat()); }
  26816. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsFloatBE (source.getAsFloat()); }
  26817. inline void copyFromSameType (Float32& source) noexcept { *data = *source.data; }
  26818. float* data;
  26819. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  26820. };
  26821. class NonInterleaved
  26822. {
  26823. public:
  26824. inline NonInterleaved() noexcept {}
  26825. inline NonInterleaved (const NonInterleaved&) noexcept {}
  26826. inline NonInterleaved (const int) noexcept {}
  26827. inline void copyFrom (const NonInterleaved&) noexcept {}
  26828. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.advance(); }
  26829. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numSamples); }
  26830. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { s.clearMultiple (numSamples); }
  26831. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) noexcept { return SampleFormatType::bytesPerSample; }
  26832. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  26833. };
  26834. class Interleaved
  26835. {
  26836. public:
  26837. inline Interleaved() noexcept : numInterleavedChannels (1) {}
  26838. inline Interleaved (const Interleaved& other) noexcept : numInterleavedChannels (other.numInterleavedChannels) {}
  26839. inline Interleaved (const int numInterleavedChannels_) noexcept : numInterleavedChannels (numInterleavedChannels_) {}
  26840. inline void copyFrom (const Interleaved& other) noexcept { numInterleavedChannels = other.numInterleavedChannels; }
  26841. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.skip (numInterleavedChannels); }
  26842. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numInterleavedChannels * numSamples); }
  26843. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  26844. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const noexcept { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  26845. int numInterleavedChannels;
  26846. enum { isInterleavedType = 1 };
  26847. };
  26848. class NonConst
  26849. {
  26850. public:
  26851. typedef void VoidType;
  26852. static inline void* toVoidPtr (VoidType* v) noexcept { return v; }
  26853. enum { isConst = 0 };
  26854. };
  26855. class Const
  26856. {
  26857. public:
  26858. typedef const void VoidType;
  26859. static inline void* toVoidPtr (VoidType* v) noexcept { return const_cast<void*> (v); }
  26860. enum { isConst = 1 };
  26861. };
  26862. #endif
  26863. /**
  26864. A pointer to a block of audio data with a particular encoding.
  26865. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  26866. the audio format as a series of template parameters, e.g.
  26867. @code
  26868. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  26869. AudioData::Pointer <AudioData::Int16,
  26870. AudioData::LittleEndian,
  26871. AudioData::NonInterleaved,
  26872. AudioData::Const> pointer (someRawAudioData);
  26873. // These methods read the sample that is being pointed to
  26874. float firstSampleAsFloat = pointer.getAsFloat();
  26875. int32 firstSampleAsInt = pointer.getAsInt32();
  26876. ++pointer; // moves the pointer to the next sample.
  26877. pointer += 3; // skips the next 3 samples.
  26878. @endcode
  26879. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  26880. converting its format.
  26881. @see AudioData::Converter
  26882. */
  26883. template <typename SampleFormat,
  26884. typename Endianness,
  26885. typename InterleavingType,
  26886. typename Constness>
  26887. class Pointer
  26888. {
  26889. public:
  26890. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  26891. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  26892. for interleaved formats, use the constructor that also takes a number of channels.
  26893. */
  26894. Pointer (typename Constness::VoidType* sourceData) noexcept
  26895. : data (Constness::toVoidPtr (sourceData))
  26896. {
  26897. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  26898. // you should pass NonInterleaved as the template parameter for the interleaving type!
  26899. static_jassert (InterleavingType::isInterleavedType == 0);
  26900. }
  26901. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  26902. For non-interleaved data, use the other constructor.
  26903. */
  26904. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) noexcept
  26905. : data (Constness::toVoidPtr (sourceData)),
  26906. interleaving (numInterleavedChannels)
  26907. {
  26908. }
  26909. /** Creates a copy of another pointer. */
  26910. Pointer (const Pointer& other) noexcept
  26911. : data (other.data),
  26912. interleaving (other.interleaving)
  26913. {
  26914. }
  26915. Pointer& operator= (const Pointer& other) noexcept
  26916. {
  26917. data = other.data;
  26918. interleaving.copyFrom (other.interleaving);
  26919. return *this;
  26920. }
  26921. /** Returns the value of the first sample as a floating point value.
  26922. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  26923. formats, the value could be outside that range, although -1 to 1 is the standard range.
  26924. */
  26925. inline float getAsFloat() const noexcept { return Endianness::getAsFloat (data); }
  26926. /** Sets the value of the first sample as a floating point value.
  26927. (This method can only be used if the AudioData::NonConst option was used).
  26928. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  26929. range will be clipped. For floating point formats, any value passed in here will be
  26930. written directly, although -1 to 1 is the standard range.
  26931. */
  26932. inline void setAsFloat (float newValue) noexcept
  26933. {
  26934. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26935. Endianness::setAsFloat (data, newValue);
  26936. }
  26937. /** Returns the value of the first sample as a 32-bit integer.
  26938. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  26939. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  26940. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  26941. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  26942. */
  26943. inline int32 getAsInt32() const noexcept { return Endianness::getAsInt32 (data); }
  26944. /** Sets the value of the first sample as a 32-bit integer.
  26945. This will be mapped to the range of the format that is being written - see getAsInt32().
  26946. */
  26947. inline void setAsInt32 (int32 newValue) noexcept
  26948. {
  26949. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26950. Endianness::setAsInt32 (data, newValue);
  26951. }
  26952. /** Moves the pointer along to the next sample. */
  26953. inline Pointer& operator++() noexcept { advance(); return *this; }
  26954. /** Moves the pointer back to the previous sample. */
  26955. inline Pointer& operator--() noexcept { interleaving.advanceDataBy (data, -1); return *this; }
  26956. /** Adds a number of samples to the pointer's position. */
  26957. Pointer& operator+= (int samplesToJump) noexcept { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  26958. /** Writes a stream of samples into this pointer from another pointer.
  26959. This will copy the specified number of samples, converting between formats appropriately.
  26960. */
  26961. void convertSamples (Pointer source, int numSamples) const noexcept
  26962. {
  26963. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26964. Pointer dest (*this);
  26965. while (--numSamples >= 0)
  26966. {
  26967. dest.data.copyFromSameType (source.data);
  26968. dest.advance();
  26969. source.advance();
  26970. }
  26971. }
  26972. /** Writes a stream of samples into this pointer from another pointer.
  26973. This will copy the specified number of samples, converting between formats appropriately.
  26974. */
  26975. template <class OtherPointerType>
  26976. void convertSamples (OtherPointerType source, int numSamples) const noexcept
  26977. {
  26978. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26979. Pointer dest (*this);
  26980. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  26981. {
  26982. while (--numSamples >= 0)
  26983. {
  26984. Endianness::copyFrom (dest.data, source);
  26985. dest.advance();
  26986. ++source;
  26987. }
  26988. }
  26989. else // copy backwards if we're increasing the sample width..
  26990. {
  26991. dest += numSamples;
  26992. source += numSamples;
  26993. while (--numSamples >= 0)
  26994. Endianness::copyFrom ((--dest).data, --source);
  26995. }
  26996. }
  26997. /** Sets a number of samples to zero. */
  26998. void clearSamples (int numSamples) const noexcept
  26999. {
  27000. Pointer dest (*this);
  27001. dest.interleaving.clear (dest.data, numSamples);
  27002. }
  27003. /** Returns true if the pointer is using a floating-point format. */
  27004. static bool isFloatingPoint() noexcept { return (bool) SampleFormat::isFloat; }
  27005. /** Returns true if the format is big-endian. */
  27006. static bool isBigEndian() noexcept { return (bool) Endianness::isBigEndian; }
  27007. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  27008. static int getBytesPerSample() noexcept { return (int) SampleFormat::bytesPerSample; }
  27009. /** Returns the number of interleaved channels in the format. */
  27010. int getNumInterleavedChannels() const noexcept { return (int) this->numInterleavedChannels; }
  27011. /** Returns the number of bytes between the start address of each sample. */
  27012. int getNumBytesBetweenSamples() const noexcept { return interleaving.getNumBytesBetweenSamples (data); }
  27013. /** Returns the accuracy of this format when represented as a 32-bit integer.
  27014. This is the smallest number above 0 that can be represented in the sample format, converted to
  27015. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  27016. its resolution is 0x100.
  27017. */
  27018. static int get32BitResolution() noexcept { return (int) SampleFormat::resolution; }
  27019. /** Returns a pointer to the underlying data. */
  27020. const void* getRawData() const noexcept { return data.data; }
  27021. private:
  27022. SampleFormat data;
  27023. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  27024. // advantage of EBCO causes an internal compiler error in VC6..
  27025. inline void advance() noexcept { interleaving.advanceData (data); }
  27026. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  27027. Pointer operator-- (int);
  27028. };
  27029. /** A base class for objects that are used to convert between two different sample formats.
  27030. The AudioData::ConverterInstance implements this base class and can be templated, so
  27031. you can create an instance that converts between two particular formats, and then
  27032. store this in the abstract base class.
  27033. @see AudioData::ConverterInstance
  27034. */
  27035. class Converter
  27036. {
  27037. public:
  27038. virtual ~Converter() {}
  27039. /** Converts a sequence of samples from the converter's source format into the dest format. */
  27040. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  27041. /** Converts a sequence of samples from the converter's source format into the dest format.
  27042. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  27043. particular sub-channel of the data to be used.
  27044. */
  27045. virtual void convertSamples (void* destSamples, int destSubChannel,
  27046. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  27047. };
  27048. /**
  27049. A class that converts between two templated AudioData::Pointer types, and which
  27050. implements the AudioData::Converter interface.
  27051. This can be used as a concrete instance of the AudioData::Converter abstract class.
  27052. @see AudioData::Converter
  27053. */
  27054. template <class SourceSampleType, class DestSampleType>
  27055. class ConverterInstance : public Converter
  27056. {
  27057. public:
  27058. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  27059. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  27060. {}
  27061. ~ConverterInstance() {}
  27062. void convertSamples (void* dest, const void* source, int numSamples) const
  27063. {
  27064. SourceSampleType s (source, sourceChannels);
  27065. DestSampleType d (dest, destChannels);
  27066. d.convertSamples (s, numSamples);
  27067. }
  27068. void convertSamples (void* dest, int destSubChannel,
  27069. const void* source, int sourceSubChannel, int numSamples) const
  27070. {
  27071. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  27072. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  27073. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  27074. d.convertSamples (s, numSamples);
  27075. }
  27076. private:
  27077. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  27078. const int sourceChannels, destChannels;
  27079. };
  27080. };
  27081. /**
  27082. A set of routines to convert buffers of 32-bit floating point data to and from
  27083. various integer formats.
  27084. Note that these functions are deprecated - the AudioData class provides a much more
  27085. flexible set of conversion classes now.
  27086. */
  27087. class JUCE_API AudioDataConverters
  27088. {
  27089. public:
  27090. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27091. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27092. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27093. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27094. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27095. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27096. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27097. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27098. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27099. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27100. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27101. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27102. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27103. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27104. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27105. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27106. enum DataFormat
  27107. {
  27108. int16LE,
  27109. int16BE,
  27110. int24LE,
  27111. int24BE,
  27112. int32LE,
  27113. int32BE,
  27114. float32LE,
  27115. float32BE,
  27116. };
  27117. static void convertFloatToFormat (DataFormat destFormat,
  27118. const float* source, void* dest, int numSamples);
  27119. static void convertFormatToFloat (DataFormat sourceFormat,
  27120. const void* source, float* dest, int numSamples);
  27121. static void interleaveSamples (const float** source, float* dest,
  27122. int numSamples, int numChannels);
  27123. static void deinterleaveSamples (const float* source, float** dest,
  27124. int numSamples, int numChannels);
  27125. private:
  27126. AudioDataConverters();
  27127. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  27128. };
  27129. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27130. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27131. class AudioFormat;
  27132. /**
  27133. Reads samples from an audio file stream.
  27134. A subclass that reads a specific type of audio format will be created by
  27135. an AudioFormat object.
  27136. @see AudioFormat, AudioFormatWriter
  27137. */
  27138. class JUCE_API AudioFormatReader
  27139. {
  27140. protected:
  27141. /** Creates an AudioFormatReader object.
  27142. @param sourceStream the stream to read from - this will be deleted
  27143. by this object when it is no longer needed. (Some
  27144. specialised readers might not use this parameter and
  27145. can leave it as 0).
  27146. @param formatName the description that will be returned by the getFormatName()
  27147. method
  27148. */
  27149. AudioFormatReader (InputStream* sourceStream,
  27150. const String& formatName);
  27151. public:
  27152. /** Destructor. */
  27153. virtual ~AudioFormatReader();
  27154. /** Returns a description of what type of format this is.
  27155. E.g. "AIFF"
  27156. */
  27157. const String getFormatName() const noexcept { return formatName; }
  27158. /** Reads samples from the stream.
  27159. @param destSamples an array of buffers into which the sample data for each
  27160. channel will be written.
  27161. If the format is fixed-point, each channel will be written
  27162. as an array of 32-bit signed integers using the full
  27163. range -0x80000000 to 0x7fffffff, regardless of the source's
  27164. bit-depth. If it is a floating-point format, you should cast
  27165. the resulting array to a (float**) to get the values (in the
  27166. range -1.0 to 1.0 or beyond)
  27167. If the format is stereo, then destSamples[0] is the left channel
  27168. data, and destSamples[1] is the right channel.
  27169. The numDestChannels parameter indicates how many pointers this array
  27170. contains, but some of these pointers can be null if you don't want to
  27171. read data for some of the channels
  27172. @param numDestChannels the number of array elements in the destChannels array
  27173. @param startSampleInSource the position in the audio file or stream at which the samples
  27174. should be read, as a number of samples from the start of the
  27175. stream. It's ok for this to be beyond the start or end of the
  27176. available data - any samples that are out-of-range will be returned
  27177. as zeros.
  27178. @param numSamplesToRead the number of samples to read. If this is greater than the number
  27179. of samples that the file or stream contains. the result will be padded
  27180. with zeros
  27181. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  27182. for some of the channels that you pass in, then they should be filled with
  27183. copies of valid source channels.
  27184. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  27185. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  27186. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  27187. was false, then only the first channel would be filled with the file's contents, and
  27188. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  27189. from a stereo file, then the last 3 would all end up with copies of the same data.
  27190. @returns true if the operation succeeded, false if there was an error. Note
  27191. that reading sections of data beyond the extent of the stream isn't an
  27192. error - the reader should just return zeros for these regions
  27193. @see readMaxLevels
  27194. */
  27195. bool read (int* const* destSamples,
  27196. int numDestChannels,
  27197. int64 startSampleInSource,
  27198. int numSamplesToRead,
  27199. bool fillLeftoverChannelsWithCopies);
  27200. /** Finds the highest and lowest sample levels from a section of the audio stream.
  27201. This will read a block of samples from the stream, and measure the
  27202. highest and lowest sample levels from the channels in that section, returning
  27203. these as normalised floating-point levels.
  27204. @param startSample the offset into the audio stream to start reading from. It's
  27205. ok for this to be beyond the start or end of the stream.
  27206. @param numSamples how many samples to read
  27207. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  27208. @param highestLeft on return, this is the highest absolute sample from the left channel
  27209. @param lowestRight on return, this is the lowest absolute sample from the right
  27210. channel (if there is one)
  27211. @param highestRight on return, this is the highest absolute sample from the right
  27212. channel (if there is one)
  27213. @see read
  27214. */
  27215. virtual void readMaxLevels (int64 startSample,
  27216. int64 numSamples,
  27217. float& lowestLeft,
  27218. float& highestLeft,
  27219. float& lowestRight,
  27220. float& highestRight);
  27221. /** Scans the source looking for a sample whose magnitude is in a specified range.
  27222. This will read from the source, either forwards or backwards between two sample
  27223. positions, until it finds a sample whose magnitude lies between two specified levels.
  27224. If it finds a suitable sample, it returns its position; if not, it will return -1.
  27225. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  27226. points when you're searching for a continuous range of samples
  27227. @param startSample the first sample to look at
  27228. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  27229. the search will go backwards
  27230. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27231. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27232. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  27233. of this many consecutive samples, all of which lie
  27234. within the target range. When it finds such a sequence,
  27235. it returns the position of the first in-range sample
  27236. it found (i.e. the earliest one if scanning forwards, the
  27237. latest one if scanning backwards)
  27238. */
  27239. int64 searchForLevel (int64 startSample,
  27240. int64 numSamplesToSearch,
  27241. double magnitudeRangeMinimum,
  27242. double magnitudeRangeMaximum,
  27243. int minimumConsecutiveSamples);
  27244. /** The sample-rate of the stream. */
  27245. double sampleRate;
  27246. /** The number of bits per sample, e.g. 16, 24, 32. */
  27247. unsigned int bitsPerSample;
  27248. /** The total number of samples in the audio stream. */
  27249. int64 lengthInSamples;
  27250. /** The total number of channels in the audio stream. */
  27251. unsigned int numChannels;
  27252. /** Indicates whether the data is floating-point or fixed. */
  27253. bool usesFloatingPointData;
  27254. /** A set of metadata values that the reader has pulled out of the stream.
  27255. Exactly what these values are depends on the format, so you can
  27256. check out the format implementation code to see what kind of stuff
  27257. they understand.
  27258. */
  27259. StringPairArray metadataValues;
  27260. /** The input stream, for use by subclasses. */
  27261. InputStream* input;
  27262. /** Subclasses must implement this method to perform the low-level read operation.
  27263. Callers should use read() instead of calling this directly.
  27264. @param destSamples the array of destination buffers to fill. Some of these
  27265. pointers may be null
  27266. @param numDestChannels the number of items in the destSamples array. This
  27267. value is guaranteed not to be greater than the number of
  27268. channels that this reader object contains
  27269. @param startOffsetInDestBuffer the number of samples from the start of the
  27270. dest data at which to begin writing
  27271. @param startSampleInFile the number of samples into the source data at which
  27272. to begin reading. This value is guaranteed to be >= 0.
  27273. @param numSamples the number of samples to read
  27274. */
  27275. virtual bool readSamples (int** destSamples,
  27276. int numDestChannels,
  27277. int startOffsetInDestBuffer,
  27278. int64 startSampleInFile,
  27279. int numSamples) = 0;
  27280. protected:
  27281. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  27282. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  27283. struct ReadHelper
  27284. {
  27285. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  27286. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  27287. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) noexcept
  27288. {
  27289. for (int i = 0; i < numDestChannels; ++i)
  27290. {
  27291. if (destData[i] != nullptr)
  27292. {
  27293. DestType dest (destData[i]);
  27294. dest += destOffset;
  27295. if (i < numSourceChannels)
  27296. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  27297. else
  27298. dest.clearSamples (numSamples);
  27299. }
  27300. }
  27301. }
  27302. };
  27303. private:
  27304. String formatName;
  27305. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  27306. };
  27307. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27308. /*** End of inlined file: juce_AudioFormatReader.h ***/
  27309. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  27310. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27311. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27312. /*** Start of inlined file: juce_AudioSource.h ***/
  27313. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27314. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  27315. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  27316. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27317. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27318. class AudioFormatReader;
  27319. class AudioFormatWriter;
  27320. /**
  27321. A multi-channel buffer of 32-bit floating point audio samples.
  27322. */
  27323. class JUCE_API AudioSampleBuffer
  27324. {
  27325. public:
  27326. /** Creates a buffer with a specified number of channels and samples.
  27327. The contents of the buffer will initially be undefined, so use clear() to
  27328. set all the samples to zero.
  27329. The buffer will allocate its memory internally, and this will be released
  27330. when the buffer is deleted.
  27331. */
  27332. AudioSampleBuffer (int numChannels,
  27333. int numSamples) noexcept;
  27334. /** Creates a buffer using a pre-allocated block of memory.
  27335. Note that if the buffer is resized or its number of channels is changed, it
  27336. will re-allocate memory internally and copy the existing data to this new area,
  27337. so it will then stop directly addressing this memory.
  27338. @param dataToReferTo a pre-allocated array containing pointers to the data
  27339. for each channel that should be used by this buffer. The
  27340. buffer will only refer to this memory, it won't try to delete
  27341. it when the buffer is deleted or resized.
  27342. @param numChannels the number of channels to use - this must correspond to the
  27343. number of elements in the array passed in
  27344. @param numSamples the number of samples to use - this must correspond to the
  27345. size of the arrays passed in
  27346. */
  27347. AudioSampleBuffer (float** dataToReferTo,
  27348. int numChannels,
  27349. int numSamples) noexcept;
  27350. /** Creates a buffer using a pre-allocated block of memory.
  27351. Note that if the buffer is resized or its number of channels is changed, it
  27352. will re-allocate memory internally and copy the existing data to this new area,
  27353. so it will then stop directly addressing this memory.
  27354. @param dataToReferTo a pre-allocated array containing pointers to the data
  27355. for each channel that should be used by this buffer. The
  27356. buffer will only refer to this memory, it won't try to delete
  27357. it when the buffer is deleted or resized.
  27358. @param numChannels the number of channels to use - this must correspond to the
  27359. number of elements in the array passed in
  27360. @param startSample the offset within the arrays at which the data begins
  27361. @param numSamples the number of samples to use - this must correspond to the
  27362. size of the arrays passed in
  27363. */
  27364. AudioSampleBuffer (float** dataToReferTo,
  27365. int numChannels,
  27366. int startSample,
  27367. int numSamples) noexcept;
  27368. /** Copies another buffer.
  27369. This buffer will make its own copy of the other's data, unless the buffer was created
  27370. using an external data buffer, in which case boths buffers will just point to the same
  27371. shared block of data.
  27372. */
  27373. AudioSampleBuffer (const AudioSampleBuffer& other) noexcept;
  27374. /** Copies another buffer onto this one.
  27375. This buffer's size will be changed to that of the other buffer.
  27376. */
  27377. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) noexcept;
  27378. /** Destructor.
  27379. This will free any memory allocated by the buffer.
  27380. */
  27381. virtual ~AudioSampleBuffer() noexcept;
  27382. /** Returns the number of channels of audio data that this buffer contains.
  27383. @see getSampleData
  27384. */
  27385. int getNumChannels() const noexcept { return numChannels; }
  27386. /** Returns the number of samples allocated in each of the buffer's channels.
  27387. @see getSampleData
  27388. */
  27389. int getNumSamples() const noexcept { return size; }
  27390. /** Returns a pointer one of the buffer's channels.
  27391. For speed, this doesn't check whether the channel number is out of range,
  27392. so be careful when using it!
  27393. */
  27394. float* getSampleData (const int channelNumber) const noexcept
  27395. {
  27396. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27397. return channels [channelNumber];
  27398. }
  27399. /** Returns a pointer to a sample in one of the buffer's channels.
  27400. For speed, this doesn't check whether the channel and sample number
  27401. are out-of-range, so be careful when using it!
  27402. */
  27403. float* getSampleData (const int channelNumber,
  27404. const int sampleOffset) const noexcept
  27405. {
  27406. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27407. jassert (isPositiveAndBelow (sampleOffset, size));
  27408. return channels [channelNumber] + sampleOffset;
  27409. }
  27410. /** Returns an array of pointers to the channels in the buffer.
  27411. Don't modify any of the pointers that are returned, and bear in mind that
  27412. these will become invalid if the buffer is resized.
  27413. */
  27414. float** getArrayOfChannels() const noexcept { return channels; }
  27415. /** Changes the buffer's size or number of channels.
  27416. This can expand or contract the buffer's length, and add or remove channels.
  27417. If keepExistingContent is true, it will try to preserve as much of the
  27418. old data as it can in the new buffer.
  27419. If clearExtraSpace is true, then any extra channels or space that is
  27420. allocated will be also be cleared. If false, then this space is left
  27421. uninitialised.
  27422. If avoidReallocating is true, then changing the buffer's size won't reduce the
  27423. amount of memory that is currently allocated (but it will still increase it if
  27424. the new size is bigger than the amount it currently has). If this is false, then
  27425. a new allocation will be done so that the buffer uses takes up the minimum amount
  27426. of memory that it needs.
  27427. */
  27428. void setSize (int newNumChannels,
  27429. int newNumSamples,
  27430. bool keepExistingContent = false,
  27431. bool clearExtraSpace = false,
  27432. bool avoidReallocating = false) noexcept;
  27433. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  27434. There's also a constructor that lets you specify arrays like this, but this
  27435. lets you change the channels dynamically.
  27436. Note that if the buffer is resized or its number of channels is changed, it
  27437. will re-allocate memory internally and copy the existing data to this new area,
  27438. so it will then stop directly addressing this memory.
  27439. @param dataToReferTo a pre-allocated array containing pointers to the data
  27440. for each channel that should be used by this buffer. The
  27441. buffer will only refer to this memory, it won't try to delete
  27442. it when the buffer is deleted or resized.
  27443. @param numChannels the number of channels to use - this must correspond to the
  27444. number of elements in the array passed in
  27445. @param numSamples the number of samples to use - this must correspond to the
  27446. size of the arrays passed in
  27447. */
  27448. void setDataToReferTo (float** dataToReferTo,
  27449. int numChannels,
  27450. int numSamples) noexcept;
  27451. /** Clears all the samples in all channels. */
  27452. void clear() noexcept;
  27453. /** Clears a specified region of all the channels.
  27454. For speed, this doesn't check whether the channel and sample number
  27455. are in-range, so be careful!
  27456. */
  27457. void clear (int startSample,
  27458. int numSamples) noexcept;
  27459. /** Clears a specified region of just one channel.
  27460. For speed, this doesn't check whether the channel and sample number
  27461. are in-range, so be careful!
  27462. */
  27463. void clear (int channel,
  27464. int startSample,
  27465. int numSamples) noexcept;
  27466. /** Applies a gain multiple to a region of one channel.
  27467. For speed, this doesn't check whether the channel and sample number
  27468. are in-range, so be careful!
  27469. */
  27470. void applyGain (int channel,
  27471. int startSample,
  27472. int numSamples,
  27473. float gain) noexcept;
  27474. /** Applies a gain multiple to a region of all the channels.
  27475. For speed, this doesn't check whether the sample numbers
  27476. are in-range, so be careful!
  27477. */
  27478. void applyGain (int startSample,
  27479. int numSamples,
  27480. float gain) noexcept;
  27481. /** Applies a range of gains to a region of a channel.
  27482. The gain that is applied to each sample will vary from
  27483. startGain on the first sample to endGain on the last Sample,
  27484. so it can be used to do basic fades.
  27485. For speed, this doesn't check whether the sample numbers
  27486. are in-range, so be careful!
  27487. */
  27488. void applyGainRamp (int channel,
  27489. int startSample,
  27490. int numSamples,
  27491. float startGain,
  27492. float endGain) noexcept;
  27493. /** Adds samples from another buffer to this one.
  27494. @param destChannel the channel within this buffer to add the samples to
  27495. @param destStartSample the start sample within this buffer's channel
  27496. @param source the source buffer to add from
  27497. @param sourceChannel the channel within the source buffer to read from
  27498. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27499. @param numSamples the number of samples to process
  27500. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27501. added to this buffer's samples
  27502. @see copyFrom
  27503. */
  27504. void addFrom (int destChannel,
  27505. int destStartSample,
  27506. const AudioSampleBuffer& source,
  27507. int sourceChannel,
  27508. int sourceStartSample,
  27509. int numSamples,
  27510. float gainToApplyToSource = 1.0f) noexcept;
  27511. /** Adds samples from an array of floats to one of the channels.
  27512. @param destChannel the channel within this buffer to add the samples to
  27513. @param destStartSample the start sample within this buffer's channel
  27514. @param source the source data to use
  27515. @param numSamples the number of samples to process
  27516. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27517. added to this buffer's samples
  27518. @see copyFrom
  27519. */
  27520. void addFrom (int destChannel,
  27521. int destStartSample,
  27522. const float* source,
  27523. int numSamples,
  27524. float gainToApplyToSource = 1.0f) noexcept;
  27525. /** Adds samples from an array of floats, applying a gain ramp to them.
  27526. @param destChannel the channel within this buffer to add the samples to
  27527. @param destStartSample the start sample within this buffer's channel
  27528. @param source the source data to use
  27529. @param numSamples the number of samples to process
  27530. @param startGain the gain to apply to the first sample (this is multiplied with
  27531. the source samples before they are added to this buffer)
  27532. @param endGain the gain to apply to the final sample. The gain is linearly
  27533. interpolated between the first and last samples.
  27534. */
  27535. void addFromWithRamp (int destChannel,
  27536. int destStartSample,
  27537. const float* source,
  27538. int numSamples,
  27539. float startGain,
  27540. float endGain) noexcept;
  27541. /** Copies samples from another buffer to this one.
  27542. @param destChannel the channel within this buffer to copy the samples to
  27543. @param destStartSample the start sample within this buffer's channel
  27544. @param source the source buffer to read from
  27545. @param sourceChannel the channel within the source buffer to read from
  27546. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27547. @param numSamples the number of samples to process
  27548. @see addFrom
  27549. */
  27550. void copyFrom (int destChannel,
  27551. int destStartSample,
  27552. const AudioSampleBuffer& source,
  27553. int sourceChannel,
  27554. int sourceStartSample,
  27555. int numSamples) noexcept;
  27556. /** Copies samples from an array of floats into one of the channels.
  27557. @param destChannel the channel within this buffer to copy the samples to
  27558. @param destStartSample the start sample within this buffer's channel
  27559. @param source the source buffer to read from
  27560. @param numSamples the number of samples to process
  27561. @see addFrom
  27562. */
  27563. void copyFrom (int destChannel,
  27564. int destStartSample,
  27565. const float* source,
  27566. int numSamples) noexcept;
  27567. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27568. @param destChannel the channel within this buffer to copy the samples to
  27569. @param destStartSample the start sample within this buffer's channel
  27570. @param source the source buffer to read from
  27571. @param numSamples the number of samples to process
  27572. @param gain the gain to apply
  27573. @see addFrom
  27574. */
  27575. void copyFrom (int destChannel,
  27576. int destStartSample,
  27577. const float* source,
  27578. int numSamples,
  27579. float gain) noexcept;
  27580. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27581. @param destChannel the channel within this buffer to copy the samples to
  27582. @param destStartSample the start sample within this buffer's channel
  27583. @param source the source buffer to read from
  27584. @param numSamples the number of samples to process
  27585. @param startGain the gain to apply to the first sample (this is multiplied with
  27586. the source samples before they are copied to this buffer)
  27587. @param endGain the gain to apply to the final sample. The gain is linearly
  27588. interpolated between the first and last samples.
  27589. @see addFrom
  27590. */
  27591. void copyFromWithRamp (int destChannel,
  27592. int destStartSample,
  27593. const float* source,
  27594. int numSamples,
  27595. float startGain,
  27596. float endGain) noexcept;
  27597. /** Finds the highest and lowest sample values in a given range.
  27598. @param channel the channel to read from
  27599. @param startSample the start sample within the channel
  27600. @param numSamples the number of samples to check
  27601. @param minVal on return, the lowest value that was found
  27602. @param maxVal on return, the highest value that was found
  27603. */
  27604. void findMinMax (int channel,
  27605. int startSample,
  27606. int numSamples,
  27607. float& minVal,
  27608. float& maxVal) const noexcept;
  27609. /** Finds the highest absolute sample value within a region of a channel.
  27610. */
  27611. float getMagnitude (int channel,
  27612. int startSample,
  27613. int numSamples) const noexcept;
  27614. /** Finds the highest absolute sample value within a region on all channels.
  27615. */
  27616. float getMagnitude (int startSample,
  27617. int numSamples) const noexcept;
  27618. /** Returns the root mean squared level for a region of a channel.
  27619. */
  27620. float getRMSLevel (int channel,
  27621. int startSample,
  27622. int numSamples) const noexcept;
  27623. /** Fills a section of the buffer using an AudioReader as its source.
  27624. This will convert the reader's fixed- or floating-point data to
  27625. the buffer's floating-point format, and will try to intelligently
  27626. cope with mismatches between the number of channels in the reader
  27627. and the buffer.
  27628. @see writeToAudioWriter
  27629. */
  27630. void readFromAudioReader (AudioFormatReader* reader,
  27631. int startSample,
  27632. int numSamples,
  27633. int64 readerStartSample,
  27634. bool useReaderLeftChan,
  27635. bool useReaderRightChan);
  27636. /** Writes a section of this buffer to an audio writer.
  27637. This saves you having to mess about with channels or floating/fixed
  27638. point conversion.
  27639. @see readFromAudioReader
  27640. */
  27641. void writeToAudioWriter (AudioFormatWriter* writer,
  27642. int startSample,
  27643. int numSamples) const;
  27644. private:
  27645. int numChannels, size;
  27646. size_t allocatedBytes;
  27647. float** channels;
  27648. HeapBlock <char> allocatedData;
  27649. float* preallocatedChannelSpace [32];
  27650. void allocateData();
  27651. void allocateChannels (float** dataToReferTo, int offset);
  27652. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27653. };
  27654. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27655. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27656. /**
  27657. Used by AudioSource::getNextAudioBlock().
  27658. */
  27659. struct JUCE_API AudioSourceChannelInfo
  27660. {
  27661. /** The destination buffer to fill with audio data.
  27662. When the AudioSource::getNextAudioBlock() method is called, the active section
  27663. of this buffer should be filled with whatever output the source produces.
  27664. Only the samples specified by the startSample and numSamples members of this structure
  27665. should be affected by the call.
  27666. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27667. method can be treated as the input if the source is performing some kind of filter operation,
  27668. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27669. a handy way of doing this.
  27670. The number of channels in the buffer could be anything, so the AudioSource
  27671. must cope with this in whatever way is appropriate for its function.
  27672. */
  27673. AudioSampleBuffer* buffer;
  27674. /** The first sample in the buffer from which the callback is expected
  27675. to write data. */
  27676. int startSample;
  27677. /** The number of samples in the buffer which the callback is expected to
  27678. fill with data. */
  27679. int numSamples;
  27680. /** Convenient method to clear the buffer if the source is not producing any data. */
  27681. void clearActiveBufferRegion() const
  27682. {
  27683. if (buffer != nullptr)
  27684. buffer->clear (startSample, numSamples);
  27685. }
  27686. };
  27687. /**
  27688. Base class for objects that can produce a continuous stream of audio.
  27689. An AudioSource has two states: 'prepared' and 'unprepared'.
  27690. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27691. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27692. process the audio data.
  27693. Once playback has finished, the releaseResources() method is called to put the stream
  27694. back into an 'unprepared' state.
  27695. @see AudioFormatReaderSource, ResamplingAudioSource
  27696. */
  27697. class JUCE_API AudioSource
  27698. {
  27699. protected:
  27700. /** Creates an AudioSource. */
  27701. AudioSource() noexcept {}
  27702. public:
  27703. /** Destructor. */
  27704. virtual ~AudioSource() {}
  27705. /** Tells the source to prepare for playing.
  27706. An AudioSource has two states: prepared and unprepared.
  27707. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27708. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27709. This callback allows the source to initialise any resources it might need when playing.
  27710. Once playback has finished, the releaseResources() method is called to put the stream
  27711. back into an 'unprepared' state.
  27712. Note that this method could be called more than once in succession without
  27713. a matching call to releaseResources(), so make sure your code is robust and
  27714. can handle that kind of situation.
  27715. @param samplesPerBlockExpected the number of samples that the source
  27716. will be expected to supply each time its
  27717. getNextAudioBlock() method is called. This
  27718. number may vary slightly, because it will be dependent
  27719. on audio hardware callbacks, and these aren't
  27720. guaranteed to always use a constant block size, so
  27721. the source should be able to cope with small variations.
  27722. @param sampleRate the sample rate that the output will be used at - this
  27723. is needed by sources such as tone generators.
  27724. @see releaseResources, getNextAudioBlock
  27725. */
  27726. virtual void prepareToPlay (int samplesPerBlockExpected,
  27727. double sampleRate) = 0;
  27728. /** Allows the source to release anything it no longer needs after playback has stopped.
  27729. This will be called when the source is no longer going to have its getNextAudioBlock()
  27730. method called, so it should release any spare memory, etc. that it might have
  27731. allocated during the prepareToPlay() call.
  27732. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27733. releaseResources(), and it may be called more than once in succession, so make sure your
  27734. code is robust and doesn't make any assumptions about when it will be called.
  27735. @see prepareToPlay, getNextAudioBlock
  27736. */
  27737. virtual void releaseResources() = 0;
  27738. /** Called repeatedly to fetch subsequent blocks of audio data.
  27739. After calling the prepareToPlay() method, this callback will be made each
  27740. time the audio playback hardware (or whatever other destination the audio
  27741. data is going to) needs another block of data.
  27742. It will generally be called on a high-priority system thread, or possibly even
  27743. an interrupt, so be careful not to do too much work here, as that will cause
  27744. audio glitches!
  27745. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27746. */
  27747. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27748. };
  27749. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27750. /*** End of inlined file: juce_AudioSource.h ***/
  27751. class AudioThumbnail;
  27752. /**
  27753. Writes samples to an audio file stream.
  27754. A subclass that writes a specific type of audio format will be created by
  27755. an AudioFormat object.
  27756. After creating one of these with the AudioFormat::createWriterFor() method
  27757. you can call its write() method to store the samples, and then delete it.
  27758. @see AudioFormat, AudioFormatReader
  27759. */
  27760. class JUCE_API AudioFormatWriter
  27761. {
  27762. protected:
  27763. /** Creates an AudioFormatWriter object.
  27764. @param destStream the stream to write to - this will be deleted
  27765. by this object when it is no longer needed
  27766. @param formatName the description that will be returned by the getFormatName()
  27767. method
  27768. @param sampleRate the sample rate to use - the base class just stores
  27769. this value, it doesn't do anything with it
  27770. @param numberOfChannels the number of channels to write - the base class just stores
  27771. this value, it doesn't do anything with it
  27772. @param bitsPerSample the bit depth of the stream - the base class just stores
  27773. this value, it doesn't do anything with it
  27774. */
  27775. AudioFormatWriter (OutputStream* destStream,
  27776. const String& formatName,
  27777. double sampleRate,
  27778. unsigned int numberOfChannels,
  27779. unsigned int bitsPerSample);
  27780. public:
  27781. /** Destructor. */
  27782. virtual ~AudioFormatWriter();
  27783. /** Returns a description of what type of format this is.
  27784. E.g. "AIFF file"
  27785. */
  27786. const String getFormatName() const noexcept { return formatName; }
  27787. /** Writes a set of samples to the audio stream.
  27788. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27789. can use AudioSampleBuffer::writeToAudioWriter().
  27790. @param samplesToWrite an array of arrays containing the sample data for
  27791. each channel to write. This is a zero-terminated
  27792. array of arrays, and can contain a different number
  27793. of channels than the actual stream uses, and the
  27794. writer should do its best to cope with this.
  27795. If the format is fixed-point, each channel will be formatted
  27796. as an array of signed integers using the full 32-bit
  27797. range -0x80000000 to 0x7fffffff, regardless of the source's
  27798. bit-depth. If it is a floating-point format, you should treat
  27799. the arrays as arrays of floats, and just cast it to an (int**)
  27800. to pass it into the method.
  27801. @param numSamples the number of samples to write
  27802. */
  27803. virtual bool write (const int** samplesToWrite,
  27804. int numSamples) = 0;
  27805. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27806. the output.
  27807. This will take care of any floating-point conversion that's required to convert
  27808. between the two formats. It won't deal with sample-rate conversion, though.
  27809. If numSamplesToRead < 0, it will write the entire length of the reader.
  27810. @returns false if it can't read or write properly during the operation
  27811. */
  27812. bool writeFromAudioReader (AudioFormatReader& reader,
  27813. int64 startSample,
  27814. int64 numSamplesToRead);
  27815. /** Reads some samples from an AudioSource, and writes these to the output.
  27816. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27817. @param source the source to read from
  27818. @param numSamplesToRead total number of samples to read and write
  27819. @param samplesPerBlock the maximum number of samples to fetch from the source
  27820. @returns false if it can't read or write properly during the operation
  27821. */
  27822. bool writeFromAudioSource (AudioSource& source,
  27823. int numSamplesToRead,
  27824. int samplesPerBlock = 2048);
  27825. /** Writes some samples from an AudioSampleBuffer.
  27826. */
  27827. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  27828. int startSample, int numSamples);
  27829. /** Returns the sample rate being used. */
  27830. double getSampleRate() const noexcept { return sampleRate; }
  27831. /** Returns the number of channels being written. */
  27832. int getNumChannels() const noexcept { return numChannels; }
  27833. /** Returns the bit-depth of the data being written. */
  27834. int getBitsPerSample() const noexcept { return bitsPerSample; }
  27835. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27836. bool isFloatingPoint() const noexcept { return usesFloatingPointData; }
  27837. /**
  27838. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  27839. data into a buffer which will be flushed to disk by a background thread.
  27840. */
  27841. class ThreadedWriter
  27842. {
  27843. public:
  27844. /** Creates a ThreadedWriter for a given writer and a thread.
  27845. The writer object which is passed in here will be owned and deleted by
  27846. the ThreadedWriter when it is no longer needed.
  27847. To stop the writer and flush the buffer to disk, simply delete this object.
  27848. */
  27849. ThreadedWriter (AudioFormatWriter* writer,
  27850. TimeSliceThread& backgroundThread,
  27851. int numSamplesToBuffer);
  27852. /** Destructor. */
  27853. ~ThreadedWriter();
  27854. /** Pushes some incoming audio data into the FIFO.
  27855. If there's enough free space in the buffer, this will add the data to it,
  27856. If the FIFO is too full to accept this many samples, the method will return
  27857. false - then you could either wait until the background thread has had time to
  27858. consume some of the buffered data and try again, or you can give up
  27859. and lost this block.
  27860. The data must be an array containing the same number of channels as the
  27861. AudioFormatWriter object is using. None of these channels can be null.
  27862. */
  27863. bool write (const float** data, int numSamples);
  27864. /** Allows you to specify a thumbnail that this writer should update with the
  27865. incoming data.
  27866. The thumbnail will be cleared and will the writer will begin adding data to
  27867. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  27868. */
  27869. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  27870. /** @internal */
  27871. class Buffer; // (only public for VC6 compatibility)
  27872. private:
  27873. friend class ScopedPointer<Buffer>;
  27874. ScopedPointer<Buffer> buffer;
  27875. };
  27876. protected:
  27877. /** The sample rate of the stream. */
  27878. double sampleRate;
  27879. /** The number of channels being written to the stream. */
  27880. unsigned int numChannels;
  27881. /** The bit depth of the file. */
  27882. unsigned int bitsPerSample;
  27883. /** True if it's a floating-point format, false if it's fixed-point. */
  27884. bool usesFloatingPointData;
  27885. /** The output stream for Use by subclasses. */
  27886. OutputStream* output;
  27887. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  27888. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  27889. struct WriteHelper
  27890. {
  27891. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  27892. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  27893. static void write (void* destData, int numDestChannels, const int** source,
  27894. int numSamples, const int sourceOffset = 0) noexcept
  27895. {
  27896. for (int i = 0; i < numDestChannels; ++i)
  27897. {
  27898. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  27899. if (*source != nullptr)
  27900. {
  27901. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  27902. ++source;
  27903. }
  27904. else
  27905. {
  27906. dest.clearSamples (numSamples);
  27907. }
  27908. }
  27909. }
  27910. };
  27911. private:
  27912. String formatName;
  27913. friend class ThreadedWriter;
  27914. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  27915. };
  27916. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27917. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  27918. /**
  27919. Subclasses of AudioFormat are used to read and write different audio
  27920. file formats.
  27921. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27922. */
  27923. class JUCE_API AudioFormat
  27924. {
  27925. public:
  27926. /** Destructor. */
  27927. virtual ~AudioFormat();
  27928. /** Returns the name of this format.
  27929. e.g. "WAV file" or "AIFF file"
  27930. */
  27931. const String& getFormatName() const;
  27932. /** Returns all the file extensions that might apply to a file of this format.
  27933. The first item will be the one that's preferred when creating a new file.
  27934. So for a wav file this might just return ".wav"; for an AIFF file it might
  27935. return two items, ".aif" and ".aiff"
  27936. */
  27937. const StringArray& getFileExtensions() const;
  27938. /** Returns true if this the given file can be read by this format.
  27939. Subclasses shouldn't do too much work here, just check the extension or
  27940. file type. The base class implementation just checks the file's extension
  27941. against one of the ones that was registered in the constructor.
  27942. */
  27943. virtual bool canHandleFile (const File& fileToTest);
  27944. /** Returns a set of sample rates that the format can read and write. */
  27945. virtual const Array <int> getPossibleSampleRates() = 0;
  27946. /** Returns a set of bit depths that the format can read and write. */
  27947. virtual const Array <int> getPossibleBitDepths() = 0;
  27948. /** Returns true if the format can do 2-channel audio. */
  27949. virtual bool canDoStereo() = 0;
  27950. /** Returns true if the format can do 1-channel audio. */
  27951. virtual bool canDoMono() = 0;
  27952. /** Returns true if the format uses compressed data. */
  27953. virtual bool isCompressed();
  27954. /** Returns a list of different qualities that can be used when writing.
  27955. Non-compressed formats will just return an empty array, but for something
  27956. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27957. When calling createWriterFor(), an index from this array is passed in to
  27958. tell the format which option is required.
  27959. */
  27960. virtual const StringArray getQualityOptions();
  27961. /** Tries to create an object that can read from a stream containing audio
  27962. data in this format.
  27963. The reader object that is returned can be used to read from the stream, and
  27964. should then be deleted by the caller.
  27965. @param sourceStream the stream to read from - the AudioFormatReader object
  27966. that is returned will delete this stream when it no longer
  27967. needs it.
  27968. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27969. should delete the stream object that was passed-in. (If a valid
  27970. reader is returned, it will always be in charge of deleting the
  27971. stream, so this parameter is ignored)
  27972. @see AudioFormatReader
  27973. */
  27974. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27975. bool deleteStreamIfOpeningFails) = 0;
  27976. /** Tries to create an object that can write to a stream with this audio format.
  27977. The writer object that is returned can be used to write to the stream, and
  27978. should then be deleted by the caller.
  27979. If the stream can't be created for some reason (e.g. the parameters passed in
  27980. here aren't suitable), this will return 0.
  27981. @param streamToWriteTo the stream that the data will go to - this will be
  27982. deleted by the AudioFormatWriter object when it's no longer
  27983. needed. If no AudioFormatWriter can be created by this method,
  27984. the stream will NOT be deleted, so that the caller can re-use it
  27985. to try to open a different format, etc
  27986. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27987. returned by getPossibleSampleRates()
  27988. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27989. the choice will depend on the results of canDoMono() and
  27990. canDoStereo()
  27991. @param bitsPerSample the bits per sample to use - this must be one of the values
  27992. returned by getPossibleBitDepths()
  27993. @param metadataValues a set of metadata values that the writer should try to write
  27994. to the stream. Exactly what these are depends on the format,
  27995. and the subclass doesn't actually have to do anything with
  27996. them if it doesn't want to. Have a look at the specific format
  27997. implementation classes to see possible values that can be
  27998. used
  27999. @param qualityOptionIndex the index of one of compression qualities returned by the
  28000. getQualityOptions() method. If there aren't any quality options
  28001. for this format, just pass 0 in this parameter, as it'll be
  28002. ignored
  28003. @see AudioFormatWriter
  28004. */
  28005. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28006. double sampleRateToUse,
  28007. unsigned int numberOfChannels,
  28008. int bitsPerSample,
  28009. const StringPairArray& metadataValues,
  28010. int qualityOptionIndex) = 0;
  28011. protected:
  28012. /** Creates an AudioFormat object.
  28013. @param formatName this sets the value that will be returned by getFormatName()
  28014. @param fileExtensions a zero-terminated list of file extensions - this is what will
  28015. be returned by getFileExtension()
  28016. */
  28017. AudioFormat (const String& formatName,
  28018. const StringArray& fileExtensions);
  28019. private:
  28020. String formatName;
  28021. StringArray fileExtensions;
  28022. };
  28023. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  28024. /*** End of inlined file: juce_AudioFormat.h ***/
  28025. /**
  28026. Reads and Writes AIFF format audio files.
  28027. @see AudioFormat
  28028. */
  28029. class JUCE_API AiffAudioFormat : public AudioFormat
  28030. {
  28031. public:
  28032. /** Creates an format object. */
  28033. AiffAudioFormat();
  28034. /** Destructor. */
  28035. ~AiffAudioFormat();
  28036. const Array <int> getPossibleSampleRates();
  28037. const Array <int> getPossibleBitDepths();
  28038. bool canDoStereo();
  28039. bool canDoMono();
  28040. #if JUCE_MAC
  28041. bool canHandleFile (const File& fileToTest);
  28042. #endif
  28043. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28044. bool deleteStreamIfOpeningFails);
  28045. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28046. double sampleRateToUse,
  28047. unsigned int numberOfChannels,
  28048. int bitsPerSample,
  28049. const StringPairArray& metadataValues,
  28050. int qualityOptionIndex);
  28051. private:
  28052. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  28053. };
  28054. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28055. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  28056. #endif
  28057. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28058. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  28059. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28060. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28061. #if JUCE_USE_CDBURNER || DOXYGEN
  28062. /**
  28063. */
  28064. class AudioCDBurner : public ChangeBroadcaster
  28065. {
  28066. public:
  28067. /** Returns a list of available optical drives.
  28068. Use openDevice() to open one of the items from this list.
  28069. */
  28070. static const StringArray findAvailableDevices();
  28071. /** Tries to open one of the optical drives.
  28072. The deviceIndex is an index into the array returned by findAvailableDevices().
  28073. */
  28074. static AudioCDBurner* openDevice (const int deviceIndex);
  28075. /** Destructor. */
  28076. ~AudioCDBurner();
  28077. enum DiskState
  28078. {
  28079. unknown, /**< An error condition, if the device isn't responding. */
  28080. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  28081. may seem to be permanently open. */
  28082. noDisc, /**< The drive has no disk in it. */
  28083. writableDiskPresent, /**< The drive contains a writeable disk. */
  28084. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  28085. };
  28086. /** Returns the current status of the device.
  28087. To get informed when the drive's status changes, attach a ChangeListener to
  28088. the AudioCDBurner.
  28089. */
  28090. DiskState getDiskState() const;
  28091. /** Returns true if there's a writable disk in the drive. */
  28092. bool isDiskPresent() const;
  28093. /** Sends an eject signal to the drive.
  28094. The eject will happen asynchronously, so you can use getDiskState() and
  28095. waitUntilStateChange() to monitor its progress.
  28096. */
  28097. bool openTray();
  28098. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  28099. @returns the device's new state
  28100. */
  28101. DiskState waitUntilStateChange (int timeOutMilliseconds);
  28102. /** Returns the set of possible write speeds that the device can handle.
  28103. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  28104. Note that if there's no media present in the drive, this value may be unavailable!
  28105. @see setWriteSpeed, getWriteSpeed
  28106. */
  28107. const Array<int> getAvailableWriteSpeeds() const;
  28108. /** Tries to enable or disable buffer underrun safety on devices that support it.
  28109. @returns true if it's now enabled. If the device doesn't support it, this
  28110. will always return false.
  28111. */
  28112. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  28113. /** Returns the number of free blocks on the disk.
  28114. There are 75 blocks per second, at 44100Hz.
  28115. */
  28116. int getNumAvailableAudioBlocks() const;
  28117. /** Adds a track to be written.
  28118. The source passed-in here will be kept by this object, and it will
  28119. be used and deleted at some point in the future, either during the
  28120. burn() method or when this AudioCDBurner object is deleted. Your caller
  28121. method shouldn't keep a reference to it or use it again after passing
  28122. it in here.
  28123. */
  28124. bool addAudioTrack (AudioSource* source, int numSamples);
  28125. /** Receives progress callbacks during a cd-burn operation.
  28126. @see AudioCDBurner::burn()
  28127. */
  28128. class BurnProgressListener
  28129. {
  28130. public:
  28131. BurnProgressListener() noexcept {}
  28132. virtual ~BurnProgressListener() {}
  28133. /** Called at intervals to report on the progress of the AudioCDBurner.
  28134. To cancel the burn, return true from this method.
  28135. */
  28136. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28137. };
  28138. /** Runs the burn process.
  28139. This method will block until the operation is complete.
  28140. @param listener the object to receive callbacks about progress
  28141. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  28142. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  28143. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  28144. 0 or less to mean the fastest speed.
  28145. */
  28146. const String burn (BurnProgressListener* listener,
  28147. bool ejectDiscAfterwards,
  28148. bool performFakeBurnForTesting,
  28149. int writeSpeed);
  28150. /** If a burn operation is currently in progress, this tells it to stop
  28151. as soon as possible.
  28152. It's also possible to stop the burn process by returning true from
  28153. BurnProgressListener::audioCDBurnProgress()
  28154. */
  28155. void abortBurn();
  28156. private:
  28157. AudioCDBurner (const int deviceIndex);
  28158. class Pimpl;
  28159. friend class ScopedPointer<Pimpl>;
  28160. ScopedPointer<Pimpl> pimpl;
  28161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  28162. };
  28163. #endif
  28164. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28165. /*** End of inlined file: juce_AudioCDBurner.h ***/
  28166. #endif
  28167. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28168. /*** Start of inlined file: juce_AudioCDReader.h ***/
  28169. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28170. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28171. #if JUCE_USE_CDREADER || DOXYGEN
  28172. #if JUCE_MAC
  28173. #endif
  28174. /**
  28175. A type of AudioFormatReader that reads from an audio CD.
  28176. One of these can be used to read a CD as if it's one big audio stream. Use the
  28177. getPositionOfTrackStart() method to find where the individual tracks are
  28178. within the stream.
  28179. @see AudioFormatReader
  28180. */
  28181. class JUCE_API AudioCDReader : public AudioFormatReader
  28182. {
  28183. public:
  28184. /** Returns a list of names of Audio CDs currently available for reading.
  28185. If there's a CD drive but no CD in it, this might return an empty list, or
  28186. possibly a device that can be opened but which has no tracks, depending
  28187. on the platform.
  28188. @see createReaderForCD
  28189. */
  28190. static const StringArray getAvailableCDNames();
  28191. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28192. @param index the index of one of the available CDs - use getAvailableCDNames()
  28193. to find out how many there are.
  28194. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28195. caller will be responsible for deleting the object returned.
  28196. */
  28197. static AudioCDReader* createReaderForCD (const int index);
  28198. /** Destructor. */
  28199. ~AudioCDReader();
  28200. /** Implementation of the AudioFormatReader method. */
  28201. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28202. int64 startSampleInFile, int numSamples);
  28203. /** Checks whether the CD has been removed from the drive.
  28204. */
  28205. bool isCDStillPresent() const;
  28206. /** Returns the total number of tracks (audio + data).
  28207. */
  28208. int getNumTracks() const;
  28209. /** Finds the sample offset of the start of a track.
  28210. @param trackNum the track number, where trackNum = 0 is the first track
  28211. and trackNum = getNumTracks() means the end of the CD.
  28212. */
  28213. int getPositionOfTrackStart (int trackNum) const;
  28214. /** Returns true if a given track is an audio track.
  28215. @param trackNum the track number, where 0 is the first track.
  28216. */
  28217. bool isTrackAudio (int trackNum) const;
  28218. /** Returns an array of sample offsets for the start of each track, followed by
  28219. the sample position of the end of the CD.
  28220. */
  28221. const Array<int>& getTrackOffsets() const;
  28222. /** Refreshes the object's table of contents.
  28223. If the disc has been ejected and a different one put in since this
  28224. object was created, this will cause it to update its idea of how many tracks
  28225. there are, etc.
  28226. */
  28227. void refreshTrackLengths();
  28228. /** Enables scanning for indexes within tracks.
  28229. @see getLastIndex
  28230. */
  28231. void enableIndexScanning (bool enabled);
  28232. /** Returns the index number found during the last read() call.
  28233. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28234. Then when the read() method is called, if it comes across an index within that
  28235. block, the index number is stored and returned by this method.
  28236. Some devices might not support indexes, of course.
  28237. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28238. @see enableIndexScanning
  28239. */
  28240. int getLastIndex() const;
  28241. /** Scans a track to find the position of any indexes within it.
  28242. @param trackNumber the track to look in, where 0 is the first track on the disc
  28243. @returns an array of sample positions of any index points found (not including
  28244. the index that marks the start of the track)
  28245. */
  28246. const Array <int> findIndexesInTrack (const int trackNumber);
  28247. /** Returns the CDDB id number for the CD.
  28248. It's not a great way of identifying a disc, but it's traditional.
  28249. */
  28250. int getCDDBId();
  28251. /** Tries to eject the disk.
  28252. Of course this might not be possible, if some other process is using it.
  28253. */
  28254. void ejectDisk();
  28255. enum
  28256. {
  28257. framesPerSecond = 75,
  28258. samplesPerFrame = 44100 / framesPerSecond
  28259. };
  28260. private:
  28261. Array<int> trackStartSamples;
  28262. #if JUCE_MAC
  28263. File volumeDir;
  28264. Array<File> tracks;
  28265. int currentReaderTrack;
  28266. ScopedPointer <AudioFormatReader> reader;
  28267. AudioCDReader (const File& volume);
  28268. #elif JUCE_WINDOWS
  28269. bool audioTracks [100];
  28270. void* handle;
  28271. bool indexingEnabled;
  28272. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28273. MemoryBlock buffer;
  28274. AudioCDReader (void* handle);
  28275. int getIndexAt (int samplePos);
  28276. #elif JUCE_LINUX
  28277. AudioCDReader();
  28278. #endif
  28279. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  28280. };
  28281. #endif
  28282. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28283. /*** End of inlined file: juce_AudioCDReader.h ***/
  28284. #endif
  28285. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28286. #endif
  28287. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28288. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  28289. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28290. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28291. /**
  28292. A class for keeping a list of available audio formats, and for deciding which
  28293. one to use to open a given file.
  28294. You can either use this class as a singleton object, or create instances of it
  28295. yourself. Once created, use its registerFormat() method to tell it which
  28296. formats it should use.
  28297. @see AudioFormat
  28298. */
  28299. class JUCE_API AudioFormatManager
  28300. {
  28301. public:
  28302. /** Creates an empty format manager.
  28303. Before it'll be any use, you'll need to call registerFormat() with all the
  28304. formats you want it to be able to recognise.
  28305. */
  28306. AudioFormatManager();
  28307. /** Destructor. */
  28308. ~AudioFormatManager();
  28309. /** Adds a format to the manager's list of available file types.
  28310. The object passed-in will be deleted by this object, so don't keep a pointer
  28311. to it!
  28312. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28313. return this one when called.
  28314. */
  28315. void registerFormat (AudioFormat* newFormat,
  28316. bool makeThisTheDefaultFormat);
  28317. /** Handy method to make it easy to register the formats that come with Juce.
  28318. Currently, this will add WAV and AIFF to the list.
  28319. */
  28320. void registerBasicFormats();
  28321. /** Clears the list of known formats. */
  28322. void clearFormats();
  28323. /** Returns the number of currently registered file formats. */
  28324. int getNumKnownFormats() const;
  28325. /** Returns one of the registered file formats. */
  28326. AudioFormat* getKnownFormat (int index) const;
  28327. /** Looks for which of the known formats is listed as being for a given file
  28328. extension.
  28329. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28330. */
  28331. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28332. /** Returns the format which has been set as the default one.
  28333. You can set a format as being the default when it is registered. It's useful
  28334. when you want to write to a file, because the best format may change between
  28335. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28336. If none has been set as the default, this method will just return the first
  28337. one in the list.
  28338. */
  28339. AudioFormat* getDefaultFormat() const;
  28340. /** Returns a set of wildcards for file-matching that contains the extensions for
  28341. all known formats.
  28342. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28343. */
  28344. const String getWildcardForAllFormats() const;
  28345. /** Searches through the known formats to try to create a suitable reader for
  28346. this file.
  28347. If none of the registered formats can open the file, it'll return 0. If it
  28348. returns a reader, it's the caller's responsibility to delete the reader.
  28349. */
  28350. AudioFormatReader* createReaderFor (const File& audioFile);
  28351. /** Searches through the known formats to try to create a suitable reader for
  28352. this stream.
  28353. The stream object that is passed-in will be deleted by this method or by the
  28354. reader that is returned, so the caller should not keep any references to it.
  28355. The stream that is passed-in must be capable of being repositioned so
  28356. that all the formats can have a go at opening it.
  28357. If none of the registered formats can open the stream, it'll return 0. If it
  28358. returns a reader, it's the caller's responsibility to delete the reader.
  28359. */
  28360. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28361. private:
  28362. OwnedArray<AudioFormat> knownFormats;
  28363. int defaultFormatIndex;
  28364. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  28365. };
  28366. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28367. /*** End of inlined file: juce_AudioFormatManager.h ***/
  28368. #endif
  28369. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28370. #endif
  28371. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28372. #endif
  28373. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28374. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  28375. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28376. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28377. /**
  28378. This class is used to wrap an AudioFormatReader and only read from a
  28379. subsection of the file.
  28380. So if you have a reader which can read a 1000 sample file, you could wrap it
  28381. in one of these to only access, e.g. samples 100 to 200, and any samples
  28382. outside that will come back as 0. Accessing sample 0 from this reader will
  28383. actually read the first sample from the other's subsection, which might
  28384. be at a non-zero position.
  28385. @see AudioFormatReader
  28386. */
  28387. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28388. {
  28389. public:
  28390. /** Creates a AudioSubsectionReader for a given data source.
  28391. @param sourceReader the source reader from which we'll be taking data
  28392. @param subsectionStartSample the sample within the source reader which will be
  28393. mapped onto sample 0 for this reader.
  28394. @param subsectionLength the number of samples from the source that will
  28395. make up the subsection. If this reader is asked for
  28396. any samples beyond this region, it will return zero.
  28397. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28398. this object is deleted.
  28399. */
  28400. AudioSubsectionReader (AudioFormatReader* sourceReader,
  28401. int64 subsectionStartSample,
  28402. int64 subsectionLength,
  28403. bool deleteSourceWhenDeleted);
  28404. /** Destructor. */
  28405. ~AudioSubsectionReader();
  28406. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28407. int64 startSampleInFile, int numSamples);
  28408. void readMaxLevels (int64 startSample,
  28409. int64 numSamples,
  28410. float& lowestLeft,
  28411. float& highestLeft,
  28412. float& lowestRight,
  28413. float& highestRight);
  28414. private:
  28415. AudioFormatReader* const source;
  28416. int64 startSample, length;
  28417. const bool deleteSourceWhenDeleted;
  28418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  28419. };
  28420. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28421. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  28422. #endif
  28423. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28424. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  28425. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28426. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28427. class AudioThumbnailCache;
  28428. /**
  28429. Makes it easy to quickly draw scaled views of the waveform shape of an
  28430. audio file.
  28431. To use this class, just create an AudioThumbNail class for the file you want
  28432. to draw, call setSource to tell it which file or resource to use, then call
  28433. drawChannel() to draw it.
  28434. The class will asynchronously scan the wavefile to create its scaled-down view,
  28435. so you should make your UI repaint itself as this data comes in. To do this, the
  28436. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28437. listeners should repaint themselves.
  28438. The thumbnail stores an internal low-res version of the wave data, and this can
  28439. be loaded and saved to avoid having to scan the file again.
  28440. @see AudioThumbnailCache
  28441. */
  28442. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  28443. {
  28444. public:
  28445. /** Creates an audio thumbnail.
  28446. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28447. of the audio data, this is the scale at which it should be done. (This
  28448. number is the number of original samples that will be averaged for each
  28449. low-res sample)
  28450. @param formatManagerToUse the audio format manager that is used to open the file
  28451. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28452. thread and storage that is used to by the thumbnail, and the cache
  28453. object can be shared between multiple thumbnails
  28454. */
  28455. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  28456. AudioFormatManager& formatManagerToUse,
  28457. AudioThumbnailCache& cacheToUse);
  28458. /** Destructor. */
  28459. ~AudioThumbnail();
  28460. /** Clears and resets the thumbnail. */
  28461. void clear();
  28462. /** Specifies the file or stream that contains the audio file.
  28463. For a file, just call
  28464. @code
  28465. setSource (new FileInputSource (file))
  28466. @endcode
  28467. You can pass a zero in here to clear the thumbnail.
  28468. The source that is passed in will be deleted by this object when it is no longer needed.
  28469. @returns true if the source could be opened as a valid audio file, false if this failed for
  28470. some reason.
  28471. */
  28472. bool setSource (InputSource* newSource);
  28473. /** Gives the thumbnail an AudioFormatReader to use directly.
  28474. This will start parsing the audio in a background thread (unless the hash code
  28475. can be looked-up successfully in the thumbnail cache). Note that the reader
  28476. object will be held by the thumbnail and deleted later when no longer needed.
  28477. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  28478. or change the input source, so the file will be held open for all this time. If
  28479. you don't want the thumbnail to keep a file handle open continuously, you
  28480. should use the setSource() method instead, which will only open the file when
  28481. it needs to.
  28482. */
  28483. void setReader (AudioFormatReader* newReader, int64 hashCode);
  28484. /** Resets the thumbnail, ready for adding data with the specified format.
  28485. If you're going to generate a thumbnail yourself, call this before using addBlock()
  28486. to add the data.
  28487. */
  28488. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  28489. /** Adds a block of level data to the thumbnail.
  28490. Call reset() before using this, to tell the thumbnail about the data format.
  28491. */
  28492. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  28493. int startOffsetInBuffer, int numSamples);
  28494. /** Reloads the low res thumbnail data from an input stream.
  28495. This is not an audio file stream! It takes a stream of thumbnail data that would
  28496. previously have been created by the saveTo() method.
  28497. @see saveTo
  28498. */
  28499. void loadFrom (InputStream& input);
  28500. /** Saves the low res thumbnail data to an output stream.
  28501. The data that is written can later be reloaded using loadFrom().
  28502. @see loadFrom
  28503. */
  28504. void saveTo (OutputStream& output) const;
  28505. /** Returns the number of channels in the file. */
  28506. int getNumChannels() const noexcept;
  28507. /** Returns the length of the audio file, in seconds. */
  28508. double getTotalLength() const noexcept;
  28509. /** Draws the waveform for a channel.
  28510. The waveform will be drawn within the specified rectangle, where startTime
  28511. and endTime specify the times within the audio file that should be positioned
  28512. at the left and right edges of the rectangle.
  28513. The waveform will be scaled vertically so that a full-volume sample will fill
  28514. the rectangle vertically, but you can also specify an extra vertical scale factor
  28515. with the verticalZoomFactor parameter.
  28516. */
  28517. void drawChannel (Graphics& g,
  28518. const Rectangle<int>& area,
  28519. double startTimeSeconds,
  28520. double endTimeSeconds,
  28521. int channelNum,
  28522. float verticalZoomFactor);
  28523. /** Draws the waveforms for all channels in the thumbnail.
  28524. This will call drawChannel() to render each of the thumbnail's channels, stacked
  28525. above each other within the specified area.
  28526. @see drawChannel
  28527. */
  28528. void drawChannels (Graphics& g,
  28529. const Rectangle<int>& area,
  28530. double startTimeSeconds,
  28531. double endTimeSeconds,
  28532. float verticalZoomFactor);
  28533. /** Returns true if the low res preview is fully generated. */
  28534. bool isFullyLoaded() const noexcept;
  28535. /** Returns the number of samples that have been set in the thumbnail. */
  28536. int64 getNumSamplesFinished() const noexcept;
  28537. /** Returns the highest level in the thumbnail.
  28538. Note that because the thumb only stores low-resolution data, this isn't
  28539. an accurate representation of the highest value, it's only a rough approximation.
  28540. */
  28541. float getApproximatePeak() const;
  28542. /** Returns the hash code that was set by setSource() or setReader(). */
  28543. int64 getHashCode() const;
  28544. #ifndef DOXYGEN
  28545. // (this is only public to avoid a VC6 bug)
  28546. class LevelDataSource;
  28547. #endif
  28548. private:
  28549. AudioFormatManager& formatManagerToUse;
  28550. AudioThumbnailCache& cache;
  28551. struct MinMaxValue;
  28552. class ThumbData;
  28553. class CachedWindow;
  28554. friend class LevelDataSource;
  28555. friend class ScopedPointer<LevelDataSource>;
  28556. friend class ThumbData;
  28557. friend class OwnedArray<ThumbData>;
  28558. friend class CachedWindow;
  28559. friend class ScopedPointer<CachedWindow>;
  28560. ScopedPointer<LevelDataSource> source;
  28561. ScopedPointer<CachedWindow> window;
  28562. OwnedArray<ThumbData> channels;
  28563. int32 samplesPerThumbSample;
  28564. int64 totalSamples, numSamplesFinished;
  28565. int32 numChannels;
  28566. double sampleRate;
  28567. CriticalSection lock;
  28568. bool setDataSource (LevelDataSource* newSource);
  28569. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28570. void createChannels (int length);
  28571. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28572. };
  28573. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28574. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28575. #endif
  28576. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28577. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28578. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28579. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28580. struct ThumbnailCacheEntry;
  28581. /**
  28582. An instance of this class is used to manage multiple AudioThumbnail objects.
  28583. The cache runs a single background thread that is shared by all the thumbnails
  28584. that need it, and it maintains a set of low-res previews in memory, to avoid
  28585. having to re-scan audio files too often.
  28586. @see AudioThumbnail
  28587. */
  28588. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28589. {
  28590. public:
  28591. /** Creates a cache object.
  28592. The maxNumThumbsToStore parameter lets you specify how many previews should
  28593. be kept in memory at once.
  28594. */
  28595. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28596. /** Destructor. */
  28597. ~AudioThumbnailCache();
  28598. /** Clears out any stored thumbnails.
  28599. */
  28600. void clear();
  28601. /** Reloads the specified thumb if this cache contains the appropriate stored
  28602. data.
  28603. This is called automatically by the AudioThumbnail class, so you shouldn't
  28604. normally need to call it directly.
  28605. */
  28606. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28607. /** Stores the cachable data from the specified thumb in this cache.
  28608. This is called automatically by the AudioThumbnail class, so you shouldn't
  28609. normally need to call it directly.
  28610. */
  28611. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28612. private:
  28613. OwnedArray <ThumbnailCacheEntry> thumbs;
  28614. int maxNumThumbsToStore;
  28615. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28616. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28617. };
  28618. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28619. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28620. #endif
  28621. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28622. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28623. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28624. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28625. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28626. /**
  28627. Reads and writes the lossless-compression FLAC audio format.
  28628. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28629. and make sure your include search path and library search path are set up to find
  28630. the FLAC header files and static libraries.
  28631. @see AudioFormat
  28632. */
  28633. class JUCE_API FlacAudioFormat : public AudioFormat
  28634. {
  28635. public:
  28636. FlacAudioFormat();
  28637. ~FlacAudioFormat();
  28638. const Array <int> getPossibleSampleRates();
  28639. const Array <int> getPossibleBitDepths();
  28640. bool canDoStereo();
  28641. bool canDoMono();
  28642. bool isCompressed();
  28643. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28644. bool deleteStreamIfOpeningFails);
  28645. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28646. double sampleRateToUse,
  28647. unsigned int numberOfChannels,
  28648. int bitsPerSample,
  28649. const StringPairArray& metadataValues,
  28650. int qualityOptionIndex);
  28651. private:
  28652. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28653. };
  28654. #endif
  28655. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28656. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28657. #endif
  28658. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28659. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28660. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28661. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28662. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28663. /**
  28664. Reads and writes the Ogg-Vorbis audio format.
  28665. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28666. and make sure your include search path and library search path are set up to find
  28667. the Vorbis and Ogg header files and static libraries.
  28668. @see AudioFormat,
  28669. */
  28670. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28671. {
  28672. public:
  28673. OggVorbisAudioFormat();
  28674. ~OggVorbisAudioFormat();
  28675. const Array <int> getPossibleSampleRates();
  28676. const Array <int> getPossibleBitDepths();
  28677. bool canDoStereo();
  28678. bool canDoMono();
  28679. bool isCompressed();
  28680. const StringArray getQualityOptions();
  28681. /** Tries to estimate the quality level of an ogg file based on its size.
  28682. If it can't read the file for some reason, this will just return 1 (medium quality),
  28683. otherwise it will return the approximate quality setting that would have been used
  28684. to create the file.
  28685. @see getQualityOptions
  28686. */
  28687. int estimateOggFileQuality (const File& source);
  28688. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28689. bool deleteStreamIfOpeningFails);
  28690. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28691. double sampleRateToUse,
  28692. unsigned int numberOfChannels,
  28693. int bitsPerSample,
  28694. const StringPairArray& metadataValues,
  28695. int qualityOptionIndex);
  28696. private:
  28697. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28698. };
  28699. #endif
  28700. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28701. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28702. #endif
  28703. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28704. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28705. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28706. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28707. #if JUCE_QUICKTIME
  28708. /**
  28709. Uses QuickTime to read the audio track a movie or media file.
  28710. As well as QuickTime movies, this should also manage to open other audio
  28711. files that quicktime can understand, like mp3, m4a, etc.
  28712. @see AudioFormat
  28713. */
  28714. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28715. {
  28716. public:
  28717. /** Creates a format object. */
  28718. QuickTimeAudioFormat();
  28719. /** Destructor. */
  28720. ~QuickTimeAudioFormat();
  28721. const Array <int> getPossibleSampleRates();
  28722. const Array <int> getPossibleBitDepths();
  28723. bool canDoStereo();
  28724. bool canDoMono();
  28725. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28726. bool deleteStreamIfOpeningFails);
  28727. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28728. double sampleRateToUse,
  28729. unsigned int numberOfChannels,
  28730. int bitsPerSample,
  28731. const StringPairArray& metadataValues,
  28732. int qualityOptionIndex);
  28733. private:
  28734. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28735. };
  28736. #endif
  28737. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28738. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28739. #endif
  28740. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28741. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28742. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28743. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28744. /**
  28745. Reads and Writes WAV format audio files.
  28746. @see AudioFormat
  28747. */
  28748. class JUCE_API WavAudioFormat : public AudioFormat
  28749. {
  28750. public:
  28751. /** Creates a format object. */
  28752. WavAudioFormat();
  28753. /** Destructor. */
  28754. ~WavAudioFormat();
  28755. /** Metadata property name used by wav readers and writers for adding
  28756. a BWAV chunk to the file.
  28757. @see AudioFormatReader::metadataValues, createWriterFor
  28758. */
  28759. static const char* const bwavDescription;
  28760. /** Metadata property name used by wav readers and writers for adding
  28761. a BWAV chunk to the file.
  28762. @see AudioFormatReader::metadataValues, createWriterFor
  28763. */
  28764. static const char* const bwavOriginator;
  28765. /** Metadata property name used by wav readers and writers for adding
  28766. a BWAV chunk to the file.
  28767. @see AudioFormatReader::metadataValues, createWriterFor
  28768. */
  28769. static const char* const bwavOriginatorRef;
  28770. /** Metadata property name used by wav readers and writers for adding
  28771. a BWAV chunk to the file.
  28772. Date format is: yyyy-mm-dd
  28773. @see AudioFormatReader::metadataValues, createWriterFor
  28774. */
  28775. static const char* const bwavOriginationDate;
  28776. /** Metadata property name used by wav readers and writers for adding
  28777. a BWAV chunk to the file.
  28778. Time format is: hh-mm-ss
  28779. @see AudioFormatReader::metadataValues, createWriterFor
  28780. */
  28781. static const char* const bwavOriginationTime;
  28782. /** Metadata property name used by wav readers and writers for adding
  28783. a BWAV chunk to the file.
  28784. This is the number of samples from the start of an edit that the
  28785. file is supposed to begin at. Seems like an obvious mistake to
  28786. only allow a file to occur in an edit once, but that's the way
  28787. it is..
  28788. @see AudioFormatReader::metadataValues, createWriterFor
  28789. */
  28790. static const char* const bwavTimeReference;
  28791. /** Metadata property name used by wav readers and writers for adding
  28792. a BWAV chunk to the file.
  28793. This is a
  28794. @see AudioFormatReader::metadataValues, createWriterFor
  28795. */
  28796. static const char* const bwavCodingHistory;
  28797. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28798. This just makes it easier than using the property names directly, and it
  28799. fills out the time and date in the right format.
  28800. */
  28801. static const StringPairArray createBWAVMetadata (const String& description,
  28802. const String& originator,
  28803. const String& originatorRef,
  28804. const Time& dateAndTime,
  28805. const int64 timeReferenceSamples,
  28806. const String& codingHistory);
  28807. const Array <int> getPossibleSampleRates();
  28808. const Array <int> getPossibleBitDepths();
  28809. bool canDoStereo();
  28810. bool canDoMono();
  28811. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28812. bool deleteStreamIfOpeningFails);
  28813. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28814. double sampleRateToUse,
  28815. unsigned int numberOfChannels,
  28816. int bitsPerSample,
  28817. const StringPairArray& metadataValues,
  28818. int qualityOptionIndex);
  28819. /** Utility function to replace the metadata in a wav file with a new set of values.
  28820. If possible, this cheats by overwriting just the metadata region of the file, rather
  28821. than by copying the whole file again.
  28822. */
  28823. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28824. private:
  28825. JUCE_LEAK_DETECTOR (WavAudioFormat);
  28826. };
  28827. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28828. /*** End of inlined file: juce_WavAudioFormat.h ***/
  28829. #endif
  28830. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28831. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  28832. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28833. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28834. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  28835. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28836. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28837. /**
  28838. A type of AudioSource which can be repositioned.
  28839. The basic AudioSource just streams continuously with no idea of a current
  28840. time or length, so the PositionableAudioSource is used for a finite stream
  28841. that has a current read position.
  28842. @see AudioSource, AudioTransportSource
  28843. */
  28844. class JUCE_API PositionableAudioSource : public AudioSource
  28845. {
  28846. protected:
  28847. /** Creates the PositionableAudioSource. */
  28848. PositionableAudioSource() noexcept {}
  28849. public:
  28850. /** Destructor */
  28851. ~PositionableAudioSource() {}
  28852. /** Tells the stream to move to a new position.
  28853. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  28854. should return samples from this position.
  28855. Note that this may be called on a different thread to getNextAudioBlock(),
  28856. so the subclass should make sure it's synchronised.
  28857. */
  28858. virtual void setNextReadPosition (int64 newPosition) = 0;
  28859. /** Returns the position from which the next block will be returned.
  28860. @see setNextReadPosition
  28861. */
  28862. virtual int64 getNextReadPosition() const = 0;
  28863. /** Returns the total length of the stream (in samples). */
  28864. virtual int64 getTotalLength() const = 0;
  28865. /** Returns true if this source is actually playing in a loop. */
  28866. virtual bool isLooping() const = 0;
  28867. /** Tells the source whether you'd like it to play in a loop. */
  28868. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  28869. };
  28870. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28871. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  28872. /**
  28873. A type of AudioSource that will read from an AudioFormatReader.
  28874. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  28875. */
  28876. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  28877. {
  28878. public:
  28879. /** Creates an AudioFormatReaderSource for a given reader.
  28880. @param sourceReader the reader to use as the data source
  28881. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  28882. when this object is deleted; if false it will be
  28883. left up to the caller to manage its lifetime
  28884. */
  28885. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  28886. bool deleteReaderWhenThisIsDeleted);
  28887. /** Destructor. */
  28888. ~AudioFormatReaderSource();
  28889. /** Toggles loop-mode.
  28890. If set to true, it will continuously loop the input source. If false,
  28891. it will just emit silence after the source has finished.
  28892. @see isLooping
  28893. */
  28894. void setLooping (bool shouldLoop);
  28895. /** Returns whether loop-mode is turned on or not. */
  28896. bool isLooping() const { return looping; }
  28897. /** Returns the reader that's being used. */
  28898. AudioFormatReader* getAudioFormatReader() const noexcept { return reader; }
  28899. /** Implementation of the AudioSource method. */
  28900. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28901. /** Implementation of the AudioSource method. */
  28902. void releaseResources();
  28903. /** Implementation of the AudioSource method. */
  28904. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28905. /** Implements the PositionableAudioSource method. */
  28906. void setNextReadPosition (int64 newPosition);
  28907. /** Implements the PositionableAudioSource method. */
  28908. int64 getNextReadPosition() const;
  28909. /** Implements the PositionableAudioSource method. */
  28910. int64 getTotalLength() const;
  28911. private:
  28912. AudioFormatReader* reader;
  28913. bool deleteReader;
  28914. int64 volatile nextPlayPos;
  28915. bool volatile looping;
  28916. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  28917. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  28918. };
  28919. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28920. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  28921. #endif
  28922. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  28923. #endif
  28924. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28925. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  28926. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28927. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28928. /*** Start of inlined file: juce_AudioIODevice.h ***/
  28929. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28930. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28931. class AudioIODevice;
  28932. /**
  28933. One of these is passed to an AudioIODevice object to stream the audio data
  28934. in and out.
  28935. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  28936. method on its own high-priority audio thread, when it needs to send or receive
  28937. the next block of data.
  28938. @see AudioIODevice, AudioDeviceManager
  28939. */
  28940. class JUCE_API AudioIODeviceCallback
  28941. {
  28942. public:
  28943. /** Destructor. */
  28944. virtual ~AudioIODeviceCallback() {}
  28945. /** Processes a block of incoming and outgoing audio data.
  28946. The subclass's implementation should use the incoming audio for whatever
  28947. purposes it needs to, and must fill all the output channels with the next
  28948. block of output data before returning.
  28949. The channel data is arranged with the same array indices as the channel name
  28950. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  28951. that aren't specified in AudioIODevice::open() will have a null pointer for their
  28952. associated channel, so remember to check for this.
  28953. @param inputChannelData a set of arrays containing the audio data for each
  28954. incoming channel - this data is valid until the function
  28955. returns. There will be one channel of data for each input
  28956. channel that was enabled when the audio device was opened
  28957. (see AudioIODevice::open())
  28958. @param numInputChannels the number of pointers to channel data in the
  28959. inputChannelData array.
  28960. @param outputChannelData a set of arrays which need to be filled with the data
  28961. that should be sent to each outgoing channel of the device.
  28962. There will be one channel of data for each output channel
  28963. that was enabled when the audio device was opened (see
  28964. AudioIODevice::open())
  28965. The initial contents of the array is undefined, so the
  28966. callback function must fill all the channels with zeros if
  28967. its output is silence. Failing to do this could cause quite
  28968. an unpleasant noise!
  28969. @param numOutputChannels the number of pointers to channel data in the
  28970. outputChannelData array.
  28971. @param numSamples the number of samples in each channel of the input and
  28972. output arrays. The number of samples will depend on the
  28973. audio device's buffer size and will usually remain constant,
  28974. although this isn't guaranteed, so make sure your code can
  28975. cope with reasonable changes in the buffer size from one
  28976. callback to the next.
  28977. */
  28978. virtual void audioDeviceIOCallback (const float** inputChannelData,
  28979. int numInputChannels,
  28980. float** outputChannelData,
  28981. int numOutputChannels,
  28982. int numSamples) = 0;
  28983. /** Called to indicate that the device is about to start calling back.
  28984. This will be called just before the audio callbacks begin, either when this
  28985. callback has just been added to an audio device, or after the device has been
  28986. restarted because of a sample-rate or block-size change.
  28987. You can use this opportunity to find out the sample rate and block size
  28988. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  28989. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  28990. @param device the audio IO device that will be used to drive the callback.
  28991. Note that if you're going to store this this pointer, it is
  28992. only valid until the next time that audioDeviceStopped is called.
  28993. */
  28994. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  28995. /** Called to indicate that the device has stopped.
  28996. */
  28997. virtual void audioDeviceStopped() = 0;
  28998. };
  28999. /**
  29000. Base class for an audio device with synchronised input and output channels.
  29001. Subclasses of this are used to implement different protocols such as DirectSound,
  29002. ASIO, CoreAudio, etc.
  29003. To create one of these, you'll need to use the AudioIODeviceType class - see the
  29004. documentation for that class for more info.
  29005. For an easier way of managing audio devices and their settings, have a look at the
  29006. AudioDeviceManager class.
  29007. @see AudioIODeviceType, AudioDeviceManager
  29008. */
  29009. class JUCE_API AudioIODevice
  29010. {
  29011. public:
  29012. /** Destructor. */
  29013. virtual ~AudioIODevice();
  29014. /** Returns the device's name, (as set in the constructor). */
  29015. const String& getName() const noexcept { return name; }
  29016. /** Returns the type of the device.
  29017. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  29018. */
  29019. const String& getTypeName() const noexcept { return typeName; }
  29020. /** Returns the names of all the available output channels on this device.
  29021. To find out which of these are currently in use, call getActiveOutputChannels().
  29022. */
  29023. virtual const StringArray getOutputChannelNames() = 0;
  29024. /** Returns the names of all the available input channels on this device.
  29025. To find out which of these are currently in use, call getActiveInputChannels().
  29026. */
  29027. virtual const StringArray getInputChannelNames() = 0;
  29028. /** Returns the number of sample-rates this device supports.
  29029. To find out which rates are available on this device, use this method to
  29030. find out how many there are, and getSampleRate() to get the rates.
  29031. @see getSampleRate
  29032. */
  29033. virtual int getNumSampleRates() = 0;
  29034. /** Returns one of the sample-rates this device supports.
  29035. To find out which rates are available on this device, use getNumSampleRates() to
  29036. find out how many there are, and getSampleRate() to get the individual rates.
  29037. The sample rate is set by the open() method.
  29038. (Note that for DirectSound some rates might not work, depending on combinations
  29039. of i/o channels that are being opened).
  29040. @see getNumSampleRates
  29041. */
  29042. virtual double getSampleRate (int index) = 0;
  29043. /** Returns the number of sizes of buffer that are available.
  29044. @see getBufferSizeSamples, getDefaultBufferSize
  29045. */
  29046. virtual int getNumBufferSizesAvailable() = 0;
  29047. /** Returns one of the possible buffer-sizes.
  29048. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  29049. @returns a number of samples
  29050. @see getNumBufferSizesAvailable, getDefaultBufferSize
  29051. */
  29052. virtual int getBufferSizeSamples (int index) = 0;
  29053. /** Returns the default buffer-size to use.
  29054. @returns a number of samples
  29055. @see getNumBufferSizesAvailable, getBufferSizeSamples
  29056. */
  29057. virtual int getDefaultBufferSize() = 0;
  29058. /** Tries to open the device ready to play.
  29059. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  29060. input channel should be enabled
  29061. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  29062. output channel should be enabled
  29063. @param sampleRate the sample rate to try to use - to find out which rates are
  29064. available, see getNumSampleRates() and getSampleRate()
  29065. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  29066. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  29067. @returns an error description if there's a problem, or an empty string if it succeeds in
  29068. opening the device
  29069. @see close
  29070. */
  29071. virtual const String open (const BigInteger& inputChannels,
  29072. const BigInteger& outputChannels,
  29073. double sampleRate,
  29074. int bufferSizeSamples) = 0;
  29075. /** Closes and releases the device if it's open. */
  29076. virtual void close() = 0;
  29077. /** Returns true if the device is still open.
  29078. A device might spontaneously close itself if something goes wrong, so this checks if
  29079. it's still open.
  29080. */
  29081. virtual bool isOpen() = 0;
  29082. /** Starts the device actually playing.
  29083. This must be called after the device has been opened.
  29084. @param callback the callback to use for streaming the data.
  29085. @see AudioIODeviceCallback, open
  29086. */
  29087. virtual void start (AudioIODeviceCallback* callback) = 0;
  29088. /** Stops the device playing.
  29089. Once a device has been started, this will stop it. Any pending calls to the
  29090. callback class will be flushed before this method returns.
  29091. */
  29092. virtual void stop() = 0;
  29093. /** Returns true if the device is still calling back.
  29094. The device might mysteriously stop, so this checks whether it's
  29095. still playing.
  29096. */
  29097. virtual bool isPlaying() = 0;
  29098. /** Returns the last error that happened if anything went wrong. */
  29099. virtual const String getLastError() = 0;
  29100. /** Returns the buffer size that the device is currently using.
  29101. If the device isn't actually open, this value doesn't really mean much.
  29102. */
  29103. virtual int getCurrentBufferSizeSamples() = 0;
  29104. /** Returns the sample rate that the device is currently using.
  29105. If the device isn't actually open, this value doesn't really mean much.
  29106. */
  29107. virtual double getCurrentSampleRate() = 0;
  29108. /** Returns the device's current physical bit-depth.
  29109. If the device isn't actually open, this value doesn't really mean much.
  29110. */
  29111. virtual int getCurrentBitDepth() = 0;
  29112. /** Returns a mask showing which of the available output channels are currently
  29113. enabled.
  29114. @see getOutputChannelNames
  29115. */
  29116. virtual const BigInteger getActiveOutputChannels() const = 0;
  29117. /** Returns a mask showing which of the available input channels are currently
  29118. enabled.
  29119. @see getInputChannelNames
  29120. */
  29121. virtual const BigInteger getActiveInputChannels() const = 0;
  29122. /** Returns the device's output latency.
  29123. This is the delay in samples between a callback getting a block of data, and
  29124. that data actually getting played.
  29125. */
  29126. virtual int getOutputLatencyInSamples() = 0;
  29127. /** Returns the device's input latency.
  29128. This is the delay in samples between some audio actually arriving at the soundcard,
  29129. and the callback getting passed this block of data.
  29130. */
  29131. virtual int getInputLatencyInSamples() = 0;
  29132. /** True if this device can show a pop-up control panel for editing its settings.
  29133. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  29134. to display it.
  29135. */
  29136. virtual bool hasControlPanel() const;
  29137. /** Shows a device-specific control panel if there is one.
  29138. This should only be called for devices which return true from hasControlPanel().
  29139. */
  29140. virtual bool showControlPanel();
  29141. protected:
  29142. /** Creates a device, setting its name and type member variables. */
  29143. AudioIODevice (const String& deviceName,
  29144. const String& typeName);
  29145. /** @internal */
  29146. String name, typeName;
  29147. };
  29148. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29149. /*** End of inlined file: juce_AudioIODevice.h ***/
  29150. /**
  29151. Wrapper class to continuously stream audio from an audio source to an
  29152. AudioIODevice.
  29153. This object acts as an AudioIODeviceCallback, so can be attached to an
  29154. output device, and will stream audio from an AudioSource.
  29155. */
  29156. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  29157. {
  29158. public:
  29159. /** Creates an empty AudioSourcePlayer. */
  29160. AudioSourcePlayer();
  29161. /** Destructor.
  29162. Make sure this object isn't still being used by an AudioIODevice before
  29163. deleting it!
  29164. */
  29165. virtual ~AudioSourcePlayer();
  29166. /** Changes the current audio source to play from.
  29167. If the source passed in is already being used, this method will do nothing.
  29168. If the source is not null, its prepareToPlay() method will be called
  29169. before it starts being used for playback.
  29170. If there's another source currently playing, its releaseResources() method
  29171. will be called after it has been swapped for the new one.
  29172. @param newSource the new source to use - this will NOT be deleted
  29173. by this object when no longer needed, so it's the
  29174. caller's responsibility to manage it.
  29175. */
  29176. void setSource (AudioSource* newSource);
  29177. /** Returns the source that's playing.
  29178. May return 0 if there's no source.
  29179. */
  29180. AudioSource* getCurrentSource() const noexcept { return source; }
  29181. /** Sets a gain to apply to the audio data.
  29182. @see getGain
  29183. */
  29184. void setGain (float newGain) noexcept;
  29185. /** Returns the current gain.
  29186. @see setGain
  29187. */
  29188. float getGain() const noexcept { return gain; }
  29189. /** Implementation of the AudioIODeviceCallback method. */
  29190. void audioDeviceIOCallback (const float** inputChannelData,
  29191. int totalNumInputChannels,
  29192. float** outputChannelData,
  29193. int totalNumOutputChannels,
  29194. int numSamples);
  29195. /** Implementation of the AudioIODeviceCallback method. */
  29196. void audioDeviceAboutToStart (AudioIODevice* device);
  29197. /** Implementation of the AudioIODeviceCallback method. */
  29198. void audioDeviceStopped();
  29199. private:
  29200. CriticalSection readLock;
  29201. AudioSource* source;
  29202. double sampleRate;
  29203. int bufferSize;
  29204. float* channels [128];
  29205. float* outputChans [128];
  29206. const float* inputChans [128];
  29207. AudioSampleBuffer tempBuffer;
  29208. float lastGain, gain;
  29209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  29210. };
  29211. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29212. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  29213. #endif
  29214. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29215. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  29216. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29217. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29218. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  29219. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29220. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29221. /**
  29222. An AudioSource which takes another source as input, and buffers it using a thread.
  29223. Create this as a wrapper around another thread, and it will read-ahead with
  29224. a background thread to smooth out playback. You can either create one of these
  29225. directly, or use it indirectly using an AudioTransportSource.
  29226. @see PositionableAudioSource, AudioTransportSource
  29227. */
  29228. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  29229. {
  29230. public:
  29231. /** Creates a BufferingAudioSource.
  29232. @param source the input source to read from
  29233. @param deleteSourceWhenDeleted if true, then the input source object will
  29234. be deleted when this object is deleted
  29235. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  29236. */
  29237. BufferingAudioSource (PositionableAudioSource* source,
  29238. bool deleteSourceWhenDeleted,
  29239. int numberOfSamplesToBuffer);
  29240. /** Destructor.
  29241. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  29242. flag was set in the constructor.
  29243. */
  29244. ~BufferingAudioSource();
  29245. /** Implementation of the AudioSource method. */
  29246. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29247. /** Implementation of the AudioSource method. */
  29248. void releaseResources();
  29249. /** Implementation of the AudioSource method. */
  29250. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29251. /** Implements the PositionableAudioSource method. */
  29252. void setNextReadPosition (int64 newPosition);
  29253. /** Implements the PositionableAudioSource method. */
  29254. int64 getNextReadPosition() const;
  29255. /** Implements the PositionableAudioSource method. */
  29256. int64 getTotalLength() const { return source->getTotalLength(); }
  29257. /** Implements the PositionableAudioSource method. */
  29258. bool isLooping() const { return source->isLooping(); }
  29259. private:
  29260. PositionableAudioSource* source;
  29261. bool deleteSourceWhenDeleted;
  29262. int numberOfSamplesToBuffer;
  29263. AudioSampleBuffer buffer;
  29264. CriticalSection bufferStartPosLock;
  29265. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  29266. bool wasSourceLooping;
  29267. double volatile sampleRate;
  29268. friend class SharedBufferingAudioSourceThread;
  29269. bool readNextBufferChunk();
  29270. void readBufferSection (int64 start, int length, int bufferOffset);
  29271. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  29272. };
  29273. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29274. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  29275. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  29276. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29277. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29278. /**
  29279. A type of AudioSource that takes an input source and changes its sample rate.
  29280. @see AudioSource
  29281. */
  29282. class JUCE_API ResamplingAudioSource : public AudioSource
  29283. {
  29284. public:
  29285. /** Creates a ResamplingAudioSource for a given input source.
  29286. @param inputSource the input source to read from
  29287. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29288. this object is deleted
  29289. @param numChannels the number of channels to process
  29290. */
  29291. ResamplingAudioSource (AudioSource* inputSource,
  29292. bool deleteInputWhenDeleted,
  29293. int numChannels = 2);
  29294. /** Destructor. */
  29295. ~ResamplingAudioSource();
  29296. /** Changes the resampling ratio.
  29297. (This value can be changed at any time, even while the source is running).
  29298. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  29299. values will speed it up; lower values will slow it
  29300. down. The ratio must be greater than 0
  29301. */
  29302. void setResamplingRatio (double samplesInPerOutputSample);
  29303. /** Returns the current resampling ratio.
  29304. This is the value that was set by setResamplingRatio().
  29305. */
  29306. double getResamplingRatio() const noexcept { return ratio; }
  29307. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29308. void releaseResources();
  29309. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29310. private:
  29311. AudioSource* const input;
  29312. const bool deleteInputWhenDeleted;
  29313. double ratio, lastRatio;
  29314. AudioSampleBuffer buffer;
  29315. int bufferPos, sampsInBuffer;
  29316. double subSampleOffset;
  29317. double coefficients[6];
  29318. SpinLock ratioLock;
  29319. const int numChannels;
  29320. HeapBlock<float*> destBuffers, srcBuffers;
  29321. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  29322. void createLowPass (double proportionalRate);
  29323. struct FilterState
  29324. {
  29325. double x1, x2, y1, y2;
  29326. };
  29327. HeapBlock<FilterState> filterStates;
  29328. void resetFilters();
  29329. void applyFilter (float* samples, int num, FilterState& fs);
  29330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  29331. };
  29332. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29333. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  29334. /**
  29335. An AudioSource that takes a PositionableAudioSource and allows it to be
  29336. played, stopped, started, etc.
  29337. This can also be told use a buffer and background thread to read ahead, and
  29338. if can correct for different sample-rates.
  29339. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  29340. to control playback of an audio file.
  29341. @see AudioSource, AudioSourcePlayer
  29342. */
  29343. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  29344. public ChangeBroadcaster
  29345. {
  29346. public:
  29347. /** Creates an AudioTransportSource.
  29348. After creating one of these, use the setSource() method to select an input source.
  29349. */
  29350. AudioTransportSource();
  29351. /** Destructor. */
  29352. ~AudioTransportSource();
  29353. /** Sets the reader that is being used as the input source.
  29354. This will stop playback, reset the position to 0 and change to the new reader.
  29355. The source passed in will not be deleted by this object, so must be managed by
  29356. the caller.
  29357. @param newSource the new input source to use. This may be zero
  29358. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  29359. is zero, no reading ahead will be done; if it's
  29360. greater than zero, a BufferingAudioSource will be used
  29361. to do the reading-ahead
  29362. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  29363. rate of the source, and playback will be sample-rate
  29364. adjusted to maintain playback at the correct pitch. If
  29365. this is 0, no sample-rate adjustment will be performed
  29366. @param maxNumChannels the maximum number of channels that may need to be played
  29367. */
  29368. void setSource (PositionableAudioSource* newSource,
  29369. int readAheadBufferSize = 0,
  29370. double sourceSampleRateToCorrectFor = 0.0,
  29371. int maxNumChannels = 2);
  29372. /** Changes the current playback position in the source stream.
  29373. The next time the getNextAudioBlock() method is called, this
  29374. is the time from which it'll read data.
  29375. @see getPosition
  29376. */
  29377. void setPosition (double newPosition);
  29378. /** Returns the position that the next data block will be read from
  29379. This is a time in seconds.
  29380. */
  29381. double getCurrentPosition() const;
  29382. /** Returns the stream's length in seconds. */
  29383. double getLengthInSeconds() const;
  29384. /** Returns true if the player has stopped because its input stream ran out of data.
  29385. */
  29386. bool hasStreamFinished() const noexcept { return inputStreamEOF; }
  29387. /** Starts playing (if a source has been selected).
  29388. If it starts playing, this will send a message to any ChangeListeners
  29389. that are registered with this object.
  29390. */
  29391. void start();
  29392. /** Stops playing.
  29393. If it's actually playing, this will send a message to any ChangeListeners
  29394. that are registered with this object.
  29395. */
  29396. void stop();
  29397. /** Returns true if it's currently playing. */
  29398. bool isPlaying() const noexcept { return playing; }
  29399. /** Changes the gain to apply to the output.
  29400. @param newGain a factor by which to multiply the outgoing samples,
  29401. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  29402. */
  29403. void setGain (float newGain) noexcept;
  29404. /** Returns the current gain setting.
  29405. @see setGain
  29406. */
  29407. float getGain() const noexcept { return gain; }
  29408. /** Implementation of the AudioSource method. */
  29409. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29410. /** Implementation of the AudioSource method. */
  29411. void releaseResources();
  29412. /** Implementation of the AudioSource method. */
  29413. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29414. /** Implements the PositionableAudioSource method. */
  29415. void setNextReadPosition (int64 newPosition);
  29416. /** Implements the PositionableAudioSource method. */
  29417. int64 getNextReadPosition() const;
  29418. /** Implements the PositionableAudioSource method. */
  29419. int64 getTotalLength() const;
  29420. /** Implements the PositionableAudioSource method. */
  29421. bool isLooping() const;
  29422. private:
  29423. PositionableAudioSource* source;
  29424. ResamplingAudioSource* resamplerSource;
  29425. BufferingAudioSource* bufferingSource;
  29426. PositionableAudioSource* positionableSource;
  29427. AudioSource* masterSource;
  29428. CriticalSection callbackLock;
  29429. float volatile gain, lastGain;
  29430. bool volatile playing, stopped;
  29431. double sampleRate, sourceSampleRate;
  29432. int blockSize, readAheadBufferSize;
  29433. bool isPrepared, inputStreamEOF;
  29434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  29435. };
  29436. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29437. /*** End of inlined file: juce_AudioTransportSource.h ***/
  29438. #endif
  29439. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29440. #endif
  29441. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29442. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29443. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29444. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29445. /**
  29446. An AudioSource that takes the audio from another source, and re-maps its
  29447. input and output channels to a different arrangement.
  29448. You can use this to increase or decrease the number of channels that an
  29449. audio source uses, or to re-order those channels.
  29450. Call the reset() method before using it to set up a default mapping, and then
  29451. the setInputChannelMapping() and setOutputChannelMapping() methods to
  29452. create an appropriate mapping, otherwise no channels will be connected and
  29453. it'll produce silence.
  29454. @see AudioSource
  29455. */
  29456. class ChannelRemappingAudioSource : public AudioSource
  29457. {
  29458. public:
  29459. /** Creates a remapping source that will pass on audio from the given input.
  29460. @param source the input source to use. Make sure that this doesn't
  29461. get deleted before the ChannelRemappingAudioSource object
  29462. @param deleteSourceWhenDeleted if true, the input source will be deleted
  29463. when this object is deleted, if false, the caller is
  29464. responsible for its deletion
  29465. */
  29466. ChannelRemappingAudioSource (AudioSource* source,
  29467. bool deleteSourceWhenDeleted);
  29468. /** Destructor. */
  29469. ~ChannelRemappingAudioSource();
  29470. /** Specifies a number of channels that this audio source must produce from its
  29471. getNextAudioBlock() callback.
  29472. */
  29473. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  29474. /** Clears any mapped channels.
  29475. After this, no channels are mapped, so this object will produce silence. Create
  29476. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  29477. */
  29478. void clearAllMappings();
  29479. /** Creates an input channel mapping.
  29480. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  29481. data will be sent to destChannelIndex of our input source.
  29482. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  29483. source specified when this object was created).
  29484. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  29485. during our getNextAudioBlock() callback
  29486. */
  29487. void setInputChannelMapping (int destChannelIndex,
  29488. int sourceChannelIndex);
  29489. /** Creates an output channel mapping.
  29490. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  29491. our input audio source will be copied to channel destChannelIndex of the final buffer.
  29492. @param sourceChannelIndex the index of an output channel coming from our input audio source
  29493. (i.e. the source specified when this object was created).
  29494. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  29495. during our getNextAudioBlock() callback
  29496. */
  29497. void setOutputChannelMapping (int sourceChannelIndex,
  29498. int destChannelIndex);
  29499. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  29500. our input audio source.
  29501. */
  29502. int getRemappedInputChannel (int inputChannelIndex) const;
  29503. /** Returns the output channel to which channel outputChannelIndex of our input audio
  29504. source will be sent to.
  29505. */
  29506. int getRemappedOutputChannel (int outputChannelIndex) const;
  29507. /** Returns an XML object to encapsulate the state of the mappings.
  29508. @see restoreFromXml
  29509. */
  29510. XmlElement* createXml() const;
  29511. /** Restores the mappings from an XML object created by createXML().
  29512. @see createXml
  29513. */
  29514. void restoreFromXml (const XmlElement& e);
  29515. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29516. void releaseResources();
  29517. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29518. private:
  29519. int requiredNumberOfChannels;
  29520. Array <int> remappedInputs, remappedOutputs;
  29521. AudioSource* const source;
  29522. const bool deleteSourceWhenDeleted;
  29523. AudioSampleBuffer buffer;
  29524. AudioSourceChannelInfo remappedInfo;
  29525. CriticalSection lock;
  29526. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  29527. };
  29528. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29529. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29530. #endif
  29531. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29532. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  29533. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29534. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29535. /*** Start of inlined file: juce_IIRFilter.h ***/
  29536. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  29537. #define __JUCE_IIRFILTER_JUCEHEADER__
  29538. /**
  29539. An IIR filter that can perform low, high, or band-pass filtering on an
  29540. audio signal.
  29541. @see IIRFilterAudioSource
  29542. */
  29543. class JUCE_API IIRFilter
  29544. {
  29545. public:
  29546. /** Creates a filter.
  29547. Initially the filter is inactive, so will have no effect on samples that
  29548. you process with it. Use the appropriate method to turn it into the type
  29549. of filter needed.
  29550. */
  29551. IIRFilter();
  29552. /** Creates a copy of another filter. */
  29553. IIRFilter (const IIRFilter& other);
  29554. /** Destructor. */
  29555. ~IIRFilter();
  29556. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29557. Note that this clears the processing state, but the type of filter and
  29558. its coefficients aren't changed. To put a filter into an inactive state, use
  29559. the makeInactive() method.
  29560. */
  29561. void reset() noexcept;
  29562. /** Performs the filter operation on the given set of samples.
  29563. */
  29564. void processSamples (float* samples,
  29565. int numSamples) noexcept;
  29566. /** Processes a single sample, without any locking or checking.
  29567. Use this if you need fast processing of a single value, but be aware that
  29568. this isn't thread-safe in the way that processSamples() is.
  29569. */
  29570. float processSingleSampleRaw (float sample) noexcept;
  29571. /** Sets the filter up to act as a low-pass filter.
  29572. */
  29573. void makeLowPass (double sampleRate,
  29574. double frequency) noexcept;
  29575. /** Sets the filter up to act as a high-pass filter.
  29576. */
  29577. void makeHighPass (double sampleRate,
  29578. double frequency) noexcept;
  29579. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29580. The gain is a scale factor that the low frequencies are multiplied by, so values
  29581. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29582. attenuate them.
  29583. */
  29584. void makeLowShelf (double sampleRate,
  29585. double cutOffFrequency,
  29586. double Q,
  29587. float gainFactor) noexcept;
  29588. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29589. The gain is a scale factor that the high frequencies are multiplied by, so values
  29590. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29591. attenuate them.
  29592. */
  29593. void makeHighShelf (double sampleRate,
  29594. double cutOffFrequency,
  29595. double Q,
  29596. float gainFactor) noexcept;
  29597. /** Sets the filter up to act as a band pass filter centred around a
  29598. frequency, with a variable Q and gain.
  29599. The gain is a scale factor that the centre frequencies are multiplied by, so
  29600. values greater than 1.0 will boost the centre frequencies, values less than
  29601. 1.0 will attenuate them.
  29602. */
  29603. void makeBandPass (double sampleRate,
  29604. double centreFrequency,
  29605. double Q,
  29606. float gainFactor) noexcept;
  29607. /** Clears the filter's coefficients so that it becomes inactive.
  29608. */
  29609. void makeInactive() noexcept;
  29610. /** Makes this filter duplicate the set-up of another one.
  29611. */
  29612. void copyCoefficientsFrom (const IIRFilter& other) noexcept;
  29613. protected:
  29614. CriticalSection processLock;
  29615. void setCoefficients (double c1, double c2, double c3,
  29616. double c4, double c5, double c6) noexcept;
  29617. bool active;
  29618. float coefficients[6];
  29619. float x1, x2, y1, y2;
  29620. // (use the copyCoefficientsFrom() method instead of this operator)
  29621. IIRFilter& operator= (const IIRFilter&);
  29622. JUCE_LEAK_DETECTOR (IIRFilter);
  29623. };
  29624. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29625. /*** End of inlined file: juce_IIRFilter.h ***/
  29626. /**
  29627. An AudioSource that performs an IIR filter on another source.
  29628. */
  29629. class JUCE_API IIRFilterAudioSource : public AudioSource
  29630. {
  29631. public:
  29632. /** Creates a IIRFilterAudioSource for a given input source.
  29633. @param inputSource the input source to read from
  29634. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29635. this object is deleted
  29636. */
  29637. IIRFilterAudioSource (AudioSource* inputSource,
  29638. bool deleteInputWhenDeleted);
  29639. /** Destructor. */
  29640. ~IIRFilterAudioSource();
  29641. /** Changes the filter to use the same parameters as the one being passed in.
  29642. */
  29643. void setFilterParameters (const IIRFilter& newSettings);
  29644. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29645. void releaseResources();
  29646. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29647. private:
  29648. AudioSource* const input;
  29649. const bool deleteInputWhenDeleted;
  29650. OwnedArray <IIRFilter> iirFilters;
  29651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29652. };
  29653. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29654. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29655. #endif
  29656. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29657. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29658. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29659. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29660. /**
  29661. An AudioSource that mixes together the output of a set of other AudioSources.
  29662. Input sources can be added and removed while the mixer is running as long as their
  29663. prepareToPlay() and releaseResources() methods are called before and after adding
  29664. them to the mixer.
  29665. */
  29666. class JUCE_API MixerAudioSource : public AudioSource
  29667. {
  29668. public:
  29669. /** Creates a MixerAudioSource.
  29670. */
  29671. MixerAudioSource();
  29672. /** Destructor. */
  29673. ~MixerAudioSource();
  29674. /** Adds an input source to the mixer.
  29675. If the mixer is running you'll need to make sure that the input source
  29676. is ready to play by calling its prepareToPlay() method before adding it.
  29677. If the mixer is stopped, then its input sources will be automatically
  29678. prepared when the mixer's prepareToPlay() method is called.
  29679. @param newInput the source to add to the mixer
  29680. @param deleteWhenRemoved if true, then this source will be deleted when
  29681. the mixer is deleted or when removeAllInputs() is
  29682. called (unless the source is previously removed
  29683. with the removeInputSource method)
  29684. */
  29685. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29686. /** Removes an input source.
  29687. If the mixer is running, this will remove the source but not call its
  29688. releaseResources() method, so the caller might want to do this manually.
  29689. @param input the source to remove
  29690. @param deleteSource whether to delete this source after it's been removed
  29691. */
  29692. void removeInputSource (AudioSource* input, bool deleteSource);
  29693. /** Removes all the input sources.
  29694. If the mixer is running, this will remove the sources but not call their
  29695. releaseResources() method, so the caller might want to do this manually.
  29696. Any sources which were added with the deleteWhenRemoved flag set will be
  29697. deleted by this method.
  29698. */
  29699. void removeAllInputs();
  29700. /** Implementation of the AudioSource method.
  29701. This will call prepareToPlay() on all its input sources.
  29702. */
  29703. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29704. /** Implementation of the AudioSource method.
  29705. This will call releaseResources() on all its input sources.
  29706. */
  29707. void releaseResources();
  29708. /** Implementation of the AudioSource method. */
  29709. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29710. private:
  29711. Array <AudioSource*> inputs;
  29712. BigInteger inputsToDelete;
  29713. CriticalSection lock;
  29714. AudioSampleBuffer tempBuffer;
  29715. double currentSampleRate;
  29716. int bufferSizeExpected;
  29717. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29718. };
  29719. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29720. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29721. #endif
  29722. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29723. #endif
  29724. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29725. #endif
  29726. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29727. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29728. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29729. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29730. /**
  29731. A simple AudioSource that generates a sine wave.
  29732. */
  29733. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  29734. {
  29735. public:
  29736. /** Creates a ToneGeneratorAudioSource. */
  29737. ToneGeneratorAudioSource();
  29738. /** Destructor. */
  29739. ~ToneGeneratorAudioSource();
  29740. /** Sets the signal's amplitude. */
  29741. void setAmplitude (float newAmplitude);
  29742. /** Sets the signal's frequency. */
  29743. void setFrequency (double newFrequencyHz);
  29744. /** Implementation of the AudioSource method. */
  29745. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29746. /** Implementation of the AudioSource method. */
  29747. void releaseResources();
  29748. /** Implementation of the AudioSource method. */
  29749. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29750. private:
  29751. double frequency, sampleRate;
  29752. double currentPhase, phasePerSample;
  29753. float amplitude;
  29754. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  29755. };
  29756. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29757. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29758. #endif
  29759. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29760. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  29761. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29762. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29763. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  29764. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29765. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29766. class AudioDeviceManager;
  29767. class Component;
  29768. /**
  29769. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  29770. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  29771. method. Each of the objects returned can then be used to list the available
  29772. devices of that type. E.g.
  29773. @code
  29774. OwnedArray <AudioIODeviceType> types;
  29775. myAudioDeviceManager.createAudioDeviceTypes (types);
  29776. for (int i = 0; i < types.size(); ++i)
  29777. {
  29778. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  29779. types[i]->scanForDevices(); // This must be called before getting the list of devices
  29780. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  29781. for (int j = 0; j < deviceNames.size(); ++j)
  29782. {
  29783. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  29784. ...
  29785. }
  29786. }
  29787. @endcode
  29788. For an easier way of managing audio devices and their settings, have a look at the
  29789. AudioDeviceManager class.
  29790. @see AudioIODevice, AudioDeviceManager
  29791. */
  29792. class JUCE_API AudioIODeviceType
  29793. {
  29794. public:
  29795. /** Returns the name of this type of driver that this object manages.
  29796. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  29797. */
  29798. const String& getTypeName() const noexcept { return typeName; }
  29799. /** Refreshes the object's cached list of known devices.
  29800. This must be called at least once before calling getDeviceNames() or any of
  29801. the other device creation methods.
  29802. */
  29803. virtual void scanForDevices() = 0;
  29804. /** Returns the list of available devices of this type.
  29805. The scanForDevices() method must have been called to create this list.
  29806. @param wantInputNames only really used by DirectSound where devices are split up
  29807. into inputs and outputs, this indicates whether to use
  29808. the input or output name to refer to a pair of devices.
  29809. */
  29810. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  29811. /** Returns the name of the default device.
  29812. This will be one of the names from the getDeviceNames() list.
  29813. @param forInput if true, this means that a default input device should be
  29814. returned; if false, it should return the default output
  29815. */
  29816. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  29817. /** Returns the index of a given device in the list of device names.
  29818. If asInput is true, it shows the index in the inputs list, otherwise it
  29819. looks for it in the outputs list.
  29820. */
  29821. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  29822. /** Returns true if two different devices can be used for the input and output.
  29823. */
  29824. virtual bool hasSeparateInputsAndOutputs() const = 0;
  29825. /** Creates one of the devices of this type.
  29826. The deviceName must be one of the strings returned by getDeviceNames(), and
  29827. scanForDevices() must have been called before this method is used.
  29828. */
  29829. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  29830. const String& inputDeviceName) = 0;
  29831. struct DeviceSetupDetails
  29832. {
  29833. AudioDeviceManager* manager;
  29834. int minNumInputChannels, maxNumInputChannels;
  29835. int minNumOutputChannels, maxNumOutputChannels;
  29836. bool useStereoPairs;
  29837. };
  29838. /** Destructor. */
  29839. virtual ~AudioIODeviceType();
  29840. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  29841. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  29842. /** Creates an iOS device type if it's available on this platform, or returns null. */
  29843. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  29844. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  29845. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  29846. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  29847. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  29848. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  29849. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  29850. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  29851. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  29852. /** Creates a JACK device type if it's available on this platform, or returns null. */
  29853. static AudioIODeviceType* createAudioIODeviceType_JACK();
  29854. /** Creates an Android device type if it's available on this platform, or returns null. */
  29855. static AudioIODeviceType* createAudioIODeviceType_Android();
  29856. protected:
  29857. explicit AudioIODeviceType (const String& typeName);
  29858. private:
  29859. String typeName;
  29860. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  29861. };
  29862. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29863. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  29864. /*** Start of inlined file: juce_MidiInput.h ***/
  29865. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  29866. #define __JUCE_MIDIINPUT_JUCEHEADER__
  29867. /*** Start of inlined file: juce_MidiMessage.h ***/
  29868. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  29869. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  29870. /**
  29871. Encapsulates a MIDI message.
  29872. @see MidiMessageSequence, MidiOutput, MidiInput
  29873. */
  29874. class JUCE_API MidiMessage
  29875. {
  29876. public:
  29877. /** Creates a 3-byte short midi message.
  29878. @param byte1 message byte 1
  29879. @param byte2 message byte 2
  29880. @param byte3 message byte 3
  29881. @param timeStamp the time to give the midi message - this value doesn't
  29882. use any particular units, so will be application-specific
  29883. */
  29884. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) noexcept;
  29885. /** Creates a 2-byte short midi message.
  29886. @param byte1 message byte 1
  29887. @param byte2 message byte 2
  29888. @param timeStamp the time to give the midi message - this value doesn't
  29889. use any particular units, so will be application-specific
  29890. */
  29891. MidiMessage (int byte1, int byte2, double timeStamp = 0) noexcept;
  29892. /** Creates a 1-byte short midi message.
  29893. @param byte1 message byte 1
  29894. @param timeStamp the time to give the midi message - this value doesn't
  29895. use any particular units, so will be application-specific
  29896. */
  29897. MidiMessage (int byte1, double timeStamp = 0) noexcept;
  29898. /** Creates a midi message from a block of data. */
  29899. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  29900. /** Reads the next midi message from some data.
  29901. This will read as many bytes from a data stream as it needs to make a
  29902. complete message, and will return the number of bytes it used. This lets
  29903. you read a sequence of midi messages from a file or stream.
  29904. @param data the data to read from
  29905. @param maxBytesToUse the maximum number of bytes it's allowed to read
  29906. @param numBytesUsed returns the number of bytes that were actually needed
  29907. @param lastStatusByte in a sequence of midi messages, the initial byte
  29908. can be dropped from a message if it's the same as the
  29909. first byte of the previous message, so this lets you
  29910. supply the byte to use if the first byte of the message
  29911. has in fact been dropped.
  29912. @param timeStamp the time to give the midi message - this value doesn't
  29913. use any particular units, so will be application-specific
  29914. */
  29915. MidiMessage (const void* data, int maxBytesToUse,
  29916. int& numBytesUsed, uint8 lastStatusByte,
  29917. double timeStamp = 0);
  29918. /** Creates an active-sense message.
  29919. Since the MidiMessage has to contain a valid message, this default constructor
  29920. just initialises it with an empty sysex message.
  29921. */
  29922. MidiMessage() noexcept;
  29923. /** Creates a copy of another midi message. */
  29924. MidiMessage (const MidiMessage& other);
  29925. /** Creates a copy of another midi message, with a different timestamp. */
  29926. MidiMessage (const MidiMessage& other, double newTimeStamp);
  29927. /** Destructor. */
  29928. ~MidiMessage();
  29929. /** Copies this message from another one. */
  29930. MidiMessage& operator= (const MidiMessage& other);
  29931. /** Returns a pointer to the raw midi data.
  29932. @see getRawDataSize
  29933. */
  29934. uint8* getRawData() const noexcept { return data; }
  29935. /** Returns the number of bytes of data in the message.
  29936. @see getRawData
  29937. */
  29938. int getRawDataSize() const noexcept { return size; }
  29939. /** Returns the timestamp associated with this message.
  29940. The exact meaning of this time and its units will vary, as messages are used in
  29941. a variety of different contexts.
  29942. If you're getting the message from a midi file, this could be a time in seconds, or
  29943. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  29944. If the message is being used in a MidiBuffer, it might indicate the number of
  29945. audio samples from the start of the buffer.
  29946. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  29947. for details of the way that it initialises this value.
  29948. @see setTimeStamp, addToTimeStamp
  29949. */
  29950. double getTimeStamp() const noexcept { return timeStamp; }
  29951. /** Changes the message's associated timestamp.
  29952. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  29953. @see addToTimeStamp, getTimeStamp
  29954. */
  29955. void setTimeStamp (double newTimestamp) noexcept { timeStamp = newTimestamp; }
  29956. /** Adds a value to the message's timestamp.
  29957. The units for the timestamp will be application-specific.
  29958. */
  29959. void addToTimeStamp (double delta) noexcept { timeStamp += delta; }
  29960. /** Returns the midi channel associated with the message.
  29961. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  29962. if it's a sysex)
  29963. @see isForChannel, setChannel
  29964. */
  29965. int getChannel() const noexcept;
  29966. /** Returns true if the message applies to the given midi channel.
  29967. @param channelNumber the channel number to look for, in the range 1 to 16
  29968. @see getChannel, setChannel
  29969. */
  29970. bool isForChannel (int channelNumber) const noexcept;
  29971. /** Changes the message's midi channel.
  29972. This won't do anything for non-channel messages like sysexes.
  29973. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  29974. */
  29975. void setChannel (int newChannelNumber) noexcept;
  29976. /** Returns true if this is a system-exclusive message.
  29977. */
  29978. bool isSysEx() const noexcept;
  29979. /** Returns a pointer to the sysex data inside the message.
  29980. If this event isn't a sysex event, it'll return 0.
  29981. @see getSysExDataSize
  29982. */
  29983. const uint8* getSysExData() const noexcept;
  29984. /** Returns the size of the sysex data.
  29985. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  29986. @see getSysExData
  29987. */
  29988. int getSysExDataSize() const noexcept;
  29989. /** Returns true if this message is a 'key-down' event.
  29990. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  29991. velocity 0, it will still be considered to be a note-on and the
  29992. method will return true. If returnTrueForVelocity0 is false, then
  29993. if this is a note-on event with velocity 0, it'll be regarded as
  29994. a note-off, and the method will return false
  29995. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  29996. */
  29997. bool isNoteOn (bool returnTrueForVelocity0 = false) const noexcept;
  29998. /** Creates a key-down message (using a floating-point velocity).
  29999. @param channel the midi channel, in the range 1 to 16
  30000. @param noteNumber the key number, 0 to 127
  30001. @param velocity in the range 0 to 1.0
  30002. @see isNoteOn
  30003. */
  30004. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) noexcept;
  30005. /** Creates a key-down message (using an integer velocity).
  30006. @param channel the midi channel, in the range 1 to 16
  30007. @param noteNumber the key number, 0 to 127
  30008. @param velocity in the range 0 to 127
  30009. @see isNoteOn
  30010. */
  30011. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) noexcept;
  30012. /** Returns true if this message is a 'key-up' event.
  30013. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  30014. for a note-on event with a velocity of 0.
  30015. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  30016. */
  30017. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const noexcept;
  30018. /** Creates a key-up message.
  30019. @param channel the midi channel, in the range 1 to 16
  30020. @param noteNumber the key number, 0 to 127
  30021. @param velocity in the range 0 to 127
  30022. @see isNoteOff
  30023. */
  30024. static const MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) noexcept;
  30025. /** Returns true if this message is a 'key-down' or 'key-up' event.
  30026. @see isNoteOn, isNoteOff
  30027. */
  30028. bool isNoteOnOrOff() const noexcept;
  30029. /** Returns the midi note number for note-on and note-off messages.
  30030. If the message isn't a note-on or off, the value returned will be
  30031. meaningless.
  30032. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  30033. */
  30034. int getNoteNumber() const noexcept;
  30035. /** Changes the midi note number of a note-on or note-off message.
  30036. If the message isn't a note on or off, this will do nothing.
  30037. */
  30038. void setNoteNumber (int newNoteNumber) noexcept;
  30039. /** Returns the velocity of a note-on or note-off message.
  30040. The value returned will be in the range 0 to 127.
  30041. If the message isn't a note-on or off event, it will return 0.
  30042. @see getFloatVelocity
  30043. */
  30044. uint8 getVelocity() const noexcept;
  30045. /** Returns the velocity of a note-on or note-off message.
  30046. The value returned will be in the range 0 to 1.0
  30047. If the message isn't a note-on or off event, it will return 0.
  30048. @see getVelocity, setVelocity
  30049. */
  30050. float getFloatVelocity() const noexcept;
  30051. /** Changes the velocity of a note-on or note-off message.
  30052. If the message isn't a note on or off, this will do nothing.
  30053. @param newVelocity the new velocity, in the range 0 to 1.0
  30054. @see getFloatVelocity, multiplyVelocity
  30055. */
  30056. void setVelocity (float newVelocity) noexcept;
  30057. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  30058. If the message isn't a note on or off, this will do nothing.
  30059. @param scaleFactor the value by which to multiply the velocity
  30060. @see setVelocity
  30061. */
  30062. void multiplyVelocity (float scaleFactor) noexcept;
  30063. /** Returns true if the message is a program (patch) change message.
  30064. @see getProgramChangeNumber, getGMInstrumentName
  30065. */
  30066. bool isProgramChange() const noexcept;
  30067. /** Returns the new program number of a program change message.
  30068. If the message isn't a program change, the value returned will be
  30069. nonsense.
  30070. @see isProgramChange, getGMInstrumentName
  30071. */
  30072. int getProgramChangeNumber() const noexcept;
  30073. /** Creates a program-change message.
  30074. @param channel the midi channel, in the range 1 to 16
  30075. @param programNumber the midi program number, 0 to 127
  30076. @see isProgramChange, getGMInstrumentName
  30077. */
  30078. static const MidiMessage programChange (int channel, int programNumber) noexcept;
  30079. /** Returns true if the message is a pitch-wheel move.
  30080. @see getPitchWheelValue, pitchWheel
  30081. */
  30082. bool isPitchWheel() const noexcept;
  30083. /** Returns the pitch wheel position from a pitch-wheel move message.
  30084. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  30085. If called for messages which aren't pitch wheel events, the number returned will be
  30086. nonsense.
  30087. @see isPitchWheel
  30088. */
  30089. int getPitchWheelValue() const noexcept;
  30090. /** Creates a pitch-wheel move message.
  30091. @param channel the midi channel, in the range 1 to 16
  30092. @param position the wheel position, in the range 0 to 16383
  30093. @see isPitchWheel
  30094. */
  30095. static const MidiMessage pitchWheel (int channel, int position) noexcept;
  30096. /** Returns true if the message is an aftertouch event.
  30097. For aftertouch events, use the getNoteNumber() method to find out the key
  30098. that it applies to, and getAftertouchValue() to find out the amount. Use
  30099. getChannel() to find out the channel.
  30100. @see getAftertouchValue, getNoteNumber
  30101. */
  30102. bool isAftertouch() const noexcept;
  30103. /** Returns the amount of aftertouch from an aftertouch messages.
  30104. The value returned is in the range 0 to 127, and will be nonsense for messages
  30105. other than aftertouch messages.
  30106. @see isAftertouch
  30107. */
  30108. int getAfterTouchValue() const noexcept;
  30109. /** Creates an aftertouch message.
  30110. @param channel the midi channel, in the range 1 to 16
  30111. @param noteNumber the key number, 0 to 127
  30112. @param aftertouchAmount the amount of aftertouch, 0 to 127
  30113. @see isAftertouch
  30114. */
  30115. static const MidiMessage aftertouchChange (int channel,
  30116. int noteNumber,
  30117. int aftertouchAmount) noexcept;
  30118. /** Returns true if the message is a channel-pressure change event.
  30119. This is like aftertouch, but common to the whole channel rather than a specific
  30120. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  30121. to find out the channel.
  30122. @see channelPressureChange
  30123. */
  30124. bool isChannelPressure() const noexcept;
  30125. /** Returns the pressure from a channel pressure change message.
  30126. @returns the pressure, in the range 0 to 127
  30127. @see isChannelPressure, channelPressureChange
  30128. */
  30129. int getChannelPressureValue() const noexcept;
  30130. /** Creates a channel-pressure change event.
  30131. @param channel the midi channel: 1 to 16
  30132. @param pressure the pressure, 0 to 127
  30133. @see isChannelPressure
  30134. */
  30135. static const MidiMessage channelPressureChange (int channel, int pressure) noexcept;
  30136. /** Returns true if this is a midi controller message.
  30137. @see getControllerNumber, getControllerValue, controllerEvent
  30138. */
  30139. bool isController() const noexcept;
  30140. /** Returns the controller number of a controller message.
  30141. The name of the controller can be looked up using the getControllerName() method.
  30142. Note that the value returned is invalid for messages that aren't controller changes.
  30143. @see isController, getControllerName, getControllerValue
  30144. */
  30145. int getControllerNumber() const noexcept;
  30146. /** Returns the controller value from a controller message.
  30147. A value 0 to 127 is returned to indicate the new controller position.
  30148. Note that the value returned is invalid for messages that aren't controller changes.
  30149. @see isController, getControllerNumber
  30150. */
  30151. int getControllerValue() const noexcept;
  30152. /** Creates a controller message.
  30153. @param channel the midi channel, in the range 1 to 16
  30154. @param controllerType the type of controller
  30155. @param value the controller value
  30156. @see isController
  30157. */
  30158. static const MidiMessage controllerEvent (int channel,
  30159. int controllerType,
  30160. int value) noexcept;
  30161. /** Checks whether this message is an all-notes-off message.
  30162. @see allNotesOff
  30163. */
  30164. bool isAllNotesOff() const noexcept;
  30165. /** Checks whether this message is an all-sound-off message.
  30166. @see allSoundOff
  30167. */
  30168. bool isAllSoundOff() const noexcept;
  30169. /** Creates an all-notes-off message.
  30170. @param channel the midi channel, in the range 1 to 16
  30171. @see isAllNotesOff
  30172. */
  30173. static const MidiMessage allNotesOff (int channel) noexcept;
  30174. /** Creates an all-sound-off message.
  30175. @param channel the midi channel, in the range 1 to 16
  30176. @see isAllSoundOff
  30177. */
  30178. static const MidiMessage allSoundOff (int channel) noexcept;
  30179. /** Creates an all-controllers-off message.
  30180. @param channel the midi channel, in the range 1 to 16
  30181. */
  30182. static const MidiMessage allControllersOff (int channel) noexcept;
  30183. /** Returns true if this event is a meta-event.
  30184. Meta-events are things like tempo changes, track names, etc.
  30185. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30186. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30187. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30188. */
  30189. bool isMetaEvent() const noexcept;
  30190. /** Returns a meta-event's type number.
  30191. If the message isn't a meta-event, this will return -1.
  30192. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30193. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30194. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30195. */
  30196. int getMetaEventType() const noexcept;
  30197. /** Returns a pointer to the data in a meta-event.
  30198. @see isMetaEvent, getMetaEventLength
  30199. */
  30200. const uint8* getMetaEventData() const noexcept;
  30201. /** Returns the length of the data for a meta-event.
  30202. @see isMetaEvent, getMetaEventData
  30203. */
  30204. int getMetaEventLength() const noexcept;
  30205. /** Returns true if this is a 'track' meta-event. */
  30206. bool isTrackMetaEvent() const noexcept;
  30207. /** Returns true if this is an 'end-of-track' meta-event. */
  30208. bool isEndOfTrackMetaEvent() const noexcept;
  30209. /** Creates an end-of-track meta-event.
  30210. @see isEndOfTrackMetaEvent
  30211. */
  30212. static const MidiMessage endOfTrack() noexcept;
  30213. /** Returns true if this is an 'track name' meta-event.
  30214. You can use the getTextFromTextMetaEvent() method to get the track's name.
  30215. */
  30216. bool isTrackNameEvent() const noexcept;
  30217. /** Returns true if this is a 'text' meta-event.
  30218. @see getTextFromTextMetaEvent
  30219. */
  30220. bool isTextMetaEvent() const noexcept;
  30221. /** Returns the text from a text meta-event.
  30222. @see isTextMetaEvent
  30223. */
  30224. const String getTextFromTextMetaEvent() const;
  30225. /** Returns true if this is a 'tempo' meta-event.
  30226. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  30227. */
  30228. bool isTempoMetaEvent() const noexcept;
  30229. /** Returns the tick length from a tempo meta-event.
  30230. @param timeFormat the 16-bit time format value from the midi file's header.
  30231. @returns the tick length (in seconds).
  30232. @see isTempoMetaEvent
  30233. */
  30234. double getTempoMetaEventTickLength (short timeFormat) const noexcept;
  30235. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  30236. @see isTempoMetaEvent, getTempoMetaEventTickLength
  30237. */
  30238. double getTempoSecondsPerQuarterNote() const noexcept;
  30239. /** Creates a tempo meta-event.
  30240. @see isTempoMetaEvent
  30241. */
  30242. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) noexcept;
  30243. /** Returns true if this is a 'time-signature' meta-event.
  30244. @see getTimeSignatureInfo
  30245. */
  30246. bool isTimeSignatureMetaEvent() const noexcept;
  30247. /** Returns the time-signature values from a time-signature meta-event.
  30248. @see isTimeSignatureMetaEvent
  30249. */
  30250. void getTimeSignatureInfo (int& numerator, int& denominator) const noexcept;
  30251. /** Creates a time-signature meta-event.
  30252. @see isTimeSignatureMetaEvent
  30253. */
  30254. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  30255. /** Returns true if this is a 'key-signature' meta-event.
  30256. @see getKeySignatureNumberOfSharpsOrFlats
  30257. */
  30258. bool isKeySignatureMetaEvent() const noexcept;
  30259. /** Returns the key from a key-signature meta-event.
  30260. @see isKeySignatureMetaEvent
  30261. */
  30262. int getKeySignatureNumberOfSharpsOrFlats() const noexcept;
  30263. /** Returns true if this is a 'channel' meta-event.
  30264. A channel meta-event specifies the midi channel that should be used
  30265. for subsequent meta-events.
  30266. @see getMidiChannelMetaEventChannel
  30267. */
  30268. bool isMidiChannelMetaEvent() const noexcept;
  30269. /** Returns the channel number from a channel meta-event.
  30270. @returns the channel, in the range 1 to 16.
  30271. @see isMidiChannelMetaEvent
  30272. */
  30273. int getMidiChannelMetaEventChannel() const noexcept;
  30274. /** Creates a midi channel meta-event.
  30275. @param channel the midi channel, in the range 1 to 16
  30276. @see isMidiChannelMetaEvent
  30277. */
  30278. static const MidiMessage midiChannelMetaEvent (int channel) noexcept;
  30279. /** Returns true if this is an active-sense message. */
  30280. bool isActiveSense() const noexcept;
  30281. /** Returns true if this is a midi start event.
  30282. @see midiStart
  30283. */
  30284. bool isMidiStart() const noexcept;
  30285. /** Creates a midi start event. */
  30286. static const MidiMessage midiStart() noexcept;
  30287. /** Returns true if this is a midi continue event.
  30288. @see midiContinue
  30289. */
  30290. bool isMidiContinue() const noexcept;
  30291. /** Creates a midi continue event. */
  30292. static const MidiMessage midiContinue() noexcept;
  30293. /** Returns true if this is a midi stop event.
  30294. @see midiStop
  30295. */
  30296. bool isMidiStop() const noexcept;
  30297. /** Creates a midi stop event. */
  30298. static const MidiMessage midiStop() noexcept;
  30299. /** Returns true if this is a midi clock event.
  30300. @see midiClock, songPositionPointer
  30301. */
  30302. bool isMidiClock() const noexcept;
  30303. /** Creates a midi clock event. */
  30304. static const MidiMessage midiClock() noexcept;
  30305. /** Returns true if this is a song-position-pointer message.
  30306. @see getSongPositionPointerMidiBeat, songPositionPointer
  30307. */
  30308. bool isSongPositionPointer() const noexcept;
  30309. /** Returns the midi beat-number of a song-position-pointer message.
  30310. @see isSongPositionPointer, songPositionPointer
  30311. */
  30312. int getSongPositionPointerMidiBeat() const noexcept;
  30313. /** Creates a song-position-pointer message.
  30314. The position is a number of midi beats from the start of the song, where 1 midi
  30315. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  30316. are 4 midi beats in a quarter-note.
  30317. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  30318. */
  30319. static const MidiMessage songPositionPointer (int positionInMidiBeats) noexcept;
  30320. /** Returns true if this is a quarter-frame midi timecode message.
  30321. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  30322. */
  30323. bool isQuarterFrame() const noexcept;
  30324. /** Returns the sequence number of a quarter-frame midi timecode message.
  30325. This will be a value between 0 and 7.
  30326. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  30327. */
  30328. int getQuarterFrameSequenceNumber() const noexcept;
  30329. /** Returns the value from a quarter-frame message.
  30330. This will be the lower nybble of the message's data-byte, a value
  30331. between 0 and 15
  30332. */
  30333. int getQuarterFrameValue() const noexcept;
  30334. /** Creates a quarter-frame MTC message.
  30335. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  30336. @param value a value 0 to 15 for the lower nybble of the message's data byte
  30337. */
  30338. static const MidiMessage quarterFrame (int sequenceNumber, int value) noexcept;
  30339. /** SMPTE timecode types.
  30340. Used by the getFullFrameParameters() and fullFrame() methods.
  30341. */
  30342. enum SmpteTimecodeType
  30343. {
  30344. fps24 = 0,
  30345. fps25 = 1,
  30346. fps30drop = 2,
  30347. fps30 = 3
  30348. };
  30349. /** Returns true if this is a full-frame midi timecode message.
  30350. */
  30351. bool isFullFrame() const noexcept;
  30352. /** Extracts the timecode information from a full-frame midi timecode message.
  30353. You should only call this on messages where you've used isFullFrame() to
  30354. check that they're the right kind.
  30355. */
  30356. void getFullFrameParameters (int& hours,
  30357. int& minutes,
  30358. int& seconds,
  30359. int& frames,
  30360. SmpteTimecodeType& timecodeType) const noexcept;
  30361. /** Creates a full-frame MTC message.
  30362. */
  30363. static const MidiMessage fullFrame (int hours,
  30364. int minutes,
  30365. int seconds,
  30366. int frames,
  30367. SmpteTimecodeType timecodeType);
  30368. /** Types of MMC command.
  30369. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  30370. */
  30371. enum MidiMachineControlCommand
  30372. {
  30373. mmc_stop = 1,
  30374. mmc_play = 2,
  30375. mmc_deferredplay = 3,
  30376. mmc_fastforward = 4,
  30377. mmc_rewind = 5,
  30378. mmc_recordStart = 6,
  30379. mmc_recordStop = 7,
  30380. mmc_pause = 9
  30381. };
  30382. /** Checks whether this is an MMC message.
  30383. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  30384. */
  30385. bool isMidiMachineControlMessage() const noexcept;
  30386. /** For an MMC message, this returns its type.
  30387. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  30388. calling this method.
  30389. */
  30390. MidiMachineControlCommand getMidiMachineControlCommand() const noexcept;
  30391. /** Creates an MMC message.
  30392. */
  30393. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  30394. /** Checks whether this is an MMC "goto" message.
  30395. If it is, the parameters passed-in are set to the time that the message contains.
  30396. @see midiMachineControlGoto
  30397. */
  30398. bool isMidiMachineControlGoto (int& hours,
  30399. int& minutes,
  30400. int& seconds,
  30401. int& frames) const noexcept;
  30402. /** Creates an MMC "goto" message.
  30403. This messages tells the device to go to a specific frame.
  30404. @see isMidiMachineControlGoto
  30405. */
  30406. static const MidiMessage midiMachineControlGoto (int hours,
  30407. int minutes,
  30408. int seconds,
  30409. int frames);
  30410. /** Creates a master-volume change message.
  30411. @param volume the volume, 0 to 1.0
  30412. */
  30413. static const MidiMessage masterVolume (float volume);
  30414. /** Creates a system-exclusive message.
  30415. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  30416. */
  30417. static const MidiMessage createSysExMessage (const uint8* sysexData,
  30418. int dataSize);
  30419. /** Reads a midi variable-length integer.
  30420. @param data the data to read the number from
  30421. @param numBytesUsed on return, this will be set to the number of bytes that were read
  30422. */
  30423. static int readVariableLengthVal (const uint8* data,
  30424. int& numBytesUsed) noexcept;
  30425. /** Based on the first byte of a short midi message, this uses a lookup table
  30426. to return the message length (either 1, 2, or 3 bytes).
  30427. The value passed in must be 0x80 or higher.
  30428. */
  30429. static int getMessageLengthFromFirstByte (const uint8 firstByte) noexcept;
  30430. /** Returns the name of a midi note number.
  30431. E.g "C", "D#", etc.
  30432. @param noteNumber the midi note number, 0 to 127
  30433. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  30434. they'll be flattened, e.g. "Db"
  30435. @param includeOctaveNumber if true, the octave number will be appended to the string,
  30436. e.g. "C#4"
  30437. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  30438. number that will be used for middle C's octave
  30439. @see getMidiNoteInHertz
  30440. */
  30441. static const String getMidiNoteName (int noteNumber,
  30442. bool useSharps,
  30443. bool includeOctaveNumber,
  30444. int octaveNumForMiddleC);
  30445. /** Returns the frequency of a midi note number.
  30446. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  30447. @see getMidiNoteName
  30448. */
  30449. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) noexcept;
  30450. /** Returns the standard name of a GM instrument.
  30451. @param midiInstrumentNumber the program number 0 to 127
  30452. @see getProgramChangeNumber
  30453. */
  30454. static const String getGMInstrumentName (int midiInstrumentNumber);
  30455. /** Returns the name of a bank of GM instruments.
  30456. @param midiBankNumber the bank, 0 to 15
  30457. */
  30458. static const String getGMInstrumentBankName (int midiBankNumber);
  30459. /** Returns the standard name of a channel 10 percussion sound.
  30460. @param midiNoteNumber the key number, 35 to 81
  30461. */
  30462. static const String getRhythmInstrumentName (int midiNoteNumber);
  30463. /** Returns the name of a controller type number.
  30464. @see getControllerNumber
  30465. */
  30466. static const String getControllerName (int controllerNumber);
  30467. private:
  30468. double timeStamp;
  30469. uint8* data;
  30470. int size;
  30471. #ifndef DOXYGEN
  30472. union
  30473. {
  30474. uint8 asBytes[4];
  30475. uint32 asInt32;
  30476. } preallocatedData;
  30477. #endif
  30478. };
  30479. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  30480. /*** End of inlined file: juce_MidiMessage.h ***/
  30481. class MidiInput;
  30482. /**
  30483. Receives incoming messages from a physical MIDI input device.
  30484. This class is overridden to handle incoming midi messages. See the MidiInput
  30485. class for more details.
  30486. @see MidiInput
  30487. */
  30488. class JUCE_API MidiInputCallback
  30489. {
  30490. public:
  30491. /** Destructor. */
  30492. virtual ~MidiInputCallback() {}
  30493. /** Receives an incoming message.
  30494. A MidiInput object will call this method when a midi event arrives. It'll be
  30495. called on a high-priority system thread, so avoid doing anything time-consuming
  30496. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  30497. for queueing incoming messages for use later.
  30498. @param source the MidiInput object that generated the message
  30499. @param message the incoming message. The message's timestamp is set to a value
  30500. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  30501. time when the message arrived.
  30502. */
  30503. virtual void handleIncomingMidiMessage (MidiInput* source,
  30504. const MidiMessage& message) = 0;
  30505. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  30506. If a long sysex message is broken up into multiple packets, this callback is made
  30507. for each packet that arrives until the message is finished, at which point
  30508. the normal handleIncomingMidiMessage() callback will be made with the entire
  30509. message.
  30510. The message passed in will contain the start of a sysex, but won't be finished
  30511. with the terminating 0xf7 byte.
  30512. */
  30513. virtual void handlePartialSysexMessage (MidiInput* source,
  30514. const uint8* messageData,
  30515. const int numBytesSoFar,
  30516. const double timestamp)
  30517. {
  30518. // (this bit is just to avoid compiler warnings about unused variables)
  30519. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  30520. }
  30521. };
  30522. /**
  30523. Represents a midi input device.
  30524. To create one of these, use the static getDevices() method to find out what inputs are
  30525. available, and then use the openDevice() method to try to open one.
  30526. @see MidiOutput
  30527. */
  30528. class JUCE_API MidiInput
  30529. {
  30530. public:
  30531. /** Returns a list of the available midi input devices.
  30532. You can open one of the devices by passing its index into the
  30533. openDevice() method.
  30534. @see getDefaultDeviceIndex, openDevice
  30535. */
  30536. static const StringArray getDevices();
  30537. /** Returns the index of the default midi input device to use.
  30538. This refers to the index in the list returned by getDevices().
  30539. */
  30540. static int getDefaultDeviceIndex();
  30541. /** Tries to open one of the midi input devices.
  30542. This will return a MidiInput object if it manages to open it. You can then
  30543. call start() and stop() on this device, and delete it when no longer needed.
  30544. If the device can't be opened, this will return a null pointer.
  30545. @param deviceIndex the index of a device from the list returned by getDevices()
  30546. @param callback the object that will receive the midi messages from this device.
  30547. @see MidiInputCallback, getDevices
  30548. */
  30549. static MidiInput* openDevice (int deviceIndex,
  30550. MidiInputCallback* callback);
  30551. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30552. /** This will try to create a new midi input device (Not available on Windows).
  30553. This will attempt to create a new midi input device with the specified name,
  30554. for other apps to connect to.
  30555. Returns 0 if a device can't be created.
  30556. @param deviceName the name to use for the new device
  30557. @param callback the object that will receive the midi messages from this device.
  30558. */
  30559. static MidiInput* createNewDevice (const String& deviceName,
  30560. MidiInputCallback* callback);
  30561. #endif
  30562. /** Destructor. */
  30563. virtual ~MidiInput();
  30564. /** Returns the name of this device.
  30565. */
  30566. virtual const String getName() const noexcept { return name; }
  30567. /** Allows you to set a custom name for the device, in case you don't like the name
  30568. it was given when created.
  30569. */
  30570. virtual void setName (const String& newName) noexcept { name = newName; }
  30571. /** Starts the device running.
  30572. After calling this, the device will start sending midi messages to the
  30573. MidiInputCallback object that was specified when the openDevice() method
  30574. was called.
  30575. @see stop
  30576. */
  30577. virtual void start();
  30578. /** Stops the device running.
  30579. @see start
  30580. */
  30581. virtual void stop();
  30582. protected:
  30583. String name;
  30584. void* internal;
  30585. explicit MidiInput (const String& name);
  30586. private:
  30587. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  30588. };
  30589. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  30590. /*** End of inlined file: juce_MidiInput.h ***/
  30591. /*** Start of inlined file: juce_MidiOutput.h ***/
  30592. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  30593. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  30594. /*** Start of inlined file: juce_MidiBuffer.h ***/
  30595. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  30596. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  30597. /**
  30598. Holds a sequence of time-stamped midi events.
  30599. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  30600. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  30601. @see MidiMessage
  30602. */
  30603. class JUCE_API MidiBuffer
  30604. {
  30605. public:
  30606. /** Creates an empty MidiBuffer. */
  30607. MidiBuffer() noexcept;
  30608. /** Creates a MidiBuffer containing a single midi message. */
  30609. explicit MidiBuffer (const MidiMessage& message) noexcept;
  30610. /** Creates a copy of another MidiBuffer. */
  30611. MidiBuffer (const MidiBuffer& other) noexcept;
  30612. /** Makes a copy of another MidiBuffer. */
  30613. MidiBuffer& operator= (const MidiBuffer& other) noexcept;
  30614. /** Destructor */
  30615. ~MidiBuffer();
  30616. /** Removes all events from the buffer. */
  30617. void clear() noexcept;
  30618. /** Removes all events between two times from the buffer.
  30619. All events for which (start <= event position < start + numSamples) will
  30620. be removed.
  30621. */
  30622. void clear (int start, int numSamples);
  30623. /** Returns true if the buffer is empty.
  30624. To actually retrieve the events, use a MidiBuffer::Iterator object
  30625. */
  30626. bool isEmpty() const noexcept;
  30627. /** Counts the number of events in the buffer.
  30628. This is actually quite a slow operation, as it has to iterate through all
  30629. the events, so you might prefer to call isEmpty() if that's all you need
  30630. to know.
  30631. */
  30632. int getNumEvents() const noexcept;
  30633. /** Adds an event to the buffer.
  30634. The sample number will be used to determine the position of the event in
  30635. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  30636. ignored.
  30637. If an event is added whose sample position is the same as one or more events
  30638. already in the buffer, the new event will be placed after the existing ones.
  30639. To retrieve events, use a MidiBuffer::Iterator object
  30640. */
  30641. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  30642. /** Adds an event to the buffer from raw midi data.
  30643. The sample number will be used to determine the position of the event in
  30644. the buffer, which is always kept sorted.
  30645. If an event is added whose sample position is the same as one or more events
  30646. already in the buffer, the new event will be placed after the existing ones.
  30647. The event data will be inspected to calculate the number of bytes in length that
  30648. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  30649. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  30650. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  30651. add an event at all.
  30652. To retrieve events, use a MidiBuffer::Iterator object
  30653. */
  30654. void addEvent (const void* rawMidiData,
  30655. int maxBytesOfMidiData,
  30656. int sampleNumber);
  30657. /** Adds some events from another buffer to this one.
  30658. @param otherBuffer the buffer containing the events you want to add
  30659. @param startSample the lowest sample number in the source buffer for which
  30660. events should be added. Any source events whose timestamp is
  30661. less than this will be ignored
  30662. @param numSamples the valid range of samples from the source buffer for which
  30663. events should be added - i.e. events in the source buffer whose
  30664. timestamp is greater than or equal to (startSample + numSamples)
  30665. will be ignored. If this value is less than 0, all events after
  30666. startSample will be taken.
  30667. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  30668. that are added to this buffer
  30669. */
  30670. void addEvents (const MidiBuffer& otherBuffer,
  30671. int startSample,
  30672. int numSamples,
  30673. int sampleDeltaToAdd);
  30674. /** Returns the sample number of the first event in the buffer.
  30675. If the buffer's empty, this will just return 0.
  30676. */
  30677. int getFirstEventTime() const noexcept;
  30678. /** Returns the sample number of the last event in the buffer.
  30679. If the buffer's empty, this will just return 0.
  30680. */
  30681. int getLastEventTime() const noexcept;
  30682. /** Exchanges the contents of this buffer with another one.
  30683. This is a quick operation, because no memory allocating or copying is done, it
  30684. just swaps the internal state of the two buffers.
  30685. */
  30686. void swapWith (MidiBuffer& other) noexcept;
  30687. /** Preallocates some memory for the buffer to use.
  30688. This helps to avoid needing to reallocate space when the buffer has messages
  30689. added to it.
  30690. */
  30691. void ensureSize (size_t minimumNumBytes);
  30692. /**
  30693. Used to iterate through the events in a MidiBuffer.
  30694. Note that altering the buffer while an iterator is using it isn't a
  30695. safe operation.
  30696. @see MidiBuffer
  30697. */
  30698. class JUCE_API Iterator
  30699. {
  30700. public:
  30701. /** Creates an Iterator for this MidiBuffer. */
  30702. Iterator (const MidiBuffer& buffer) noexcept;
  30703. /** Destructor. */
  30704. ~Iterator() noexcept;
  30705. /** Repositions the iterator so that the next event retrieved will be the first
  30706. one whose sample position is at greater than or equal to the given position.
  30707. */
  30708. void setNextSamplePosition (int samplePosition) noexcept;
  30709. /** Retrieves a copy of the next event from the buffer.
  30710. @param result on return, this will be the message (the MidiMessage's timestamp
  30711. is not set)
  30712. @param samplePosition on return, this will be the position of the event
  30713. @returns true if an event was found, or false if the iterator has reached
  30714. the end of the buffer
  30715. */
  30716. bool getNextEvent (MidiMessage& result,
  30717. int& samplePosition) noexcept;
  30718. /** Retrieves the next event from the buffer.
  30719. @param midiData on return, this pointer will be set to a block of data containing
  30720. the midi message. Note that to make it fast, this is a pointer
  30721. directly into the MidiBuffer's internal data, so is only valid
  30722. temporarily until the MidiBuffer is altered.
  30723. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  30724. midi message
  30725. @param samplePosition on return, this will be the position of the event
  30726. @returns true if an event was found, or false if the iterator has reached
  30727. the end of the buffer
  30728. */
  30729. bool getNextEvent (const uint8* &midiData,
  30730. int& numBytesOfMidiData,
  30731. int& samplePosition) noexcept;
  30732. private:
  30733. const MidiBuffer& buffer;
  30734. const uint8* data;
  30735. JUCE_DECLARE_NON_COPYABLE (Iterator);
  30736. };
  30737. private:
  30738. friend class MidiBuffer::Iterator;
  30739. MemoryBlock data;
  30740. int bytesUsed;
  30741. uint8* getData() const noexcept;
  30742. uint8* findEventAfter (uint8* d, int samplePosition) const noexcept;
  30743. static int getEventTime (const void* d) noexcept;
  30744. static uint16 getEventDataSize (const void* d) noexcept;
  30745. static uint16 getEventTotalSize (const void* d) noexcept;
  30746. JUCE_LEAK_DETECTOR (MidiBuffer);
  30747. };
  30748. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  30749. /*** End of inlined file: juce_MidiBuffer.h ***/
  30750. /**
  30751. Controls a physical MIDI output device.
  30752. To create one of these, use the static getDevices() method to get a list of the
  30753. available output devices, then use the openDevice() method to try to open one.
  30754. @see MidiInput
  30755. */
  30756. class JUCE_API MidiOutput : private Thread
  30757. {
  30758. public:
  30759. /** Returns a list of the available midi output devices.
  30760. You can open one of the devices by passing its index into the
  30761. openDevice() method.
  30762. @see getDefaultDeviceIndex, openDevice
  30763. */
  30764. static const StringArray getDevices();
  30765. /** Returns the index of the default midi output device to use.
  30766. This refers to the index in the list returned by getDevices().
  30767. */
  30768. static int getDefaultDeviceIndex();
  30769. /** Tries to open one of the midi output devices.
  30770. This will return a MidiOutput object if it manages to open it. You can then
  30771. send messages to this device, and delete it when no longer needed.
  30772. If the device can't be opened, this will return a null pointer.
  30773. @param deviceIndex the index of a device from the list returned by getDevices()
  30774. @see getDevices
  30775. */
  30776. static MidiOutput* openDevice (int deviceIndex);
  30777. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30778. /** This will try to create a new midi output device (Not available on Windows).
  30779. This will attempt to create a new midi output device that other apps can connect
  30780. to and use as their midi input.
  30781. Returns 0 if a device can't be created.
  30782. @param deviceName the name to use for the new device
  30783. */
  30784. static MidiOutput* createNewDevice (const String& deviceName);
  30785. #endif
  30786. /** Destructor. */
  30787. virtual ~MidiOutput();
  30788. /** Makes this device output a midi message.
  30789. @see MidiMessage
  30790. */
  30791. virtual void sendMessageNow (const MidiMessage& message);
  30792. /** Sends a midi reset to the device. */
  30793. virtual void reset();
  30794. /** Returns the current volume setting for this device. */
  30795. virtual bool getVolume (float& leftVol,
  30796. float& rightVol);
  30797. /** Changes the overall volume for this device. */
  30798. virtual void setVolume (float leftVol,
  30799. float rightVol);
  30800. /** This lets you supply a block of messages that will be sent out at some point
  30801. in the future.
  30802. The MidiOutput class has an internal thread that can send out timestamped
  30803. messages - this appends a set of messages to its internal buffer, ready for
  30804. sending.
  30805. This will only work if you've already started the thread with startBackgroundThread().
  30806. A time is supplied, at which the block of messages should be sent. This time uses
  30807. the same time base as Time::getMillisecondCounter(), and must be in the future.
  30808. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  30809. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  30810. samplesPerSecondForBuffer value is needed to convert this sample position to a
  30811. real time.
  30812. */
  30813. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  30814. double millisecondCounterToStartAt,
  30815. double samplesPerSecondForBuffer);
  30816. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  30817. */
  30818. virtual void clearAllPendingMessages();
  30819. /** Starts up a background thread so that the device can send blocks of data.
  30820. Call this to get the device ready, before using sendBlockOfMessages().
  30821. */
  30822. virtual void startBackgroundThread();
  30823. /** Stops the background thread, and clears any pending midi events.
  30824. @see startBackgroundThread
  30825. */
  30826. virtual void stopBackgroundThread();
  30827. protected:
  30828. void* internal;
  30829. struct PendingMessage
  30830. {
  30831. PendingMessage (const void* data, int len, double timeStamp);
  30832. MidiMessage message;
  30833. PendingMessage* next;
  30834. };
  30835. CriticalSection lock;
  30836. PendingMessage* firstMessage;
  30837. MidiOutput();
  30838. void run();
  30839. private:
  30840. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  30841. };
  30842. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  30843. /*** End of inlined file: juce_MidiOutput.h ***/
  30844. /*** Start of inlined file: juce_ComboBox.h ***/
  30845. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  30846. #define __JUCE_COMBOBOX_JUCEHEADER__
  30847. /*** Start of inlined file: juce_Label.h ***/
  30848. #ifndef __JUCE_LABEL_JUCEHEADER__
  30849. #define __JUCE_LABEL_JUCEHEADER__
  30850. /*** Start of inlined file: juce_TextEditor.h ***/
  30851. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  30852. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  30853. /*** Start of inlined file: juce_Viewport.h ***/
  30854. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  30855. #define __JUCE_VIEWPORT_JUCEHEADER__
  30856. /*** Start of inlined file: juce_ScrollBar.h ***/
  30857. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  30858. #define __JUCE_SCROLLBAR_JUCEHEADER__
  30859. /*** Start of inlined file: juce_Button.h ***/
  30860. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30861. #define __JUCE_BUTTON_JUCEHEADER__
  30862. /*** Start of inlined file: juce_TooltipWindow.h ***/
  30863. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30864. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30865. /*** Start of inlined file: juce_TooltipClient.h ***/
  30866. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30867. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30868. /**
  30869. Components that want to use pop-up tooltips should implement this interface.
  30870. A TooltipWindow will wait for the mouse to hover over a component that
  30871. implements the TooltipClient interface, and when it finds one, it will display
  30872. the tooltip returned by its getTooltip() method.
  30873. @see TooltipWindow, SettableTooltipClient
  30874. */
  30875. class JUCE_API TooltipClient
  30876. {
  30877. public:
  30878. /** Destructor. */
  30879. virtual ~TooltipClient() {}
  30880. /** Returns the string that this object wants to show as its tooltip. */
  30881. virtual const String getTooltip() = 0;
  30882. };
  30883. /**
  30884. An implementation of TooltipClient that stores the tooltip string and a method
  30885. for changing it.
  30886. This makes it easy to add a tooltip to a custom component, by simply adding this
  30887. as a base class and calling setTooltip().
  30888. Many of the Juce widgets already use this as a base class to implement their
  30889. tooltips.
  30890. @see TooltipClient, TooltipWindow
  30891. */
  30892. class JUCE_API SettableTooltipClient : public TooltipClient
  30893. {
  30894. public:
  30895. /** Destructor. */
  30896. virtual ~SettableTooltipClient() {}
  30897. /** Assigns a new tooltip to this object. */
  30898. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  30899. /** Returns the tooltip assigned to this object. */
  30900. virtual const String getTooltip() { return tooltipString; }
  30901. protected:
  30902. SettableTooltipClient() {}
  30903. private:
  30904. String tooltipString;
  30905. };
  30906. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30907. /*** End of inlined file: juce_TooltipClient.h ***/
  30908. /**
  30909. A window that displays a pop-up tooltip when the mouse hovers over another component.
  30910. To enable tooltips in your app, just create a single instance of a TooltipWindow
  30911. object.
  30912. The TooltipWindow object will then stay invisible, waiting until the mouse
  30913. hovers for the specified length of time - it will then see if it's currently
  30914. over a component which implements the TooltipClient interface, and if so,
  30915. it will make itself visible to show the tooltip in the appropriate place.
  30916. @see TooltipClient, SettableTooltipClient
  30917. */
  30918. class JUCE_API TooltipWindow : public Component,
  30919. private Timer
  30920. {
  30921. public:
  30922. /** Creates a tooltip window.
  30923. Make sure your app only creates one instance of this class, otherwise you'll
  30924. get multiple overlaid tooltips appearing. The window will initially be invisible
  30925. and will make itself visible when it needs to display a tip.
  30926. To change the style of tooltips, see the LookAndFeel class for its tooltip
  30927. methods.
  30928. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  30929. otherwise the tooltip will be added to the given parent
  30930. component.
  30931. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  30932. before a tooltip will be shown
  30933. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  30934. */
  30935. explicit TooltipWindow (Component* parentComponent = nullptr,
  30936. int millisecondsBeforeTipAppears = 700);
  30937. /** Destructor. */
  30938. ~TooltipWindow();
  30939. /** Changes the time before the tip appears.
  30940. This lets you change the value that was set in the constructor.
  30941. */
  30942. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) noexcept;
  30943. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  30944. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30945. methods.
  30946. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30947. */
  30948. enum ColourIds
  30949. {
  30950. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  30951. textColourId = 0x1001c00, /**< The colour to use for the text. */
  30952. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  30953. };
  30954. private:
  30955. int millisecondsBeforeTipAppears;
  30956. Point<int> lastMousePos;
  30957. int mouseClicks;
  30958. unsigned int lastCompChangeTime, lastHideTime;
  30959. Component* lastComponentUnderMouse;
  30960. bool changedCompsSinceShown;
  30961. String tipShowing, lastTipUnderMouse;
  30962. void paint (Graphics& g);
  30963. void mouseEnter (const MouseEvent& e);
  30964. void timerCallback();
  30965. static const String getTipFor (Component* c);
  30966. void showFor (const String& tip);
  30967. void hide();
  30968. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  30969. };
  30970. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30971. /*** End of inlined file: juce_TooltipWindow.h ***/
  30972. #if JUCE_VC6
  30973. #define Listener ButtonListener
  30974. #endif
  30975. /**
  30976. A base class for buttons.
  30977. This contains all the logic for button behaviours such as enabling/disabling,
  30978. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  30979. and radio groups, etc.
  30980. @see TextButton, DrawableButton, ToggleButton
  30981. */
  30982. class JUCE_API Button : public Component,
  30983. public SettableTooltipClient,
  30984. public ApplicationCommandManagerListener,
  30985. public ValueListener,
  30986. private KeyListener
  30987. {
  30988. protected:
  30989. /** Creates a button.
  30990. @param buttonName the text to put in the button (the component's name is also
  30991. initially set to this string, but these can be changed later
  30992. using the setName() and setButtonText() methods)
  30993. */
  30994. explicit Button (const String& buttonName);
  30995. public:
  30996. /** Destructor. */
  30997. virtual ~Button();
  30998. /** Changes the button's text.
  30999. @see getButtonText
  31000. */
  31001. void setButtonText (const String& newText);
  31002. /** Returns the text displayed in the button.
  31003. @see setButtonText
  31004. */
  31005. const String getButtonText() const { return text; }
  31006. /** Returns true if the button is currently being held down by the mouse.
  31007. @see isOver
  31008. */
  31009. bool isDown() const noexcept;
  31010. /** Returns true if the mouse is currently over the button.
  31011. This will be also be true if the mouse is being held down.
  31012. @see isDown
  31013. */
  31014. bool isOver() const noexcept;
  31015. /** A button has an on/off state associated with it, and this changes that.
  31016. By default buttons are 'off' and for simple buttons that you click to perform
  31017. an action you won't change this. Toggle buttons, however will want to
  31018. change their state when turned on or off.
  31019. @param shouldBeOn whether to set the button's toggle state to be on or
  31020. off. If it's a member of a button group, this will
  31021. always try to turn it on, and to turn off any other
  31022. buttons in the group
  31023. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  31024. the button will be repainted but no notification will
  31025. be sent
  31026. @see getToggleState, setRadioGroupId
  31027. */
  31028. void setToggleState (bool shouldBeOn,
  31029. bool sendChangeNotification);
  31030. /** Returns true if the button in 'on'.
  31031. By default buttons are 'off' and for simple buttons that you click to perform
  31032. an action you won't change this. Toggle buttons, however will want to
  31033. change their state when turned on or off.
  31034. @see setToggleState
  31035. */
  31036. bool getToggleState() const noexcept { return isOn.getValue(); }
  31037. /** Returns the Value object that represents the botton's toggle state.
  31038. You can use this Value object to connect the button's state to external values or setters,
  31039. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  31040. your own Value object.
  31041. @see getToggleState, Value
  31042. */
  31043. Value& getToggleStateValue() { return isOn; }
  31044. /** This tells the button to automatically flip the toggle state when
  31045. the button is clicked.
  31046. If set to true, then before the clicked() callback occurs, the toggle-state
  31047. of the button is flipped.
  31048. */
  31049. void setClickingTogglesState (bool shouldToggle) noexcept;
  31050. /** Returns true if this button is set to be an automatic toggle-button.
  31051. This returns the last value that was passed to setClickingTogglesState().
  31052. */
  31053. bool getClickingTogglesState() const noexcept;
  31054. /** Enables the button to act as a member of a mutually-exclusive group
  31055. of 'radio buttons'.
  31056. If the group ID is set to a non-zero number, then this button will
  31057. act as part of a group of buttons with the same ID, only one of
  31058. which can be 'on' at the same time. Note that when it's part of
  31059. a group, clicking a toggle-button that's 'on' won't turn it off.
  31060. To find other buttons with the same ID, this button will search through
  31061. its sibling components for ToggleButtons, so all the buttons for a
  31062. particular group must be placed inside the same parent component.
  31063. Set the group ID back to zero if you want it to act as a normal toggle
  31064. button again.
  31065. @see getRadioGroupId
  31066. */
  31067. void setRadioGroupId (int newGroupId);
  31068. /** Returns the ID of the group to which this button belongs.
  31069. (See setRadioGroupId() for an explanation of this).
  31070. */
  31071. int getRadioGroupId() const noexcept { return radioGroupId; }
  31072. /**
  31073. Used to receive callbacks when a button is clicked.
  31074. @see Button::addListener, Button::removeListener
  31075. */
  31076. class JUCE_API Listener
  31077. {
  31078. public:
  31079. /** Destructor. */
  31080. virtual ~Listener() {}
  31081. /** Called when the button is clicked. */
  31082. virtual void buttonClicked (Button* button) = 0;
  31083. /** Called when the button's state changes. */
  31084. virtual void buttonStateChanged (Button*) {}
  31085. };
  31086. /** Registers a listener to receive events when this button's state changes.
  31087. If the listener is already registered, this will not register it again.
  31088. @see removeListener
  31089. */
  31090. void addListener (Listener* newListener);
  31091. /** Removes a previously-registered button listener
  31092. @see addListener
  31093. */
  31094. void removeListener (Listener* listener);
  31095. /** Causes the button to act as if it's been clicked.
  31096. This will asynchronously make the button draw itself going down and up, and
  31097. will then call back the clicked() method as if mouse was clicked on it.
  31098. @see clicked
  31099. */
  31100. virtual void triggerClick();
  31101. /** Sets a command ID for this button to automatically invoke when it's clicked.
  31102. When the button is pressed, it will use the given manager to trigger the
  31103. command ID.
  31104. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  31105. before this button is. To disable the command triggering, call this method and
  31106. pass 0 for the parameters.
  31107. If generateTooltip is true, then the button's tooltip will be automatically
  31108. generated based on the name of this command and its current shortcut key.
  31109. @see addShortcut, getCommandID
  31110. */
  31111. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  31112. int commandID,
  31113. bool generateTooltip);
  31114. /** Returns the command ID that was set by setCommandToTrigger().
  31115. */
  31116. int getCommandID() const noexcept { return commandID; }
  31117. /** Assigns a shortcut key to trigger the button.
  31118. The button registers itself with its top-level parent component for keypresses.
  31119. Note that a different way of linking buttons to keypresses is by using the
  31120. setCommandToTrigger() method to invoke a command.
  31121. @see clearShortcuts
  31122. */
  31123. void addShortcut (const KeyPress& key);
  31124. /** Removes all key shortcuts that had been set for this button.
  31125. @see addShortcut
  31126. */
  31127. void clearShortcuts();
  31128. /** Returns true if the given keypress is a shortcut for this button.
  31129. @see addShortcut
  31130. */
  31131. bool isRegisteredForShortcut (const KeyPress& key) const;
  31132. /** Sets an auto-repeat speed for the button when it is held down.
  31133. (Auto-repeat is disabled by default).
  31134. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  31135. triggering the next click. If this is zero, auto-repeat
  31136. is disabled
  31137. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  31138. triggered
  31139. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  31140. get faster, the longer the button is held down, up to the
  31141. minimum interval specified here
  31142. */
  31143. void setRepeatSpeed (int initialDelayInMillisecs,
  31144. int repeatDelayInMillisecs,
  31145. int minimumDelayInMillisecs = -1) noexcept;
  31146. /** Sets whether the button click should happen when the mouse is pressed or released.
  31147. By default the button is only considered to have been clicked when the mouse is
  31148. released, but setting this to true will make it call the clicked() method as soon
  31149. as the button is pressed.
  31150. This is useful if the button is being used to show a pop-up menu, as it allows
  31151. the click to be used as a drag onto the menu.
  31152. */
  31153. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) noexcept;
  31154. /** Returns the number of milliseconds since the last time the button
  31155. went into the 'down' state.
  31156. */
  31157. uint32 getMillisecondsSinceButtonDown() const noexcept;
  31158. /** Sets the tooltip for this button.
  31159. @see TooltipClient, TooltipWindow
  31160. */
  31161. void setTooltip (const String& newTooltip);
  31162. // (implementation of the TooltipClient method)
  31163. const String getTooltip();
  31164. /** A combination of these flags are used by setConnectedEdges().
  31165. */
  31166. enum ConnectedEdgeFlags
  31167. {
  31168. ConnectedOnLeft = 1,
  31169. ConnectedOnRight = 2,
  31170. ConnectedOnTop = 4,
  31171. ConnectedOnBottom = 8
  31172. };
  31173. /** Hints about which edges of the button might be connected to adjoining buttons.
  31174. The value passed in is a bitwise combination of any of the values in the
  31175. ConnectedEdgeFlags enum.
  31176. E.g. if you are placing two buttons adjacent to each other, you could use this to
  31177. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  31178. without rounded corners on the edges that connect. It's only a hint, so the
  31179. LookAndFeel can choose to ignore it if it's not relevent for this type of
  31180. button.
  31181. */
  31182. void setConnectedEdges (int connectedEdgeFlags);
  31183. /** Returns the set of flags passed into setConnectedEdges(). */
  31184. int getConnectedEdgeFlags() const noexcept { return connectedEdgeFlags; }
  31185. /** Indicates whether the button adjoins another one on its left edge.
  31186. @see setConnectedEdges
  31187. */
  31188. bool isConnectedOnLeft() const noexcept { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  31189. /** Indicates whether the button adjoins another one on its right edge.
  31190. @see setConnectedEdges
  31191. */
  31192. bool isConnectedOnRight() const noexcept { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  31193. /** Indicates whether the button adjoins another one on its top edge.
  31194. @see setConnectedEdges
  31195. */
  31196. bool isConnectedOnTop() const noexcept { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  31197. /** Indicates whether the button adjoins another one on its bottom edge.
  31198. @see setConnectedEdges
  31199. */
  31200. bool isConnectedOnBottom() const noexcept { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  31201. /** Used by setState(). */
  31202. enum ButtonState
  31203. {
  31204. buttonNormal,
  31205. buttonOver,
  31206. buttonDown
  31207. };
  31208. /** Can be used to force the button into a particular state.
  31209. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  31210. from happening.
  31211. The state that you set here will only last until it is automatically changed when the mouse
  31212. enters or exits the button, or the mouse-button is pressed or released.
  31213. */
  31214. void setState (const ButtonState newState);
  31215. // These are deprecated - please use addListener() and removeListener() instead!
  31216. JUCE_DEPRECATED (void addButtonListener (Listener*));
  31217. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  31218. protected:
  31219. /** This method is called when the button has been clicked.
  31220. Subclasses can override this to perform whatever they actions they need
  31221. to do.
  31222. Alternatively, a ButtonListener can be added to the button, and these listeners
  31223. will be called when the click occurs.
  31224. @see triggerClick
  31225. */
  31226. virtual void clicked();
  31227. /** This method is called when the button has been clicked.
  31228. By default it just calls clicked(), but you might want to override it to handle
  31229. things like clicking when a modifier key is pressed, etc.
  31230. @see ModifierKeys
  31231. */
  31232. virtual void clicked (const ModifierKeys& modifiers);
  31233. /** Subclasses should override this to actually paint the button's contents.
  31234. It's better to use this than the paint method, because it gives you information
  31235. about the over/down state of the button.
  31236. @param g the graphics context to use
  31237. @param isMouseOverButton true if the button is either in the 'over' or
  31238. 'down' state
  31239. @param isButtonDown true if the button should be drawn in the 'down' position
  31240. */
  31241. virtual void paintButton (Graphics& g,
  31242. bool isMouseOverButton,
  31243. bool isButtonDown) = 0;
  31244. /** Called when the button's up/down/over state changes.
  31245. Subclasses can override this if they need to do something special when the button
  31246. goes up or down.
  31247. @see isDown, isOver
  31248. */
  31249. virtual void buttonStateChanged();
  31250. /** @internal */
  31251. virtual void internalClickCallback (const ModifierKeys& modifiers);
  31252. /** @internal */
  31253. void handleCommandMessage (int commandId);
  31254. /** @internal */
  31255. void mouseEnter (const MouseEvent& e);
  31256. /** @internal */
  31257. void mouseExit (const MouseEvent& e);
  31258. /** @internal */
  31259. void mouseDown (const MouseEvent& e);
  31260. /** @internal */
  31261. void mouseDrag (const MouseEvent& e);
  31262. /** @internal */
  31263. void mouseUp (const MouseEvent& e);
  31264. /** @internal */
  31265. bool keyPressed (const KeyPress& key);
  31266. /** @internal */
  31267. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31268. /** @internal */
  31269. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  31270. /** @internal */
  31271. void paint (Graphics& g);
  31272. /** @internal */
  31273. void parentHierarchyChanged();
  31274. /** @internal */
  31275. void visibilityChanged();
  31276. /** @internal */
  31277. void focusGained (FocusChangeType cause);
  31278. /** @internal */
  31279. void focusLost (FocusChangeType cause);
  31280. /** @internal */
  31281. void enablementChanged();
  31282. /** @internal */
  31283. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  31284. /** @internal */
  31285. void applicationCommandListChanged();
  31286. /** @internal */
  31287. void valueChanged (Value& value);
  31288. private:
  31289. Array <KeyPress> shortcuts;
  31290. WeakReference<Component> keySource;
  31291. String text;
  31292. ListenerList <Listener> buttonListeners;
  31293. class RepeatTimer;
  31294. friend class RepeatTimer;
  31295. friend class ScopedPointer <RepeatTimer>;
  31296. ScopedPointer <RepeatTimer> repeatTimer;
  31297. uint32 buttonPressTime, lastRepeatTime;
  31298. ApplicationCommandManager* commandManagerToUse;
  31299. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  31300. int radioGroupId, commandID, connectedEdgeFlags;
  31301. ButtonState buttonState;
  31302. Value isOn;
  31303. bool lastToggleState : 1;
  31304. bool clickTogglesState : 1;
  31305. bool needsToRelease : 1;
  31306. bool needsRepainting : 1;
  31307. bool isKeyDown : 1;
  31308. bool triggerOnMouseDown : 1;
  31309. bool generateTooltip : 1;
  31310. void repeatTimerCallback();
  31311. RepeatTimer& getRepeatTimer();
  31312. ButtonState updateState();
  31313. ButtonState updateState (bool isOver, bool isDown);
  31314. bool isShortcutPressed() const;
  31315. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  31316. void flashButtonState();
  31317. void sendClickMessage (const ModifierKeys& modifiers);
  31318. void sendStateMessage();
  31319. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  31320. };
  31321. #ifndef DOXYGEN
  31322. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  31323. typedef Button::Listener ButtonListener;
  31324. #endif
  31325. #if JUCE_VC6
  31326. #undef Listener
  31327. #endif
  31328. #endif // __JUCE_BUTTON_JUCEHEADER__
  31329. /*** End of inlined file: juce_Button.h ***/
  31330. /**
  31331. A scrollbar component.
  31332. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  31333. sets the range of values it can represent. Then you can use setCurrentRange() to
  31334. change the position and size of the scrollbar's 'thumb'.
  31335. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  31336. the user moves it, and you can use the getCurrentRangeStart() to find out where
  31337. they moved it to.
  31338. The scrollbar will adjust its own visibility according to whether its thumb size
  31339. allows it to actually be scrolled.
  31340. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  31341. instead of handling a scrollbar directly.
  31342. @see ScrollBar::Listener
  31343. */
  31344. class JUCE_API ScrollBar : public Component,
  31345. public AsyncUpdater,
  31346. private Timer
  31347. {
  31348. public:
  31349. /** Creates a Scrollbar.
  31350. @param isVertical whether it should be a vertical or horizontal bar
  31351. @param buttonsAreVisible whether to show the up/down or left/right buttons
  31352. */
  31353. ScrollBar (bool isVertical,
  31354. bool buttonsAreVisible = true);
  31355. /** Destructor. */
  31356. ~ScrollBar();
  31357. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  31358. bool isVertical() const noexcept { return vertical; }
  31359. /** Changes the scrollbar's direction.
  31360. You'll also need to resize the bar appropriately - this just changes its internal
  31361. layout.
  31362. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  31363. */
  31364. void setOrientation (bool shouldBeVertical);
  31365. /** Shows or hides the scrollbar's buttons. */
  31366. void setButtonVisibility (bool buttonsAreVisible);
  31367. /** Tells the scrollbar whether to make itself invisible when not needed.
  31368. The default behaviour is for a scrollbar to become invisible when the thumb
  31369. fills the whole of its range (i.e. when it can't be moved). Setting this
  31370. value to false forces the bar to always be visible.
  31371. @see autoHides()
  31372. */
  31373. void setAutoHide (bool shouldHideWhenFullRange);
  31374. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  31375. as its maximum range.
  31376. @see setAutoHide
  31377. */
  31378. bool autoHides() const noexcept;
  31379. /** Sets the minimum and maximum values that the bar will move between.
  31380. The bar's thumb will always be constrained so that the entire thumb lies
  31381. within this range.
  31382. @see setCurrentRange
  31383. */
  31384. void setRangeLimits (const Range<double>& newRangeLimit);
  31385. /** Sets the minimum and maximum values that the bar will move between.
  31386. The bar's thumb will always be constrained so that the entire thumb lies
  31387. within this range.
  31388. @see setCurrentRange
  31389. */
  31390. void setRangeLimits (double minimum, double maximum);
  31391. /** Returns the current limits on the thumb position.
  31392. @see setRangeLimits
  31393. */
  31394. const Range<double> getRangeLimit() const noexcept { return totalRange; }
  31395. /** Returns the lower value that the thumb can be set to.
  31396. This is the value set by setRangeLimits().
  31397. */
  31398. double getMinimumRangeLimit() const noexcept { return totalRange.getStart(); }
  31399. /** Returns the upper value that the thumb can be set to.
  31400. This is the value set by setRangeLimits().
  31401. */
  31402. double getMaximumRangeLimit() const noexcept { return totalRange.getEnd(); }
  31403. /** Changes the position of the scrollbar's 'thumb'.
  31404. If this method call actually changes the scrollbar's position, it will trigger an
  31405. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31406. are registered.
  31407. @see getCurrentRange. setCurrentRangeStart
  31408. */
  31409. void setCurrentRange (const Range<double>& newRange);
  31410. /** Changes the position of the scrollbar's 'thumb'.
  31411. This sets both the position and size of the thumb - to just set the position without
  31412. changing the size, you can use setCurrentRangeStart().
  31413. If this method call actually changes the scrollbar's position, it will trigger an
  31414. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31415. are registered.
  31416. @param newStart the top (or left) of the thumb, in the range
  31417. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  31418. value is beyond these limits, it will be clipped.
  31419. @param newSize the size of the thumb, such that
  31420. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  31421. size is beyond these limits, it will be clipped.
  31422. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  31423. */
  31424. void setCurrentRange (double newStart, double newSize);
  31425. /** Moves the bar's thumb position.
  31426. This will move the thumb position without changing the thumb size. Note
  31427. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  31428. If this method call actually changes the scrollbar's position, it will trigger an
  31429. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31430. are registered.
  31431. @see setCurrentRange
  31432. */
  31433. void setCurrentRangeStart (double newStart);
  31434. /** Returns the current thumb range.
  31435. @see getCurrentRange, setCurrentRange
  31436. */
  31437. const Range<double> getCurrentRange() const noexcept { return visibleRange; }
  31438. /** Returns the position of the top of the thumb.
  31439. @see getCurrentRange, setCurrentRangeStart
  31440. */
  31441. double getCurrentRangeStart() const noexcept { return visibleRange.getStart(); }
  31442. /** Returns the current size of the thumb.
  31443. @see getCurrentRange, setCurrentRange
  31444. */
  31445. double getCurrentRangeSize() const noexcept { return visibleRange.getLength(); }
  31446. /** Sets the amount by which the up and down buttons will move the bar.
  31447. The value here is in terms of the total range, and is added or subtracted
  31448. from the thumb position when the user clicks an up/down (or left/right) button.
  31449. */
  31450. void setSingleStepSize (double newSingleStepSize);
  31451. /** Moves the scrollbar by a number of single-steps.
  31452. This will move the bar by a multiple of its single-step interval (as
  31453. specified using the setSingleStepSize() method).
  31454. A positive value here will move the bar down or to the right, a negative
  31455. value moves it up or to the left.
  31456. */
  31457. void moveScrollbarInSteps (int howManySteps);
  31458. /** Moves the scroll bar up or down in pages.
  31459. This will move the bar by a multiple of its current thumb size, effectively
  31460. doing a page-up or down.
  31461. A positive value here will move the bar down or to the right, a negative
  31462. value moves it up or to the left.
  31463. */
  31464. void moveScrollbarInPages (int howManyPages);
  31465. /** Scrolls to the top (or left).
  31466. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  31467. */
  31468. void scrollToTop();
  31469. /** Scrolls to the bottom (or right).
  31470. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  31471. */
  31472. void scrollToBottom();
  31473. /** Changes the delay before the up and down buttons autorepeat when they are held
  31474. down.
  31475. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  31476. @see Button::setRepeatSpeed
  31477. */
  31478. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  31479. int repeatDelayInMillisecs,
  31480. int minimumDelayInMillisecs = -1);
  31481. /** A set of colour IDs to use to change the colour of various aspects of the component.
  31482. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31483. methods.
  31484. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31485. */
  31486. enum ColourIds
  31487. {
  31488. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  31489. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  31490. 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. */
  31491. };
  31492. /**
  31493. A class for receiving events from a ScrollBar.
  31494. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  31495. method, and it will be called when the bar's position changes.
  31496. @see ScrollBar::addListener, ScrollBar::removeListener
  31497. */
  31498. class JUCE_API Listener
  31499. {
  31500. public:
  31501. /** Destructor. */
  31502. virtual ~Listener() {}
  31503. /** Called when a ScrollBar is moved.
  31504. @param scrollBarThatHasMoved the bar that has moved
  31505. @param newRangeStart the new range start of this bar
  31506. */
  31507. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  31508. double newRangeStart) = 0;
  31509. };
  31510. /** Registers a listener that will be called when the scrollbar is moved. */
  31511. void addListener (Listener* listener);
  31512. /** Deregisters a previously-registered listener. */
  31513. void removeListener (Listener* listener);
  31514. /** @internal */
  31515. bool keyPressed (const KeyPress& key);
  31516. /** @internal */
  31517. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31518. /** @internal */
  31519. void lookAndFeelChanged();
  31520. /** @internal */
  31521. void handleAsyncUpdate();
  31522. /** @internal */
  31523. void mouseDown (const MouseEvent& e);
  31524. /** @internal */
  31525. void mouseDrag (const MouseEvent& e);
  31526. /** @internal */
  31527. void mouseUp (const MouseEvent& e);
  31528. /** @internal */
  31529. void paint (Graphics& g);
  31530. /** @internal */
  31531. void resized();
  31532. private:
  31533. Range <double> totalRange, visibleRange;
  31534. double singleStepSize, dragStartRange;
  31535. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  31536. int dragStartMousePos, lastMousePos;
  31537. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  31538. bool vertical, isDraggingThumb, autohides;
  31539. class ScrollbarButton;
  31540. friend class ScopedPointer<ScrollbarButton>;
  31541. ScopedPointer<ScrollbarButton> upButton, downButton;
  31542. ListenerList <Listener> listeners;
  31543. void updateThumbPosition();
  31544. void timerCallback();
  31545. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  31546. };
  31547. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  31548. typedef ScrollBar::Listener ScrollBarListener;
  31549. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  31550. /*** End of inlined file: juce_ScrollBar.h ***/
  31551. /**
  31552. A Viewport is used to contain a larger child component, and allows the child
  31553. to be automatically scrolled around.
  31554. To use a Viewport, just create one and set the component that goes inside it
  31555. using the setViewedComponent() method. When the child component changes size,
  31556. the Viewport will adjust its scrollbars accordingly.
  31557. A subclass of the viewport can be created which will receive calls to its
  31558. visibleAreaChanged() method when the subcomponent changes position or size.
  31559. */
  31560. class JUCE_API Viewport : public Component,
  31561. private ComponentListener,
  31562. private ScrollBar::Listener
  31563. {
  31564. public:
  31565. /** Creates a Viewport.
  31566. The viewport is initially empty - use the setViewedComponent() method to
  31567. add a child component for it to manage.
  31568. */
  31569. explicit Viewport (const String& componentName = String::empty);
  31570. /** Destructor. */
  31571. ~Viewport();
  31572. /** Sets the component that this viewport will contain and scroll around.
  31573. This will add the given component to this Viewport and position it at (0, 0).
  31574. (Don't add or remove any child components directly using the normal
  31575. Component::addChildComponent() methods).
  31576. @param newViewedComponent the component to add to this viewport, or null to remove
  31577. the current component.
  31578. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  31579. automatically when the viewport is deleted or when a different
  31580. component is added. If false, the caller must manage the lifetime
  31581. of the component
  31582. @see getViewedComponent
  31583. */
  31584. void setViewedComponent (Component* newViewedComponent,
  31585. bool deleteComponentWhenNoLongerNeeded = true);
  31586. /** Returns the component that's currently being used inside the Viewport.
  31587. @see setViewedComponent
  31588. */
  31589. Component* getViewedComponent() const noexcept { return contentComp; }
  31590. /** Changes the position of the viewed component.
  31591. The inner component will be moved so that the pixel at the top left of
  31592. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  31593. within the inner component.
  31594. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31595. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31596. */
  31597. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  31598. /** Changes the position of the viewed component.
  31599. The inner component will be moved so that the pixel at the top left of
  31600. the viewport will be the pixel at the specified coordinates within the
  31601. inner component.
  31602. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31603. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31604. */
  31605. void setViewPosition (const Point<int>& newPosition);
  31606. /** Changes the view position as a proportion of the distance it can move.
  31607. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  31608. visible area in the top-left, and (1, 1) would put it as far down and
  31609. to the right as it's possible to go whilst keeping the child component
  31610. on-screen.
  31611. */
  31612. void setViewPositionProportionately (double proportionX, double proportionY);
  31613. /** If the specified position is at the edges of the viewport, this method scrolls
  31614. the viewport to bring that position nearer to the centre.
  31615. Call this if you're dragging an object inside a viewport and want to make it scroll
  31616. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  31617. useful when auto-scrolling.
  31618. @param mouseX the x position, relative to the Viewport's top-left
  31619. @param mouseY the y position, relative to the Viewport's top-left
  31620. @param distanceFromEdge specifies how close to an edge the position needs to be
  31621. before the viewport should scroll in that direction
  31622. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  31623. to scroll by.
  31624. @returns true if the viewport was scrolled
  31625. */
  31626. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  31627. /** Returns the position within the child component of the top-left of its visible area.
  31628. */
  31629. const Point<int> getViewPosition() const noexcept { return lastVisibleArea.getPosition(); }
  31630. /** Returns the position within the child component of the top-left of its visible area.
  31631. @see getViewWidth, setViewPosition
  31632. */
  31633. int getViewPositionX() const noexcept { return lastVisibleArea.getX(); }
  31634. /** Returns the position within the child component of the top-left of its visible area.
  31635. @see getViewHeight, setViewPosition
  31636. */
  31637. int getViewPositionY() const noexcept { return lastVisibleArea.getY(); }
  31638. /** Returns the width of the visible area of the child component.
  31639. This may be less than the width of this Viewport if there's a vertical scrollbar
  31640. or if the child component is itself smaller.
  31641. */
  31642. int getViewWidth() const noexcept { return lastVisibleArea.getWidth(); }
  31643. /** Returns the height of the visible area of the child component.
  31644. This may be less than the height of this Viewport if there's a horizontal scrollbar
  31645. or if the child component is itself smaller.
  31646. */
  31647. int getViewHeight() const noexcept { return lastVisibleArea.getHeight(); }
  31648. /** Returns the width available within this component for the contents.
  31649. This will be the width of the viewport component minus the width of a
  31650. vertical scrollbar (if visible).
  31651. */
  31652. int getMaximumVisibleWidth() const;
  31653. /** Returns the height available within this component for the contents.
  31654. This will be the height of the viewport component minus the space taken up
  31655. by a horizontal scrollbar (if visible).
  31656. */
  31657. int getMaximumVisibleHeight() const;
  31658. /** Callback method that is called when the visible area changes.
  31659. This will be called when the visible area is moved either be scrolling or
  31660. by calls to setViewPosition(), etc.
  31661. */
  31662. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  31663. /** Turns scrollbars on or off.
  31664. If set to false, the scrollbars won't ever appear. When true (the default)
  31665. they will appear only when needed.
  31666. */
  31667. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  31668. bool showHorizontalScrollbarIfNeeded);
  31669. /** True if the vertical scrollbar is enabled.
  31670. @see setScrollBarsShown
  31671. */
  31672. bool isVerticalScrollBarShown() const noexcept { return showVScrollbar; }
  31673. /** True if the horizontal scrollbar is enabled.
  31674. @see setScrollBarsShown
  31675. */
  31676. bool isHorizontalScrollBarShown() const noexcept { return showHScrollbar; }
  31677. /** Changes the width of the scrollbars.
  31678. If this isn't specified, the default width from the LookAndFeel class will be used.
  31679. @see LookAndFeel::getDefaultScrollbarWidth
  31680. */
  31681. void setScrollBarThickness (int thickness);
  31682. /** Returns the thickness of the scrollbars.
  31683. @see setScrollBarThickness
  31684. */
  31685. int getScrollBarThickness() const;
  31686. /** Changes the distance that a single-step click on a scrollbar button
  31687. will move the viewport.
  31688. */
  31689. void setSingleStepSizes (int stepX, int stepY);
  31690. /** Shows or hides the buttons on any scrollbars that are used.
  31691. @see ScrollBar::setButtonVisibility
  31692. */
  31693. void setScrollBarButtonVisibility (bool buttonsVisible);
  31694. /** Returns a pointer to the scrollbar component being used.
  31695. Handy if you need to customise the bar somehow.
  31696. */
  31697. ScrollBar* getVerticalScrollBar() noexcept { return &verticalScrollBar; }
  31698. /** Returns a pointer to the scrollbar component being used.
  31699. Handy if you need to customise the bar somehow.
  31700. */
  31701. ScrollBar* getHorizontalScrollBar() noexcept { return &horizontalScrollBar; }
  31702. /** @internal */
  31703. void resized();
  31704. /** @internal */
  31705. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  31706. /** @internal */
  31707. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31708. /** @internal */
  31709. bool keyPressed (const KeyPress& key);
  31710. /** @internal */
  31711. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  31712. /** @internal */
  31713. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31714. private:
  31715. WeakReference<Component> contentComp;
  31716. Rectangle<int> lastVisibleArea;
  31717. int scrollBarThickness;
  31718. int singleStepX, singleStepY;
  31719. bool showHScrollbar, showVScrollbar, deleteContent;
  31720. Component contentHolder;
  31721. ScrollBar verticalScrollBar;
  31722. ScrollBar horizontalScrollBar;
  31723. void updateVisibleArea();
  31724. void deleteContentComp();
  31725. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  31726. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  31727. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  31728. #endif
  31729. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  31730. };
  31731. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  31732. /*** End of inlined file: juce_Viewport.h ***/
  31733. /*** Start of inlined file: juce_PopupMenu.h ***/
  31734. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  31735. #define __JUCE_POPUPMENU_JUCEHEADER__
  31736. /** Creates and displays a popup-menu.
  31737. To show a popup-menu, you create one of these, add some items to it, then
  31738. call its show() method, which returns the id of the item the user selects.
  31739. E.g. @code
  31740. void MyWidget::mouseDown (const MouseEvent& e)
  31741. {
  31742. PopupMenu m;
  31743. m.addItem (1, "item 1");
  31744. m.addItem (2, "item 2");
  31745. const int result = m.show();
  31746. if (result == 0)
  31747. {
  31748. // user dismissed the menu without picking anything
  31749. }
  31750. else if (result == 1)
  31751. {
  31752. // user picked item 1
  31753. }
  31754. else if (result == 2)
  31755. {
  31756. // user picked item 2
  31757. }
  31758. }
  31759. @endcode
  31760. Submenus are easy too: @code
  31761. void MyWidget::mouseDown (const MouseEvent& e)
  31762. {
  31763. PopupMenu subMenu;
  31764. subMenu.addItem (1, "item 1");
  31765. subMenu.addItem (2, "item 2");
  31766. PopupMenu mainMenu;
  31767. mainMenu.addItem (3, "item 3");
  31768. mainMenu.addSubMenu ("other choices", subMenu);
  31769. const int result = m.show();
  31770. ...etc
  31771. }
  31772. @endcode
  31773. */
  31774. class JUCE_API PopupMenu
  31775. {
  31776. public:
  31777. /** Creates an empty popup menu. */
  31778. PopupMenu();
  31779. /** Creates a copy of another menu. */
  31780. PopupMenu (const PopupMenu& other);
  31781. /** Destructor. */
  31782. ~PopupMenu();
  31783. /** Copies this menu from another one. */
  31784. PopupMenu& operator= (const PopupMenu& other);
  31785. /** Resets the menu, removing all its items. */
  31786. void clear();
  31787. /** Appends a new text item for this menu to show.
  31788. @param itemResultId the number that will be returned from the show() method
  31789. if the user picks this item. The value should never be
  31790. zero, because that's used to indicate that the user didn't
  31791. select anything.
  31792. @param itemText the text to show.
  31793. @param isActive if false, the item will be shown 'greyed-out' and can't be
  31794. picked
  31795. @param isTicked if true, the item will be shown with a tick next to it
  31796. @param iconToUse if this is non-zero, it should be an image that will be
  31797. displayed to the left of the item. This method will take its
  31798. own copy of the image passed-in, so there's no need to keep
  31799. it hanging around.
  31800. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  31801. */
  31802. void addItem (int itemResultId,
  31803. const String& itemText,
  31804. bool isActive = true,
  31805. bool isTicked = false,
  31806. const Image& iconToUse = Image::null);
  31807. /** Adds an item that represents one of the commands in a command manager object.
  31808. @param commandManager the manager to use to trigger the command and get information
  31809. about it
  31810. @param commandID the ID of the command
  31811. @param displayName if this is non-empty, then this string will be used instead of
  31812. the command's registered name
  31813. */
  31814. void addCommandItem (ApplicationCommandManager* commandManager,
  31815. int commandID,
  31816. const String& displayName = String::empty);
  31817. /** Appends a text item with a special colour.
  31818. This is the same as addItem(), but specifies a colour to use for the
  31819. text, which will override the default colours that are used by the
  31820. current look-and-feel. See addItem() for a description of the parameters.
  31821. */
  31822. void addColouredItem (int itemResultId,
  31823. const String& itemText,
  31824. const Colour& itemTextColour,
  31825. bool isActive = true,
  31826. bool isTicked = false,
  31827. const Image& iconToUse = Image::null);
  31828. /** Appends a custom menu item that can't be used to trigger a result.
  31829. This will add a user-defined component to use as a menu item. Unlike the
  31830. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  31831. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  31832. delete the component when it's finished, so it's the caller's responsibility
  31833. to manage the component that is passed-in.
  31834. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  31835. detection of a mouse-click on your component, and use that to trigger the
  31836. menu ID specified in itemResultId. If this is false, the menu item can't
  31837. be triggered, so itemResultId is not used.
  31838. @see CustomComponent
  31839. */
  31840. void addCustomItem (int itemResultId,
  31841. Component* customComponent,
  31842. int idealWidth, int idealHeight,
  31843. bool triggerMenuItemAutomaticallyWhenClicked);
  31844. /** Appends a sub-menu.
  31845. If the menu that's passed in is empty, it will appear as an inactive item.
  31846. */
  31847. void addSubMenu (const String& subMenuName,
  31848. const PopupMenu& subMenu,
  31849. bool isActive = true,
  31850. const Image& iconToUse = Image::null,
  31851. bool isTicked = false);
  31852. /** Appends a separator to the menu, to help break it up into sections.
  31853. The menu class is smart enough not to display separators at the top or bottom
  31854. of the menu, and it will replace mutliple adjacent separators with a single
  31855. one, so your code can be quite free and easy about adding these, and it'll
  31856. always look ok.
  31857. */
  31858. void addSeparator();
  31859. /** Adds a non-clickable text item to the menu.
  31860. This is a bold-font items which can be used as a header to separate the items
  31861. into named groups.
  31862. */
  31863. void addSectionHeader (const String& title);
  31864. /** Returns the number of items that the menu currently contains.
  31865. (This doesn't count separators).
  31866. */
  31867. int getNumItems() const noexcept;
  31868. /** Returns true if the menu contains a command item that triggers the given command. */
  31869. bool containsCommandItem (int commandID) const;
  31870. /** Returns true if the menu contains any items that can be used. */
  31871. bool containsAnyActiveItems() const noexcept;
  31872. /** Class used to create a set of options to pass to the show() method.
  31873. You can chain together a series of calls to this class's methods to create
  31874. a set of whatever options you want to specify.
  31875. E.g. @code
  31876. PopupMenu menu;
  31877. ...
  31878. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  31879. .withMaximumNumColumns (3)
  31880. .withTargetComponent (myComp));
  31881. @endcode
  31882. */
  31883. class JUCE_API Options
  31884. {
  31885. public:
  31886. Options();
  31887. const Options withTargetComponent (Component* targetComponent) const;
  31888. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  31889. const Options withMinimumWidth (int minWidth) const;
  31890. const Options withMaximumNumColumns (int maxNumColumns) const;
  31891. const Options withStandardItemHeight (int standardHeight) const;
  31892. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  31893. private:
  31894. friend class PopupMenu;
  31895. Rectangle<int> targetArea;
  31896. Component* targetComponent;
  31897. int visibleItemID, minWidth, maxColumns, standardHeight;
  31898. };
  31899. #if JUCE_MODAL_LOOPS_PERMITTED
  31900. /** Displays the menu and waits for the user to pick something.
  31901. This will display the menu modally, and return the ID of the item that the
  31902. user picks. If they click somewhere off the menu to get rid of it without
  31903. choosing anything, this will return 0.
  31904. The current location of the mouse will be used as the position to show the
  31905. menu - to explicitly set the menu's position, use showAt() instead. Depending
  31906. on where this point is on the screen, the menu will appear above, below or
  31907. to the side of the point.
  31908. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  31909. then when the menu first appears, it will make sure
  31910. that this item is visible. So if the menu has too many
  31911. items to fit on the screen, it will be scrolled to a
  31912. position where this item is visible.
  31913. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  31914. than this if some items are too long to fit.
  31915. @param maximumNumColumns if there are too many items to fit on-screen in a single
  31916. vertical column, the menu may be laid out as a series of
  31917. columns - this is the maximum number allowed. To use the
  31918. default value for this (probably about 7), you can pass
  31919. in zero.
  31920. @param standardItemHeight if this is non-zero, it will be used as the standard
  31921. height for menu items (apart from custom items)
  31922. @param callback if this is non-zero, the menu will be launched asynchronously,
  31923. returning immediately, and the callback will receive a
  31924. call when the menu is either dismissed or has an item
  31925. selected. This object will be owned and deleted by the
  31926. system, so make sure that it works safely and that any
  31927. pointers that it uses are safely within scope.
  31928. @see showAt
  31929. */
  31930. int show (int itemIdThatMustBeVisible = 0,
  31931. int minimumWidth = 0,
  31932. int maximumNumColumns = 0,
  31933. int standardItemHeight = 0,
  31934. ModalComponentManager::Callback* callback = nullptr);
  31935. /** Displays the menu at a specific location.
  31936. This is the same as show(), but uses a specific location (in global screen
  31937. co-ordinates) rather than the current mouse position.
  31938. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  31939. will be adjacent. Depending on where this is, the menu will decide which edge to
  31940. attach itself to, in order to fit itself fully on-screen. If you just want to
  31941. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  31942. with the position that you want.
  31943. @see show()
  31944. */
  31945. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  31946. int itemIdThatMustBeVisible = 0,
  31947. int minimumWidth = 0,
  31948. int maximumNumColumns = 0,
  31949. int standardItemHeight = 0,
  31950. ModalComponentManager::Callback* callback = nullptr);
  31951. /** Displays the menu as if it's attached to a component such as a button.
  31952. This is similar to showAt(), but will position it next to the given component, e.g.
  31953. so that the menu's edge is aligned with that of the component. This is intended for
  31954. things like buttons that trigger a pop-up menu.
  31955. */
  31956. int showAt (Component* componentToAttachTo,
  31957. int itemIdThatMustBeVisible = 0,
  31958. int minimumWidth = 0,
  31959. int maximumNumColumns = 0,
  31960. int standardItemHeight = 0,
  31961. ModalComponentManager::Callback* callback = nullptr);
  31962. /** Displays and runs the menu modally, with a set of options.
  31963. */
  31964. int showMenu (const Options& options);
  31965. #endif
  31966. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  31967. void showMenuAsync (const Options& options,
  31968. ModalComponentManager::Callback* callback);
  31969. /** Closes any menus that are currently open.
  31970. This might be useful if you have a situation where your window is being closed
  31971. by some means other than a user action, and you'd like to make sure that menus
  31972. aren't left hanging around.
  31973. */
  31974. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  31975. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  31976. This can be called before show() if you need a customised menu. Be careful
  31977. not to delete the LookAndFeel object before the menu has been deleted.
  31978. */
  31979. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  31980. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  31981. These constants can be used either via the LookAndFeel::setColour()
  31982. method for the look and feel that is set for this menu with setLookAndFeel()
  31983. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  31984. */
  31985. enum ColourIds
  31986. {
  31987. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  31988. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  31989. colour is specified when the item is added). */
  31990. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  31991. addSectionHeader() method). */
  31992. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  31993. highlighted menu item. */
  31994. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  31995. highlighted item. */
  31996. };
  31997. /**
  31998. Allows you to iterate through the items in a pop-up menu, and examine
  31999. their properties.
  32000. To use this, just create one and repeatedly call its next() method. When this
  32001. returns true, all the member variables of the iterator are filled-out with
  32002. information describing the menu item. When it returns false, the end of the
  32003. list has been reached.
  32004. */
  32005. class JUCE_API MenuItemIterator
  32006. {
  32007. public:
  32008. /** Creates an iterator that will scan through the items in the specified
  32009. menu.
  32010. Be careful not to add any items to a menu while it is being iterated,
  32011. or things could get out of step.
  32012. */
  32013. MenuItemIterator (const PopupMenu& menu);
  32014. /** Destructor. */
  32015. ~MenuItemIterator();
  32016. /** Returns true if there is another item, and sets up all this object's
  32017. member variables to reflect that item's properties.
  32018. */
  32019. bool next();
  32020. String itemName;
  32021. const PopupMenu* subMenu;
  32022. int itemId;
  32023. bool isSeparator;
  32024. bool isTicked;
  32025. bool isEnabled;
  32026. bool isCustomComponent;
  32027. bool isSectionHeader;
  32028. const Colour* customColour;
  32029. Image customImage;
  32030. ApplicationCommandManager* commandManager;
  32031. private:
  32032. const PopupMenu& menu;
  32033. int index;
  32034. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  32035. };
  32036. /** A user-defined copmonent that can be used as an item in a popup menu.
  32037. @see PopupMenu::addCustomItem
  32038. */
  32039. class JUCE_API CustomComponent : public Component,
  32040. public ReferenceCountedObject
  32041. {
  32042. public:
  32043. /** Creates a custom item.
  32044. If isTriggeredAutomatically is true, then the menu will automatically detect
  32045. a mouse-click on this component and use that to invoke the menu item. If it's
  32046. false, then it's up to your class to manually trigger the item when it wants to.
  32047. */
  32048. CustomComponent (bool isTriggeredAutomatically = true);
  32049. /** Destructor. */
  32050. ~CustomComponent();
  32051. /** Returns a rectangle with the size that this component would like to have.
  32052. Note that the size which this method returns isn't necessarily the one that
  32053. the menu will give it, as the items will be stretched to have a uniform width.
  32054. */
  32055. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  32056. /** Dismisses the menu, indicating that this item has been chosen.
  32057. This will cause the menu to exit from its modal state, returning
  32058. this item's id as the result.
  32059. */
  32060. void triggerMenuItem();
  32061. /** Returns true if this item should be highlighted because the mouse is over it.
  32062. You can call this method in your paint() method to find out whether
  32063. to draw a highlight.
  32064. */
  32065. bool isItemHighlighted() const noexcept { return isHighlighted; }
  32066. /** @internal */
  32067. bool isTriggeredAutomatically() const noexcept { return triggeredAutomatically; }
  32068. /** @internal */
  32069. void setHighlighted (bool shouldBeHighlighted);
  32070. private:
  32071. bool isHighlighted, triggeredAutomatically;
  32072. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  32073. };
  32074. /** Appends a custom menu item.
  32075. This will add a user-defined component to use as a menu item. The component
  32076. passed in will be deleted by this menu when it's no longer needed.
  32077. @see CustomComponent
  32078. */
  32079. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  32080. private:
  32081. class Item;
  32082. class ItemComponent;
  32083. class Window;
  32084. friend class MenuItemIterator;
  32085. friend class ItemComponent;
  32086. friend class Window;
  32087. friend class CustomComponent;
  32088. friend class MenuBarComponent;
  32089. friend class OwnedArray <Item>;
  32090. friend class OwnedArray <ItemComponent>;
  32091. friend class ScopedPointer <Window>;
  32092. OwnedArray <Item> items;
  32093. LookAndFeel* lookAndFeel;
  32094. bool separatorPending;
  32095. void addSeparatorIfPending();
  32096. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  32097. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  32098. JUCE_LEAK_DETECTOR (PopupMenu);
  32099. };
  32100. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  32101. /*** End of inlined file: juce_PopupMenu.h ***/
  32102. /*** Start of inlined file: juce_TextInputTarget.h ***/
  32103. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32104. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32105. /**
  32106. An abstract base class which can be implemented by components that function as
  32107. text editors.
  32108. This class allows different types of text editor component to provide a uniform
  32109. interface, which can be used by things like OS-specific input methods, on-screen
  32110. keyboards, etc.
  32111. */
  32112. class JUCE_API TextInputTarget
  32113. {
  32114. public:
  32115. /** */
  32116. TextInputTarget() {}
  32117. /** Destructor. */
  32118. virtual ~TextInputTarget() {}
  32119. /** Returns true if this input target is currently accepting input.
  32120. For example, a text editor might return false if it's in read-only mode.
  32121. */
  32122. virtual bool isTextInputActive() const = 0;
  32123. /** Returns the extents of the selected text region, or an empty range if
  32124. nothing is selected,
  32125. */
  32126. virtual const Range<int> getHighlightedRegion() const = 0;
  32127. /** Sets the currently-selected text region. */
  32128. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  32129. /** Sets a number of temporarily underlined sections.
  32130. This is needed by MS Windows input method UI.
  32131. */
  32132. virtual void setTemporaryUnderlining (const Array <Range<int> >& underlinedRegions) = 0;
  32133. /** Returns a specified sub-section of the text. */
  32134. virtual const String getTextInRange (const Range<int>& range) const = 0;
  32135. /** Inserts some text, overwriting the selected text region, if there is one. */
  32136. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  32137. /** Returns the position of the caret, relative to the component's origin. */
  32138. virtual const Rectangle<int> getCaretRectangle() = 0;
  32139. };
  32140. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32141. /*** End of inlined file: juce_TextInputTarget.h ***/
  32142. /*** Start of inlined file: juce_CaretComponent.h ***/
  32143. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  32144. #define __JUCE_CARETCOMPONENT_JUCEHEADER__
  32145. /**
  32146. */
  32147. class JUCE_API CaretComponent : public Component,
  32148. public Timer
  32149. {
  32150. public:
  32151. /** Creates the caret component.
  32152. The keyFocusOwner is an optional component which the caret will check, making
  32153. itself visible only when the keyFocusOwner has keyboard focus.
  32154. */
  32155. CaretComponent (Component* keyFocusOwner);
  32156. /** Destructor. */
  32157. ~CaretComponent();
  32158. /** Sets the caret's position to place it next to the given character.
  32159. The area is the rectangle containing the entire character that the caret is
  32160. positioned on, so by default a vertical-line caret may choose to just show itself
  32161. at the left of this area. You can override this method to customise its size.
  32162. This method will also force the caret to reset its timer and become visible (if
  32163. appropriate), so that as it moves, you can see where it is.
  32164. */
  32165. virtual void setCaretPosition (const Rectangle<int>& characterArea);
  32166. /** A set of colour IDs to use to change the colour of various aspects of the caret.
  32167. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32168. methods.
  32169. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32170. */
  32171. enum ColourIds
  32172. {
  32173. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  32174. };
  32175. /** @internal */
  32176. void paint (Graphics& g);
  32177. /** @internal */
  32178. void timerCallback();
  32179. private:
  32180. Component* owner;
  32181. bool shouldBeShown() const;
  32182. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  32183. };
  32184. #endif // __JUCE_CARETCOMPONENT_JUCEHEADER__
  32185. /*** End of inlined file: juce_CaretComponent.h ***/
  32186. /**
  32187. A component containing text that can be edited.
  32188. A TextEditor can either be in single- or multi-line mode, and supports mixed
  32189. fonts and colours.
  32190. @see TextEditor::Listener, Label
  32191. */
  32192. class JUCE_API TextEditor : public Component,
  32193. public TextInputTarget,
  32194. public SettableTooltipClient
  32195. {
  32196. public:
  32197. /** Creates a new, empty text editor.
  32198. @param componentName the name to pass to the component for it to use as its name
  32199. @param passwordCharacter if this is not zero, this character will be used as a replacement
  32200. for all characters that are drawn on screen - e.g. to create
  32201. a password-style textbox containing circular blobs instead of text,
  32202. you could set this value to 0x25cf, which is the unicode character
  32203. for a black splodge (not all fonts include this, though), or 0x2022,
  32204. which is a bullet (probably the best choice for linux).
  32205. */
  32206. explicit TextEditor (const String& componentName = String::empty,
  32207. juce_wchar passwordCharacter = 0);
  32208. /** Destructor. */
  32209. virtual ~TextEditor();
  32210. /** Puts the editor into either multi- or single-line mode.
  32211. By default, the editor will be in single-line mode, so use this if you need a multi-line
  32212. editor.
  32213. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  32214. on if you want a multi-line editor with line-breaks.
  32215. @see isMultiLine, setReturnKeyStartsNewLine
  32216. */
  32217. void setMultiLine (bool shouldBeMultiLine,
  32218. bool shouldWordWrap = true);
  32219. /** Returns true if the editor is in multi-line mode.
  32220. */
  32221. bool isMultiLine() const;
  32222. /** Changes the behaviour of the return key.
  32223. If set to true, the return key will insert a new-line into the text; if false
  32224. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  32225. method. By default this is set to false, and when true it will only insert
  32226. new-lines when in multi-line mode (see setMultiLine()).
  32227. */
  32228. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  32229. /** Returns the value set by setReturnKeyStartsNewLine().
  32230. See setReturnKeyStartsNewLine() for more info.
  32231. */
  32232. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  32233. /** Indicates whether the tab key should be accepted and used to input a tab character,
  32234. or whether it gets ignored.
  32235. By default the tab key is ignored, so that it can be used to switch keyboard focus
  32236. between components.
  32237. */
  32238. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  32239. /** Returns true if the tab key is being used for input.
  32240. @see setTabKeyUsedAsCharacter
  32241. */
  32242. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  32243. /** Changes the editor to read-only mode.
  32244. By default, the text editor is not read-only. If you're making it read-only, you
  32245. might also want to call setCaretVisible (false) to get rid of the caret.
  32246. The text can still be highlighted and copied when in read-only mode.
  32247. @see isReadOnly, setCaretVisible
  32248. */
  32249. void setReadOnly (bool shouldBeReadOnly);
  32250. /** Returns true if the editor is in read-only mode.
  32251. */
  32252. bool isReadOnly() const;
  32253. /** Makes the caret visible or invisible.
  32254. By default the caret is visible.
  32255. @see setCaretColour, setCaretPosition
  32256. */
  32257. void setCaretVisible (bool shouldBeVisible);
  32258. /** Returns true if the caret is enabled.
  32259. @see setCaretVisible
  32260. */
  32261. bool isCaretVisible() const { return caret != nullptr; }
  32262. /** Enables/disables a vertical scrollbar.
  32263. (This only applies when in multi-line mode). When the text gets too long to fit
  32264. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  32265. this is enabled, the scrollbar will be hidden unless it's needed.
  32266. By default the scrollbar is enabled.
  32267. */
  32268. void setScrollbarsShown (bool shouldBeEnabled);
  32269. /** Returns true if scrollbars are enabled.
  32270. @see setScrollbarsShown
  32271. */
  32272. bool areScrollbarsShown() const { return scrollbarVisible; }
  32273. /** Changes the password character used to disguise the text.
  32274. @param passwordCharacter if this is not zero, this character will be used as a replacement
  32275. for all characters that are drawn on screen - e.g. to create
  32276. a password-style textbox containing circular blobs instead of text,
  32277. you could set this value to 0x25cf, which is the unicode character
  32278. for a black splodge (not all fonts include this, though), or 0x2022,
  32279. which is a bullet (probably the best choice for linux).
  32280. */
  32281. void setPasswordCharacter (juce_wchar passwordCharacter);
  32282. /** Returns the current password character.
  32283. @see setPasswordCharacter
  32284. */
  32285. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  32286. /** Allows a right-click menu to appear for the editor.
  32287. (This defaults to being enabled).
  32288. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  32289. of options such as cut/copy/paste, undo/redo, etc.
  32290. */
  32291. void setPopupMenuEnabled (bool menuEnabled);
  32292. /** Returns true if the right-click menu is enabled.
  32293. @see setPopupMenuEnabled
  32294. */
  32295. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  32296. /** Returns true if a popup-menu is currently being displayed.
  32297. */
  32298. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  32299. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  32300. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32301. methods.
  32302. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32303. */
  32304. enum ColourIds
  32305. {
  32306. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  32307. transparent if necessary. */
  32308. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  32309. that because the editor can contain multiple colours, calling this
  32310. method won't change the colour of existing text - to do that, call
  32311. applyFontToAllText() after calling this method.*/
  32312. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  32313. the text - this can be transparent if you don't want to show any
  32314. highlighting.*/
  32315. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  32316. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  32317. the edge of the component. */
  32318. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  32319. the edge of the component when it has focus. */
  32320. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  32321. around the edge of the editor. */
  32322. };
  32323. /** Sets the font to use for newly added text.
  32324. This will change the font that will be used next time any text is added or entered
  32325. into the editor. It won't change the font of any existing text - to do that, use
  32326. applyFontToAllText() instead.
  32327. @see applyFontToAllText
  32328. */
  32329. void setFont (const Font& newFont);
  32330. /** Applies a font to all the text in the editor.
  32331. This will also set the current font to use for any new text that's added.
  32332. @see setFont
  32333. */
  32334. void applyFontToAllText (const Font& newFont);
  32335. /** Returns the font that's currently being used for new text.
  32336. @see setFont
  32337. */
  32338. const Font getFont() const;
  32339. /** If set to true, focusing on the editor will highlight all its text.
  32340. (Set to false by default).
  32341. This is useful for boxes where you expect the user to re-enter all the
  32342. text when they focus on the component, rather than editing what's already there.
  32343. */
  32344. void setSelectAllWhenFocused (bool b);
  32345. /** Sets limits on the characters that can be entered.
  32346. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  32347. limit is set
  32348. @param allowedCharacters if this is non-empty, then only characters that occur in
  32349. this string are allowed to be entered into the editor.
  32350. */
  32351. void setInputRestrictions (int maxTextLength,
  32352. const String& allowedCharacters = String::empty);
  32353. /** When the text editor is empty, it can be set to display a message.
  32354. This is handy for things like telling the user what to type in the box - the
  32355. string is only displayed, it's not taken to actually be the contents of
  32356. the editor.
  32357. */
  32358. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  32359. /** Changes the size of the scrollbars that are used.
  32360. Handy if you need smaller scrollbars for a small text box.
  32361. */
  32362. void setScrollBarThickness (int newThicknessPixels);
  32363. /** Shows or hides the buttons on any scrollbars that are used.
  32364. @see ScrollBar::setButtonVisibility
  32365. */
  32366. void setScrollBarButtonVisibility (bool buttonsVisible);
  32367. /**
  32368. Receives callbacks from a TextEditor component when it changes.
  32369. @see TextEditor::addListener
  32370. */
  32371. class JUCE_API Listener
  32372. {
  32373. public:
  32374. /** Destructor. */
  32375. virtual ~Listener() {}
  32376. /** Called when the user changes the text in some way. */
  32377. virtual void textEditorTextChanged (TextEditor& editor);
  32378. /** Called when the user presses the return key. */
  32379. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  32380. /** Called when the user presses the escape key. */
  32381. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  32382. /** Called when the text editor loses focus. */
  32383. virtual void textEditorFocusLost (TextEditor& editor);
  32384. };
  32385. /** Registers a listener to be told when things happen to the text.
  32386. @see removeListener
  32387. */
  32388. void addListener (Listener* newListener);
  32389. /** Deregisters a listener.
  32390. @see addListener
  32391. */
  32392. void removeListener (Listener* listenerToRemove);
  32393. /** Returns the entire contents of the editor. */
  32394. const String getText() const;
  32395. /** Returns a section of the contents of the editor. */
  32396. const String getTextInRange (const Range<int>& textRange) const;
  32397. /** Returns true if there are no characters in the editor.
  32398. This is more efficient than calling getText().isEmpty().
  32399. */
  32400. bool isEmpty() const;
  32401. /** Sets the entire content of the editor.
  32402. This will clear the editor and insert the given text (using the current text colour
  32403. and font). You can set the current text colour using
  32404. @code setColour (TextEditor::textColourId, ...);
  32405. @endcode
  32406. @param newText the text to add
  32407. @param sendTextChangeMessage if true, this will cause a change message to
  32408. be sent to all the listeners.
  32409. @see insertText
  32410. */
  32411. void setText (const String& newText,
  32412. bool sendTextChangeMessage = true);
  32413. /** Returns a Value object that can be used to get or set the text.
  32414. Bear in mind that this operate quite slowly if your text box contains large
  32415. amounts of text, as it needs to dynamically build the string that's involved. It's
  32416. best used for small text boxes.
  32417. */
  32418. Value& getTextValue();
  32419. /** Inserts some text at the current caret position.
  32420. If a section of the text is highlighted, it will be replaced by
  32421. this string, otherwise it will be inserted.
  32422. To delete a section of text, you can use setHighlightedRegion() to
  32423. highlight it, and call insertTextAtCursor (String::empty).
  32424. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  32425. */
  32426. void insertTextAtCaret (const String& textToInsert);
  32427. /** Deletes all the text from the editor. */
  32428. void clear();
  32429. /** Deletes the currently selected region.
  32430. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  32431. @see copy, paste, SystemClipboard
  32432. */
  32433. void cut();
  32434. /** Copies the currently selected region to the clipboard.
  32435. @see cut, paste, SystemClipboard
  32436. */
  32437. void copy();
  32438. /** Pastes the contents of the clipboard into the editor at the caret position.
  32439. @see cut, copy, SystemClipboard
  32440. */
  32441. void paste();
  32442. /** Moves the caret to be in front of a given character.
  32443. @see getCaretPosition
  32444. */
  32445. void setCaretPosition (int newIndex);
  32446. /** Returns the current index of the caret.
  32447. @see setCaretPosition
  32448. */
  32449. int getCaretPosition() const;
  32450. /** Attempts to scroll the text editor so that the caret ends up at
  32451. a specified position.
  32452. This won't affect the caret's position within the text, it tries to scroll
  32453. the entire editor vertically and horizontally so that the caret is sitting
  32454. at the given position (relative to the top-left of this component).
  32455. Depending on the amount of text available, it might not be possible to
  32456. scroll far enough for the caret to reach this exact position, but it
  32457. will go as far as it can in that direction.
  32458. */
  32459. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  32460. /** Get the graphical position of the caret.
  32461. The rectangle returned is relative to the component's top-left corner.
  32462. @see scrollEditorToPositionCaret
  32463. */
  32464. const Rectangle<int> getCaretRectangle();
  32465. /** Selects a section of the text. */
  32466. void setHighlightedRegion (const Range<int>& newSelection);
  32467. /** Returns the range of characters that are selected.
  32468. If nothing is selected, this will return an empty range.
  32469. @see setHighlightedRegion
  32470. */
  32471. const Range<int> getHighlightedRegion() const { return selection; }
  32472. /** Returns the section of text that is currently selected. */
  32473. const String getHighlightedText() const;
  32474. /** Finds the index of the character at a given position.
  32475. The co-ordinates are relative to the component's top-left.
  32476. */
  32477. int getTextIndexAt (int x, int y);
  32478. /** Counts the number of characters in the text.
  32479. This is quicker than getting the text as a string if you just need to know
  32480. the length.
  32481. */
  32482. int getTotalNumChars() const;
  32483. /** Returns the total width of the text, as it is currently laid-out.
  32484. This may be larger than the size of the TextEditor, and can change when
  32485. the TextEditor is resized or the text changes.
  32486. */
  32487. int getTextWidth() const;
  32488. /** Returns the maximum height of the text, as it is currently laid-out.
  32489. This may be larger than the size of the TextEditor, and can change when
  32490. the TextEditor is resized or the text changes.
  32491. */
  32492. int getTextHeight() const;
  32493. /** Changes the size of the gap at the top and left-edge of the editor.
  32494. By default there's a gap of 4 pixels.
  32495. */
  32496. void setIndents (int newLeftIndent, int newTopIndent);
  32497. /** Changes the size of border left around the edge of the component.
  32498. @see getBorder
  32499. */
  32500. void setBorder (const BorderSize<int>& border);
  32501. /** Returns the size of border around the edge of the component.
  32502. @see setBorder
  32503. */
  32504. const BorderSize<int> getBorder() const;
  32505. /** Used to disable the auto-scrolling which keeps the caret visible.
  32506. If true (the default), the editor will scroll when the caret moves offscreen. If
  32507. set to false, it won't.
  32508. */
  32509. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  32510. /** @internal */
  32511. void paint (Graphics& g);
  32512. /** @internal */
  32513. void paintOverChildren (Graphics& g);
  32514. /** @internal */
  32515. void mouseDown (const MouseEvent& e);
  32516. /** @internal */
  32517. void mouseUp (const MouseEvent& e);
  32518. /** @internal */
  32519. void mouseDrag (const MouseEvent& e);
  32520. /** @internal */
  32521. void mouseDoubleClick (const MouseEvent& e);
  32522. /** @internal */
  32523. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  32524. /** @internal */
  32525. bool keyPressed (const KeyPress& key);
  32526. /** @internal */
  32527. bool keyStateChanged (bool isKeyDown);
  32528. /** @internal */
  32529. void focusGained (FocusChangeType cause);
  32530. /** @internal */
  32531. void focusLost (FocusChangeType cause);
  32532. /** @internal */
  32533. void resized();
  32534. /** @internal */
  32535. void enablementChanged();
  32536. /** @internal */
  32537. void colourChanged();
  32538. /** @internal */
  32539. void lookAndFeelChanged();
  32540. /** @internal */
  32541. bool isTextInputActive() const;
  32542. /** @internal */
  32543. void setTemporaryUnderlining (const Array <Range<int> >&);
  32544. /** This adds the items to the popup menu.
  32545. By default it adds the cut/copy/paste items, but you can override this if
  32546. you need to replace these with your own items.
  32547. If you want to add your own items to the existing ones, you can override this,
  32548. call the base class's addPopupMenuItems() method, then append your own items.
  32549. When the menu has been shown, performPopupMenuAction() will be called to
  32550. perform the item that the user has chosen.
  32551. The default menu items will be added using item IDs in the range
  32552. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  32553. menu IDs.
  32554. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  32555. a pointer to the info about it, or may be null if the menu is being triggered
  32556. by some other means.
  32557. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  32558. */
  32559. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  32560. const MouseEvent* mouseClickEvent);
  32561. /** This is called to perform one of the items that was shown on the popup menu.
  32562. If you've overridden addPopupMenuItems(), you should also override this
  32563. to perform the actions that you've added.
  32564. If you've overridden addPopupMenuItems() but have still left the default items
  32565. on the menu, remember to call the superclass's performPopupMenuAction()
  32566. so that it can perform the default actions if that's what the user clicked on.
  32567. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  32568. */
  32569. virtual void performPopupMenuAction (int menuItemID);
  32570. protected:
  32571. /** Scrolls the minimum distance needed to get the caret into view. */
  32572. void scrollToMakeSureCursorIsVisible();
  32573. /** @internal */
  32574. void moveCaret (int newCaretPos);
  32575. /** @internal */
  32576. void moveCaretTo (int newPosition, bool isSelecting);
  32577. /** Used internally to dispatch a text-change message. */
  32578. void textChanged();
  32579. /** Begins a new transaction in the UndoManager. */
  32580. void newTransaction();
  32581. /** Used internally to trigger an undo or redo. */
  32582. void doUndoRedo (bool isRedo);
  32583. /** Can be overridden to intercept return key presses directly */
  32584. virtual void returnPressed();
  32585. /** Can be overridden to intercept escape key presses directly */
  32586. virtual void escapePressed();
  32587. /** @internal */
  32588. void handleCommandMessage (int commandId);
  32589. private:
  32590. class Iterator;
  32591. class UniformTextSection;
  32592. class TextHolderComponent;
  32593. class InsertAction;
  32594. class RemoveAction;
  32595. friend class InsertAction;
  32596. friend class RemoveAction;
  32597. ScopedPointer <Viewport> viewport;
  32598. TextHolderComponent* textHolder;
  32599. BorderSize<int> borderSize;
  32600. bool readOnly : 1;
  32601. bool multiline : 1;
  32602. bool wordWrap : 1;
  32603. bool returnKeyStartsNewLine : 1;
  32604. bool popupMenuEnabled : 1;
  32605. bool selectAllTextWhenFocused : 1;
  32606. bool scrollbarVisible : 1;
  32607. bool wasFocused : 1;
  32608. bool keepCaretOnScreen : 1;
  32609. bool tabKeyUsed : 1;
  32610. bool menuActive : 1;
  32611. bool valueTextNeedsUpdating : 1;
  32612. UndoManager undoManager;
  32613. ScopedPointer<CaretComponent> caret;
  32614. int maxTextLength;
  32615. Range<int> selection;
  32616. int leftIndent, topIndent;
  32617. unsigned int lastTransactionTime;
  32618. Font currentFont;
  32619. mutable int totalNumChars;
  32620. int caretPosition;
  32621. Array <UniformTextSection*> sections;
  32622. String textToShowWhenEmpty;
  32623. Colour colourForTextWhenEmpty;
  32624. juce_wchar passwordCharacter;
  32625. Value textValue;
  32626. enum
  32627. {
  32628. notDragging,
  32629. draggingSelectionStart,
  32630. draggingSelectionEnd
  32631. } dragType;
  32632. String allowedCharacters;
  32633. ListenerList <Listener> listeners;
  32634. Array <Range<int> > underlinedSections;
  32635. void coalesceSimilarSections();
  32636. void splitSection (int sectionIndex, int charToSplitAt);
  32637. void clearInternal (UndoManager* um);
  32638. void insert (const String& text, int insertIndex, const Font& font,
  32639. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  32640. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  32641. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  32642. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  32643. void updateCaretPosition();
  32644. void textWasChangedByValue();
  32645. int indexAtPosition (float x, float y);
  32646. int findWordBreakAfter (int position) const;
  32647. int findWordBreakBefore (int position) const;
  32648. friend class TextHolderComponent;
  32649. friend class TextEditorViewport;
  32650. void drawContent (Graphics& g);
  32651. void updateTextHolderSize();
  32652. float getWordWrapWidth() const;
  32653. void timerCallbackInt();
  32654. void repaintText (const Range<int>& range);
  32655. UndoManager* getUndoManager() noexcept;
  32656. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  32657. };
  32658. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  32659. typedef TextEditor::Listener TextEditorListener;
  32660. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  32661. /*** End of inlined file: juce_TextEditor.h ***/
  32662. #if JUCE_VC6
  32663. #define Listener ButtonListener
  32664. #endif
  32665. /**
  32666. A component that displays a text string, and can optionally become a text
  32667. editor when clicked.
  32668. */
  32669. class JUCE_API Label : public Component,
  32670. public SettableTooltipClient,
  32671. protected TextEditorListener,
  32672. private ComponentListener,
  32673. private ValueListener
  32674. {
  32675. public:
  32676. /** Creates a Label.
  32677. @param componentName the name to give the component
  32678. @param labelText the text to show in the label
  32679. */
  32680. Label (const String& componentName = String::empty,
  32681. const String& labelText = String::empty);
  32682. /** Destructor. */
  32683. ~Label();
  32684. /** Changes the label text.
  32685. If broadcastChangeMessage is true and the new text is different to the current
  32686. text, then the class will broadcast a change message to any Label::Listener objects
  32687. that are registered.
  32688. */
  32689. void setText (const String& newText, bool broadcastChangeMessage);
  32690. /** Returns the label's current text.
  32691. @param returnActiveEditorContents if this is true and the label is currently
  32692. being edited, then this method will return the
  32693. text as it's being shown in the editor. If false,
  32694. then the value returned here won't be updated until
  32695. the user has finished typing and pressed the return
  32696. key.
  32697. */
  32698. const String getText (bool returnActiveEditorContents = false) const;
  32699. /** Returns the text content as a Value object.
  32700. You can call Value::referTo() on this object to make the label read and control
  32701. a Value object that you supply.
  32702. */
  32703. Value& getTextValue() { return textValue; }
  32704. /** Changes the font to use to draw the text.
  32705. @see getFont
  32706. */
  32707. void setFont (const Font& newFont);
  32708. /** Returns the font currently being used.
  32709. @see setFont
  32710. */
  32711. const Font& getFont() const noexcept;
  32712. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32713. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32714. methods.
  32715. Note that you can also use the constants from TextEditor::ColourIds to change the
  32716. colour of the text editor that is opened when a label is editable.
  32717. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32718. */
  32719. enum ColourIds
  32720. {
  32721. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  32722. textColourId = 0x1000281, /**< The colour for the text. */
  32723. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  32724. Leave this transparent to not have an outline. */
  32725. };
  32726. /** Sets the style of justification to be used for positioning the text.
  32727. (The default is Justification::centredLeft)
  32728. */
  32729. void setJustificationType (const Justification& justification);
  32730. /** Returns the type of justification, as set in setJustificationType(). */
  32731. const Justification getJustificationType() const noexcept { return justification; }
  32732. /** Changes the gap that is left between the edge of the component and the text.
  32733. By default there's a small gap left at the sides of the component to allow for
  32734. the drawing of the border, but you can change this if necessary.
  32735. */
  32736. void setBorderSize (int horizontalBorder, int verticalBorder);
  32737. /** Returns the size of the horizontal gap being left around the text.
  32738. */
  32739. int getHorizontalBorderSize() const noexcept { return horizontalBorderSize; }
  32740. /** Returns the size of the vertical gap being left around the text.
  32741. */
  32742. int getVerticalBorderSize() const noexcept { return verticalBorderSize; }
  32743. /** Makes this label "stick to" another component.
  32744. This will cause the label to follow another component around, staying
  32745. either to its left or above it.
  32746. @param owner the component to follow
  32747. @param onLeft if true, the label will stay on the left of its component; if
  32748. false, it will stay above it.
  32749. */
  32750. void attachToComponent (Component* owner, bool onLeft);
  32751. /** If this label has been attached to another component using attachToComponent, this
  32752. returns the other component.
  32753. Returns 0 if the label is not attached.
  32754. */
  32755. Component* getAttachedComponent() const;
  32756. /** If the label is attached to the left of another component, this returns true.
  32757. Returns false if the label is above the other component. This is only relevent if
  32758. attachToComponent() has been called.
  32759. */
  32760. bool isAttachedOnLeft() const noexcept { return leftOfOwnerComp; }
  32761. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  32762. using ellipsis.
  32763. @see Graphics::drawFittedText
  32764. */
  32765. void setMinimumHorizontalScale (float newScale);
  32766. float getMinimumHorizontalScale() const noexcept { return minimumHorizontalScale; }
  32767. /**
  32768. A class for receiving events from a Label.
  32769. You can register a Label::Listener with a Label using the Label::addListener()
  32770. method, and it will be called when the text of the label changes, either because
  32771. of a call to Label::setText() or by the user editing the text (if the label is
  32772. editable).
  32773. @see Label::addListener, Label::removeListener
  32774. */
  32775. class JUCE_API Listener
  32776. {
  32777. public:
  32778. /** Destructor. */
  32779. virtual ~Listener() {}
  32780. /** Called when a Label's text has changed.
  32781. */
  32782. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  32783. };
  32784. /** Registers a listener that will be called when the label's text changes. */
  32785. void addListener (Listener* listener);
  32786. /** Deregisters a previously-registered listener. */
  32787. void removeListener (Listener* listener);
  32788. /** Makes the label turn into a TextEditor when clicked.
  32789. By default this is turned off.
  32790. If turned on, then single- or double-clicking will turn the label into
  32791. an editor. If the user then changes the text, then the ChangeBroadcaster
  32792. base class will be used to send change messages to any listeners that
  32793. have registered.
  32794. If the user changes the text, the textWasEdited() method will be called
  32795. afterwards, and subclasses can override this if they need to do anything
  32796. special.
  32797. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  32798. @param editOnDoubleClick if true, a double-click is needed to start editing
  32799. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  32800. edited will discard any changes; if false, then this will
  32801. commit the changes.
  32802. @see showEditor, setEditorColours, TextEditor
  32803. */
  32804. void setEditable (bool editOnSingleClick,
  32805. bool editOnDoubleClick = false,
  32806. bool lossOfFocusDiscardsChanges = false);
  32807. /** Returns true if this option was set using setEditable(). */
  32808. bool isEditableOnSingleClick() const noexcept { return editSingleClick; }
  32809. /** Returns true if this option was set using setEditable(). */
  32810. bool isEditableOnDoubleClick() const noexcept { return editDoubleClick; }
  32811. /** Returns true if this option has been set in a call to setEditable(). */
  32812. bool doesLossOfFocusDiscardChanges() const noexcept { return lossOfFocusDiscardsChanges; }
  32813. /** Returns true if the user can edit this label's text. */
  32814. bool isEditable() const noexcept { return editSingleClick || editDoubleClick; }
  32815. /** Makes the editor appear as if the label had been clicked by the user.
  32816. @see textWasEdited, setEditable
  32817. */
  32818. void showEditor();
  32819. /** Hides the editor if it was being shown.
  32820. @param discardCurrentEditorContents if true, the label's text will be
  32821. reset to whatever it was before the editor
  32822. was shown; if false, the current contents of the
  32823. editor will be used to set the label's text
  32824. before it is hidden.
  32825. */
  32826. void hideEditor (bool discardCurrentEditorContents);
  32827. /** Returns true if the editor is currently focused and active. */
  32828. bool isBeingEdited() const noexcept;
  32829. protected:
  32830. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  32831. Subclasses can override this if they need to customise this component in some way.
  32832. */
  32833. virtual TextEditor* createEditorComponent();
  32834. /** Called after the user changes the text. */
  32835. virtual void textWasEdited();
  32836. /** Called when the text has been altered. */
  32837. virtual void textWasChanged();
  32838. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  32839. virtual void editorShown (TextEditor* editorComponent);
  32840. /** Called when the text editor is going to be deleted, after editing has finished. */
  32841. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  32842. /** @internal */
  32843. void paint (Graphics& g);
  32844. /** @internal */
  32845. void resized();
  32846. /** @internal */
  32847. void mouseUp (const MouseEvent& e);
  32848. /** @internal */
  32849. void mouseDoubleClick (const MouseEvent& e);
  32850. /** @internal */
  32851. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  32852. /** @internal */
  32853. void componentParentHierarchyChanged (Component& component);
  32854. /** @internal */
  32855. void componentVisibilityChanged (Component& component);
  32856. /** @internal */
  32857. void inputAttemptWhenModal();
  32858. /** @internal */
  32859. void focusGained (FocusChangeType);
  32860. /** @internal */
  32861. void enablementChanged();
  32862. /** @internal */
  32863. KeyboardFocusTraverser* createFocusTraverser();
  32864. /** @internal */
  32865. void textEditorTextChanged (TextEditor& editor);
  32866. /** @internal */
  32867. void textEditorReturnKeyPressed (TextEditor& editor);
  32868. /** @internal */
  32869. void textEditorEscapeKeyPressed (TextEditor& editor);
  32870. /** @internal */
  32871. void textEditorFocusLost (TextEditor& editor);
  32872. /** @internal */
  32873. void colourChanged();
  32874. /** @internal */
  32875. void valueChanged (Value&);
  32876. private:
  32877. Value textValue;
  32878. String lastTextValue;
  32879. Font font;
  32880. Justification justification;
  32881. ScopedPointer<TextEditor> editor;
  32882. ListenerList<Listener> listeners;
  32883. WeakReference<Component> ownerComponent;
  32884. int horizontalBorderSize, verticalBorderSize;
  32885. float minimumHorizontalScale;
  32886. bool editSingleClick : 1;
  32887. bool editDoubleClick : 1;
  32888. bool lossOfFocusDiscardsChanges : 1;
  32889. bool leftOfOwnerComp : 1;
  32890. bool updateFromTextEditorContents (TextEditor&);
  32891. void callChangeListeners();
  32892. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  32893. };
  32894. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  32895. typedef Label::Listener LabelListener;
  32896. #if JUCE_VC6
  32897. #undef Listener
  32898. #endif
  32899. #endif // __JUCE_LABEL_JUCEHEADER__
  32900. /*** End of inlined file: juce_Label.h ***/
  32901. #if JUCE_VC6
  32902. #define Listener SliderListener
  32903. #endif
  32904. /**
  32905. A component that lets the user choose from a drop-down list of choices.
  32906. The combo-box has a list of text strings, each with an associated id number,
  32907. that will be shown in the drop-down list when the user clicks on the component.
  32908. The currently selected choice is displayed in the combo-box, and this can
  32909. either be read-only text, or editable.
  32910. To find out when the user selects a different item or edits the text, you
  32911. can register a ComboBox::Listener to receive callbacks.
  32912. @see ComboBox::Listener
  32913. */
  32914. class JUCE_API ComboBox : public Component,
  32915. public SettableTooltipClient,
  32916. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  32917. public ValueListener,
  32918. private AsyncUpdater
  32919. {
  32920. public:
  32921. /** Creates a combo-box.
  32922. On construction, the text field will be empty, so you should call the
  32923. setSelectedId() or setText() method to choose the initial value before
  32924. displaying it.
  32925. @param componentName the name to set for the component (see Component::setName())
  32926. */
  32927. explicit ComboBox (const String& componentName = String::empty);
  32928. /** Destructor. */
  32929. ~ComboBox();
  32930. /** Sets whether the test in the combo-box is editable.
  32931. The default state for a new ComboBox is non-editable, and can only be changed
  32932. by choosing from the drop-down list.
  32933. */
  32934. void setEditableText (bool isEditable);
  32935. /** Returns true if the text is directly editable.
  32936. @see setEditableText
  32937. */
  32938. bool isTextEditable() const noexcept;
  32939. /** Sets the style of justification to be used for positioning the text.
  32940. The default is Justification::centredLeft. The text is displayed using a
  32941. Label component inside the ComboBox.
  32942. */
  32943. void setJustificationType (const Justification& justification);
  32944. /** Returns the current justification for the text box.
  32945. @see setJustificationType
  32946. */
  32947. const Justification getJustificationType() const noexcept;
  32948. /** Adds an item to be shown in the drop-down list.
  32949. @param newItemText the text of the item to show in the list
  32950. @param newItemId an associated ID number that can be set or retrieved - see
  32951. getSelectedId() and setSelectedId(). Note that this value can not
  32952. be 0!
  32953. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  32954. */
  32955. void addItem (const String& newItemText, int newItemId);
  32956. /** Adds a separator line to the drop-down list.
  32957. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  32958. */
  32959. void addSeparator();
  32960. /** Adds a heading to the drop-down list, so that you can group the items into
  32961. different sections.
  32962. The headings are indented slightly differently to set them apart from the
  32963. items on the list, and obviously can't be selected. You might want to add
  32964. separators between your sections too.
  32965. @see addItem, addSeparator
  32966. */
  32967. void addSectionHeading (const String& headingName);
  32968. /** This allows items in the drop-down list to be selectively disabled.
  32969. When you add an item, it's enabled by default, but you can call this
  32970. method to change its status.
  32971. If you disable an item which is already selected, this won't change the
  32972. current selection - it just stops the user choosing that item from the list.
  32973. */
  32974. void setItemEnabled (int itemId, bool shouldBeEnabled);
  32975. /** Returns true if the given item is enabled. */
  32976. bool isItemEnabled (int itemId) const noexcept;
  32977. /** Changes the text for an existing item.
  32978. */
  32979. void changeItemText (int itemId, const String& newText);
  32980. /** Removes all the items from the drop-down list.
  32981. If this call causes the content to be cleared, then a change-message
  32982. will be broadcast unless dontSendChangeMessage is true.
  32983. @see addItem, removeItem, getNumItems
  32984. */
  32985. void clear (bool dontSendChangeMessage = false);
  32986. /** Returns the number of items that have been added to the list.
  32987. Note that this doesn't include headers or separators.
  32988. */
  32989. int getNumItems() const noexcept;
  32990. /** Returns the text for one of the items in the list.
  32991. Note that this doesn't include headers or separators.
  32992. @param index the item's index from 0 to (getNumItems() - 1)
  32993. */
  32994. const String getItemText (int index) const;
  32995. /** Returns the ID for one of the items in the list.
  32996. Note that this doesn't include headers or separators.
  32997. @param index the item's index from 0 to (getNumItems() - 1)
  32998. */
  32999. int getItemId (int index) const noexcept;
  33000. /** Returns the index in the list of a particular item ID.
  33001. If no such ID is found, this will return -1.
  33002. */
  33003. int indexOfItemId (int itemId) const noexcept;
  33004. /** Returns the ID of the item that's currently shown in the box.
  33005. If no item is selected, or if the text is editable and the user
  33006. has entered something which isn't one of the items in the list, then
  33007. this will return 0.
  33008. @see setSelectedId, getSelectedItemIndex, getText
  33009. */
  33010. int getSelectedId() const noexcept;
  33011. /** Returns a Value object that can be used to get or set the selected item's ID.
  33012. You can call Value::referTo() on this object to make the combo box control
  33013. another Value object.
  33014. */
  33015. Value& getSelectedIdAsValue() { return currentId; }
  33016. /** Sets one of the items to be the current selection.
  33017. This will set the ComboBox's text to that of the item that matches
  33018. this ID.
  33019. @param newItemId the new item to select
  33020. @param dontSendChangeMessage if set to true, this method won't trigger a
  33021. change notification
  33022. @see getSelectedId, setSelectedItemIndex, setText
  33023. */
  33024. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  33025. /** Returns the index of the item that's currently shown in the box.
  33026. If no item is selected, or if the text is editable and the user
  33027. has entered something which isn't one of the items in the list, then
  33028. this will return -1.
  33029. @see setSelectedItemIndex, getSelectedId, getText
  33030. */
  33031. int getSelectedItemIndex() const;
  33032. /** Sets one of the items to be the current selection.
  33033. This will set the ComboBox's text to that of the item at the given
  33034. index in the list.
  33035. @param newItemIndex the new item to select
  33036. @param dontSendChangeMessage if set to true, this method won't trigger a
  33037. change notification
  33038. @see getSelectedItemIndex, setSelectedId, setText
  33039. */
  33040. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  33041. /** Returns the text that is currently shown in the combo-box's text field.
  33042. If the ComboBox has editable text, then this text may have been edited
  33043. by the user; otherwise it will be one of the items from the list, or
  33044. possibly an empty string if nothing was selected.
  33045. @see setText, getSelectedId, getSelectedItemIndex
  33046. */
  33047. const String getText() const;
  33048. /** Sets the contents of the combo-box's text field.
  33049. The text passed-in will be set as the current text regardless of whether
  33050. it is one of the items in the list. If the current text isn't one of the
  33051. items, then getSelectedId() will return -1, otherwise it wil return
  33052. the approriate ID.
  33053. @param newText the text to select
  33054. @param dontSendChangeMessage if set to true, this method won't trigger a
  33055. change notification
  33056. @see getText
  33057. */
  33058. void setText (const String& newText, bool dontSendChangeMessage = false);
  33059. /** Programmatically opens the text editor to allow the user to edit the current item.
  33060. This is the same effect as when the box is clicked-on.
  33061. @see Label::showEditor();
  33062. */
  33063. void showEditor();
  33064. /** Pops up the combo box's list. */
  33065. void showPopup();
  33066. /**
  33067. A class for receiving events from a ComboBox.
  33068. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  33069. method, and it will be called when the selected item in the box changes.
  33070. @see ComboBox::addListener, ComboBox::removeListener
  33071. */
  33072. class JUCE_API Listener
  33073. {
  33074. public:
  33075. /** Destructor. */
  33076. virtual ~Listener() {}
  33077. /** Called when a ComboBox has its selected item changed. */
  33078. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  33079. };
  33080. /** Registers a listener that will be called when the box's content changes. */
  33081. void addListener (Listener* listener);
  33082. /** Deregisters a previously-registered listener. */
  33083. void removeListener (Listener* listener);
  33084. /** Sets a message to display when there is no item currently selected.
  33085. @see getTextWhenNothingSelected
  33086. */
  33087. void setTextWhenNothingSelected (const String& newMessage);
  33088. /** Returns the text that is shown when no item is selected.
  33089. @see setTextWhenNothingSelected
  33090. */
  33091. const String getTextWhenNothingSelected() const;
  33092. /** Sets the message to show when there are no items in the list, and the user clicks
  33093. on the drop-down box.
  33094. By default it just says "no choices", but this lets you change it to something more
  33095. meaningful.
  33096. */
  33097. void setTextWhenNoChoicesAvailable (const String& newMessage);
  33098. /** Returns the text shown when no items have been added to the list.
  33099. @see setTextWhenNoChoicesAvailable
  33100. */
  33101. const String getTextWhenNoChoicesAvailable() const;
  33102. /** Gives the ComboBox a tooltip. */
  33103. void setTooltip (const String& newTooltip);
  33104. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  33105. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33106. methods.
  33107. To change the colours of the menu that pops up
  33108. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33109. */
  33110. enum ColourIds
  33111. {
  33112. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  33113. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  33114. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  33115. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  33116. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  33117. };
  33118. /** @internal */
  33119. void labelTextChanged (Label*);
  33120. /** @internal */
  33121. void enablementChanged();
  33122. /** @internal */
  33123. void colourChanged();
  33124. /** @internal */
  33125. void focusGained (Component::FocusChangeType cause);
  33126. /** @internal */
  33127. void focusLost (Component::FocusChangeType cause);
  33128. /** @internal */
  33129. void handleAsyncUpdate();
  33130. /** @internal */
  33131. const String getTooltip() { return label->getTooltip(); }
  33132. /** @internal */
  33133. void mouseDown (const MouseEvent&);
  33134. /** @internal */
  33135. void mouseDrag (const MouseEvent&);
  33136. /** @internal */
  33137. void mouseUp (const MouseEvent&);
  33138. /** @internal */
  33139. void lookAndFeelChanged();
  33140. /** @internal */
  33141. void paint (Graphics&);
  33142. /** @internal */
  33143. void resized();
  33144. /** @internal */
  33145. bool keyStateChanged (bool isKeyDown);
  33146. /** @internal */
  33147. bool keyPressed (const KeyPress&);
  33148. /** @internal */
  33149. void valueChanged (Value&);
  33150. private:
  33151. struct ItemInfo
  33152. {
  33153. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  33154. bool isSeparator() const noexcept;
  33155. bool isRealItem() const noexcept;
  33156. String name;
  33157. int itemId;
  33158. bool isEnabled : 1, isHeading : 1;
  33159. };
  33160. OwnedArray <ItemInfo> items;
  33161. Value currentId;
  33162. int lastCurrentId;
  33163. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  33164. ListenerList <Listener> listeners;
  33165. ScopedPointer<Label> label;
  33166. String textWhenNothingSelected, noChoicesMessage;
  33167. ItemInfo* getItemForId (int itemId) const noexcept;
  33168. ItemInfo* getItemForIndex (int index) const noexcept;
  33169. bool selectIfEnabled (int index);
  33170. static void popupMenuFinishedCallback (int, ComboBox*);
  33171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  33172. };
  33173. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  33174. typedef ComboBox::Listener ComboBoxListener;
  33175. #if JUCE_VC6
  33176. #undef Listener
  33177. #endif
  33178. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  33179. /*** End of inlined file: juce_ComboBox.h ***/
  33180. /**
  33181. Manages the state of some audio and midi i/o devices.
  33182. This class keeps tracks of a currently-selected audio device, through
  33183. with which it continuously streams data from an audio callback, as well as
  33184. one or more midi inputs.
  33185. The idea is that your application will create one global instance of this object,
  33186. and let it take care of creating and deleting specific types of audio devices
  33187. internally. So when the device is changed, your callbacks will just keep running
  33188. without having to worry about this.
  33189. The manager can save and reload all of its device settings as XML, which
  33190. makes it very easy for you to save and reload the audio setup of your
  33191. application.
  33192. And to make it easy to let the user change its settings, there's a component
  33193. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  33194. device selection/sample-rate/latency controls.
  33195. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  33196. call addAudioCallback() to register your audio callback with it, and use that to process
  33197. your audio data.
  33198. The manager also acts as a handy hub for incoming midi messages, allowing a
  33199. listener to register for messages from either a specific midi device, or from whatever
  33200. the current default midi input device is. The listener then doesn't have to worry about
  33201. re-registering with different midi devices if they are changed or deleted.
  33202. And yet another neat trick is that amount of CPU time being used is measured and
  33203. available with the getCpuUsage() method.
  33204. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  33205. listeners whenever one of its settings is changed.
  33206. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  33207. */
  33208. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  33209. {
  33210. public:
  33211. /** Creates a default AudioDeviceManager.
  33212. Initially no audio device will be selected. You should call the initialise() method
  33213. and register an audio callback with setAudioCallback() before it'll be able to
  33214. actually make any noise.
  33215. */
  33216. AudioDeviceManager();
  33217. /** Destructor. */
  33218. ~AudioDeviceManager();
  33219. /**
  33220. This structure holds a set of properties describing the current audio setup.
  33221. An AudioDeviceManager uses this class to save/load its current settings, and to
  33222. specify your preferred options when opening a device.
  33223. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  33224. */
  33225. struct JUCE_API AudioDeviceSetup
  33226. {
  33227. /** Creates an AudioDeviceSetup object.
  33228. The default constructor sets all the member variables to indicate default values.
  33229. You can then fill-in any values you want to before passing the object to
  33230. AudioDeviceManager::initialise().
  33231. */
  33232. AudioDeviceSetup();
  33233. bool operator== (const AudioDeviceSetup& other) const;
  33234. /** The name of the audio device used for output.
  33235. The name has to be one of the ones listed by the AudioDeviceManager's currently
  33236. selected device type.
  33237. This may be the same as the input device.
  33238. An empty string indicates the default device.
  33239. */
  33240. String outputDeviceName;
  33241. /** The name of the audio device used for input.
  33242. This may be the same as the output device.
  33243. An empty string indicates the default device.
  33244. */
  33245. String inputDeviceName;
  33246. /** The current sample rate.
  33247. This rate is used for both the input and output devices.
  33248. A value of 0 indicates the default rate.
  33249. */
  33250. double sampleRate;
  33251. /** The buffer size, in samples.
  33252. This buffer size is used for both the input and output devices.
  33253. A value of 0 indicates the default buffer size.
  33254. */
  33255. int bufferSize;
  33256. /** The set of active input channels.
  33257. The bits that are set in this array indicate the channels of the
  33258. input device that are active.
  33259. If useDefaultInputChannels is true, this value is ignored.
  33260. */
  33261. BigInteger inputChannels;
  33262. /** If this is true, it indicates that the inputChannels array
  33263. should be ignored, and instead, the device's default channels
  33264. should be used.
  33265. */
  33266. bool useDefaultInputChannels;
  33267. /** The set of active output channels.
  33268. The bits that are set in this array indicate the channels of the
  33269. input device that are active.
  33270. If useDefaultOutputChannels is true, this value is ignored.
  33271. */
  33272. BigInteger outputChannels;
  33273. /** If this is true, it indicates that the outputChannels array
  33274. should be ignored, and instead, the device's default channels
  33275. should be used.
  33276. */
  33277. bool useDefaultOutputChannels;
  33278. };
  33279. /** Opens a set of audio devices ready for use.
  33280. This will attempt to open either a default audio device, or one that was
  33281. previously saved as XML.
  33282. @param numInputChannelsNeeded a minimum number of input channels needed
  33283. by your app.
  33284. @param numOutputChannelsNeeded a minimum number of output channels to open
  33285. @param savedState either a previously-saved state that was produced
  33286. by createStateXml(), or 0 if you want the manager
  33287. to choose the best device to open.
  33288. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  33289. fails to open, then a default device will be used
  33290. instead. If false, then on failure, no device is
  33291. opened.
  33292. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  33293. name, then that will be used as the default device
  33294. (assuming that there wasn't one specified in the XML).
  33295. The string can actually be a simple wildcard, containing "*"
  33296. and "?" characters
  33297. @param preferredSetupOptions if this is non-null, the structure will be used as the
  33298. set of preferred settings when opening the device. If you
  33299. use this parameter, the preferredDefaultDeviceName
  33300. field will be ignored
  33301. @returns an error message if anything went wrong, or an empty string if it worked ok.
  33302. */
  33303. const String initialise (int numInputChannelsNeeded,
  33304. int numOutputChannelsNeeded,
  33305. const XmlElement* savedState,
  33306. bool selectDefaultDeviceOnFailure,
  33307. const String& preferredDefaultDeviceName = String::empty,
  33308. const AudioDeviceSetup* preferredSetupOptions = 0);
  33309. /** Returns some XML representing the current state of the manager.
  33310. This stores the current device, its samplerate, block size, etc, and
  33311. can be restored later with initialise().
  33312. */
  33313. XmlElement* createStateXml() const;
  33314. /** Returns the current device properties that are in use.
  33315. @see setAudioDeviceSetup
  33316. */
  33317. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  33318. /** Changes the current device or its settings.
  33319. If you want to change a device property, like the current sample rate or
  33320. block size, you can call getAudioDeviceSetup() to retrieve the current
  33321. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  33322. and pass it back into this method to apply the new settings.
  33323. @param newSetup the settings that you'd like to use
  33324. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  33325. settings will be taken as having been explicitly chosen by the
  33326. user, and the next time createStateXml() is called, these settings
  33327. will be returned. If it's false, then the device is treated as a
  33328. temporary or default device, and a call to createStateXml() will
  33329. return either the last settings that were made with treatAsChosenDevice
  33330. as true, or the last XML settings that were passed into initialise().
  33331. @returns an error message if anything went wrong, or an empty string if it worked ok.
  33332. @see getAudioDeviceSetup
  33333. */
  33334. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  33335. bool treatAsChosenDevice);
  33336. /** Returns the currently-active audio device. */
  33337. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  33338. /** Returns the type of audio device currently in use.
  33339. @see setCurrentAudioDeviceType
  33340. */
  33341. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  33342. /** Returns the currently active audio device type object.
  33343. Don't keep a copy of this pointer - it's owned by the device manager and could
  33344. change at any time.
  33345. */
  33346. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  33347. /** Changes the class of audio device being used.
  33348. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  33349. this because there's only one type: CoreAudio.
  33350. For a list of types, see getAvailableDeviceTypes().
  33351. */
  33352. void setCurrentAudioDeviceType (const String& type,
  33353. bool treatAsChosenDevice);
  33354. /** Closes the currently-open device.
  33355. You can call restartLastAudioDevice() later to reopen it in the same state
  33356. that it was just in.
  33357. */
  33358. void closeAudioDevice();
  33359. /** Tries to reload the last audio device that was running.
  33360. Note that this only reloads the last device that was running before
  33361. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  33362. and can only be called after a device has been opened with SetAudioDevice().
  33363. If a device is already open, this call will do nothing.
  33364. */
  33365. void restartLastAudioDevice();
  33366. /** Registers an audio callback to be used.
  33367. The manager will redirect callbacks from whatever audio device is currently
  33368. in use to all registered callback objects. If more than one callback is
  33369. active, they will all be given the same input data, and their outputs will
  33370. be summed.
  33371. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  33372. object before returning.
  33373. To remove a callback, use removeAudioCallback().
  33374. */
  33375. void addAudioCallback (AudioIODeviceCallback* newCallback);
  33376. /** Deregisters a previously added callback.
  33377. If necessary, this method will invoke audioDeviceStopped() on the callback
  33378. object before returning.
  33379. @see addAudioCallback
  33380. */
  33381. void removeAudioCallback (AudioIODeviceCallback* callback);
  33382. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  33383. Returns a value between 0 and 1.0
  33384. */
  33385. double getCpuUsage() const;
  33386. /** Enables or disables a midi input device.
  33387. The list of devices can be obtained with the MidiInput::getDevices() method.
  33388. Any incoming messages from enabled input devices will be forwarded on to all the
  33389. listeners that have been registered with the addMidiInputCallback() method. They
  33390. can either register for messages from a particular device, or from just the
  33391. "default" midi input.
  33392. Routing the midi input via an AudioDeviceManager means that when a listener
  33393. registers for the default midi input, this default device can be changed by the
  33394. manager without the listeners having to know about it or re-register.
  33395. It also means that a listener can stay registered for a midi input that is disabled
  33396. or not present, so that when the input is re-enabled, the listener will start
  33397. receiving messages again.
  33398. @see addMidiInputCallback, isMidiInputEnabled
  33399. */
  33400. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  33401. /** Returns true if a given midi input device is being used.
  33402. @see setMidiInputEnabled
  33403. */
  33404. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  33405. /** Registers a listener for callbacks when midi events arrive from a midi input.
  33406. The device name can be empty to indicate that it wants events from whatever the
  33407. current "default" device is. Or it can be the name of one of the midi input devices
  33408. (see MidiInput::getDevices() for the names).
  33409. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  33410. events forwarded on to listeners.
  33411. */
  33412. void addMidiInputCallback (const String& midiInputDeviceName,
  33413. MidiInputCallback* callback);
  33414. /** Removes a listener that was previously registered with addMidiInputCallback().
  33415. */
  33416. void removeMidiInputCallback (const String& midiInputDeviceName,
  33417. MidiInputCallback* callback);
  33418. /** Sets a midi output device to use as the default.
  33419. The list of devices can be obtained with the MidiOutput::getDevices() method.
  33420. The specified device will be opened automatically and can be retrieved with the
  33421. getDefaultMidiOutput() method.
  33422. Pass in an empty string to deselect all devices. For the default device, you
  33423. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  33424. @see getDefaultMidiOutput, getDefaultMidiOutputName
  33425. */
  33426. void setDefaultMidiOutput (const String& deviceName);
  33427. /** Returns the name of the default midi output.
  33428. @see setDefaultMidiOutput, getDefaultMidiOutput
  33429. */
  33430. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  33431. /** Returns the current default midi output device.
  33432. If no device has been selected, or the device can't be opened, this will
  33433. return 0.
  33434. @see getDefaultMidiOutputName
  33435. */
  33436. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  33437. /** Returns a list of the types of device supported.
  33438. */
  33439. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  33440. /** Creates a list of available types.
  33441. This will add a set of new AudioIODeviceType objects to the specified list, to
  33442. represent each available types of device.
  33443. You can override this if your app needs to do something specific, like avoid
  33444. using DirectSound devices, etc.
  33445. */
  33446. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  33447. /** Plays a beep through the current audio device.
  33448. This is here to allow the audio setup UI panels to easily include a "test"
  33449. button so that the user can check where the audio is coming from.
  33450. */
  33451. void playTestSound();
  33452. /** Turns on level-measuring.
  33453. When enabled, the device manager will measure the peak input level
  33454. across all channels, and you can get this level by calling getCurrentInputLevel().
  33455. This is mainly intended for audio setup UI panels to use to create a mic
  33456. level display, so that the user can check that they've selected the right
  33457. device.
  33458. A simple filter is used to make the level decay smoothly, but this is
  33459. only intended for giving rough feedback, and not for any kind of accurate
  33460. measurement.
  33461. */
  33462. void enableInputLevelMeasurement (bool enableMeasurement);
  33463. /** Returns the current input level.
  33464. To use this, you must first enable it by calling enableInputLevelMeasurement().
  33465. See enableInputLevelMeasurement() for more info.
  33466. */
  33467. double getCurrentInputLevel() const;
  33468. /** Returns the a lock that can be used to synchronise access to the audio callback.
  33469. Obviously while this is locked, you're blocking the audio thread from running, so
  33470. it must only be used for very brief periods when absolutely necessary.
  33471. */
  33472. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  33473. /** Returns the a lock that can be used to synchronise access to the midi callback.
  33474. Obviously while this is locked, you're blocking the midi system from running, so
  33475. it must only be used for very brief periods when absolutely necessary.
  33476. */
  33477. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  33478. private:
  33479. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  33480. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  33481. AudioDeviceSetup currentSetup;
  33482. ScopedPointer <AudioIODevice> currentAudioDevice;
  33483. SortedSet <AudioIODeviceCallback*> callbacks;
  33484. int numInputChansNeeded, numOutputChansNeeded;
  33485. String currentDeviceType;
  33486. BigInteger inputChannels, outputChannels;
  33487. ScopedPointer <XmlElement> lastExplicitSettings;
  33488. mutable bool listNeedsScanning;
  33489. bool useInputNames;
  33490. int inputLevelMeasurementEnabledCount;
  33491. double inputLevel;
  33492. ScopedPointer <AudioSampleBuffer> testSound;
  33493. int testSoundPosition;
  33494. AudioSampleBuffer tempBuffer;
  33495. StringArray midiInsFromXml;
  33496. OwnedArray <MidiInput> enabledMidiInputs;
  33497. Array <MidiInputCallback*> midiCallbacks;
  33498. StringArray midiCallbackDevices;
  33499. String defaultMidiOutputName;
  33500. ScopedPointer <MidiOutput> defaultMidiOutput;
  33501. CriticalSection audioCallbackLock, midiCallbackLock;
  33502. double cpuUsageMs, timeToCpuScale;
  33503. class CallbackHandler : public AudioIODeviceCallback,
  33504. public MidiInputCallback
  33505. {
  33506. public:
  33507. void audioDeviceIOCallback (const float**, int, float**, int, int);
  33508. void audioDeviceAboutToStart (AudioIODevice*);
  33509. void audioDeviceStopped();
  33510. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  33511. AudioDeviceManager* owner;
  33512. };
  33513. CallbackHandler callbackHandler;
  33514. friend class CallbackHandler;
  33515. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  33516. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  33517. void audioDeviceAboutToStartInt (AudioIODevice*);
  33518. void audioDeviceStoppedInt();
  33519. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  33520. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  33521. const BigInteger& ins, const BigInteger& outs);
  33522. void stopDevice();
  33523. void updateXml();
  33524. void createDeviceTypesIfNeeded();
  33525. void scanDevicesIfNeeded();
  33526. void deleteCurrentDevice();
  33527. double chooseBestSampleRate (double preferred) const;
  33528. int chooseBestBufferSize (int preferred) const;
  33529. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  33530. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  33531. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  33532. };
  33533. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  33534. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  33535. #endif
  33536. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  33537. #endif
  33538. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  33539. #endif
  33540. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  33541. #endif
  33542. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  33543. #endif
  33544. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  33545. /*** Start of inlined file: juce_Decibels.h ***/
  33546. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  33547. #define __JUCE_DECIBELS_JUCEHEADER__
  33548. /**
  33549. This class contains some helpful static methods for dealing with decibel values.
  33550. */
  33551. class Decibels
  33552. {
  33553. public:
  33554. /** Converts a dBFS value to its equivalent gain level.
  33555. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  33556. decibel value lower than minusInfinityDb will return a gain of 0.
  33557. */
  33558. template <typename Type>
  33559. static Type decibelsToGain (const Type decibels,
  33560. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33561. {
  33562. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  33563. : Type();
  33564. }
  33565. /** Converts a gain level into a dBFS value.
  33566. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  33567. If the gain is 0 (or negative), then the method will return the value
  33568. provided as minusInfinityDb.
  33569. */
  33570. template <typename Type>
  33571. static Type gainToDecibels (const Type gain,
  33572. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33573. {
  33574. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  33575. : minusInfinityDb;
  33576. }
  33577. /** Converts a decibel reading to a string, with the 'dB' suffix.
  33578. If the decibel value is lower than minusInfinityDb, the return value will
  33579. be "-INF dB".
  33580. */
  33581. template <typename Type>
  33582. static const String toString (const Type decibels,
  33583. const int decimalPlaces = 2,
  33584. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33585. {
  33586. String s;
  33587. if (decibels <= minusInfinityDb)
  33588. {
  33589. s = "-INF dB";
  33590. }
  33591. else
  33592. {
  33593. if (decibels >= Type())
  33594. s << '+';
  33595. s << String (decibels, decimalPlaces) << " dB";
  33596. }
  33597. return s;
  33598. }
  33599. private:
  33600. enum
  33601. {
  33602. defaultMinusInfinitydB = -100
  33603. };
  33604. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  33605. JUCE_DECLARE_NON_COPYABLE (Decibels);
  33606. };
  33607. #endif // __JUCE_DECIBELS_JUCEHEADER__
  33608. /*** End of inlined file: juce_Decibels.h ***/
  33609. #endif
  33610. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  33611. #endif
  33612. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  33613. #endif
  33614. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33615. /*** Start of inlined file: juce_MidiFile.h ***/
  33616. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33617. #define __JUCE_MIDIFILE_JUCEHEADER__
  33618. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  33619. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33620. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33621. /**
  33622. A sequence of timestamped midi messages.
  33623. This allows the sequence to be manipulated, and also to be read from and
  33624. written to a standard midi file.
  33625. @see MidiMessage, MidiFile
  33626. */
  33627. class JUCE_API MidiMessageSequence
  33628. {
  33629. public:
  33630. /** Creates an empty midi sequence object. */
  33631. MidiMessageSequence();
  33632. /** Creates a copy of another sequence. */
  33633. MidiMessageSequence (const MidiMessageSequence& other);
  33634. /** Replaces this sequence with another one. */
  33635. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  33636. /** Destructor. */
  33637. ~MidiMessageSequence();
  33638. /** Structure used to hold midi events in the sequence.
  33639. These structures act as 'handles' on the events as they are moved about in
  33640. the list, and make it quick to find the matching note-offs for note-on events.
  33641. @see MidiMessageSequence::getEventPointer
  33642. */
  33643. class MidiEventHolder
  33644. {
  33645. public:
  33646. /** Destructor. */
  33647. ~MidiEventHolder();
  33648. /** The message itself, whose timestamp is used to specify the event's time.
  33649. */
  33650. MidiMessage message;
  33651. /** The matching note-off event (if this is a note-on event).
  33652. If this isn't a note-on, this pointer will be null.
  33653. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  33654. note-offs up-to-date after events have been moved around in the sequence
  33655. or deleted.
  33656. */
  33657. MidiEventHolder* noteOffObject;
  33658. private:
  33659. friend class MidiMessageSequence;
  33660. MidiEventHolder (const MidiMessage& message);
  33661. JUCE_LEAK_DETECTOR (MidiEventHolder);
  33662. };
  33663. /** Clears the sequence. */
  33664. void clear();
  33665. /** Returns the number of events in the sequence. */
  33666. int getNumEvents() const;
  33667. /** Returns a pointer to one of the events. */
  33668. MidiEventHolder* getEventPointer (int index) const;
  33669. /** Returns the time of the note-up that matches the note-on at this index.
  33670. If the event at this index isn't a note-on, it'll just return 0.
  33671. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33672. */
  33673. double getTimeOfMatchingKeyUp (int index) const;
  33674. /** Returns the index of the note-up that matches the note-on at this index.
  33675. If the event at this index isn't a note-on, it'll just return -1.
  33676. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33677. */
  33678. int getIndexOfMatchingKeyUp (int index) const;
  33679. /** Returns the index of an event. */
  33680. int getIndexOf (MidiEventHolder* event) const;
  33681. /** Returns the index of the first event on or after the given timestamp.
  33682. If the time is beyond the end of the sequence, this will return the
  33683. number of events.
  33684. */
  33685. int getNextIndexAtTime (double timeStamp) const;
  33686. /** Returns the timestamp of the first event in the sequence.
  33687. @see getEndTime
  33688. */
  33689. double getStartTime() const;
  33690. /** Returns the timestamp of the last event in the sequence.
  33691. @see getStartTime
  33692. */
  33693. double getEndTime() const;
  33694. /** Returns the timestamp of the event at a given index.
  33695. If the index is out-of-range, this will return 0.0
  33696. */
  33697. double getEventTime (int index) const;
  33698. /** Inserts a midi message into the sequence.
  33699. The index at which the new message gets inserted will depend on its timestamp,
  33700. because the sequence is kept sorted.
  33701. Remember to call updateMatchedPairs() after adding note-on events.
  33702. @param newMessage the new message to add (an internal copy will be made)
  33703. @param timeAdjustment an optional value to add to the timestamp of the message
  33704. that will be inserted
  33705. @see updateMatchedPairs
  33706. */
  33707. void addEvent (const MidiMessage& newMessage,
  33708. double timeAdjustment = 0);
  33709. /** Deletes one of the events in the sequence.
  33710. Remember to call updateMatchedPairs() after removing events.
  33711. @param index the index of the event to delete
  33712. @param deleteMatchingNoteUp whether to also remove the matching note-off
  33713. if the event you're removing is a note-on
  33714. */
  33715. void deleteEvent (int index, bool deleteMatchingNoteUp);
  33716. /** Merges another sequence into this one.
  33717. Remember to call updateMatchedPairs() after using this method.
  33718. @param other the sequence to add from
  33719. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  33720. as they are read from the other sequence
  33721. @param firstAllowableDestTime events will not be added if their time is earlier
  33722. than this time. (This is after their time has been adjusted
  33723. by the timeAdjustmentDelta)
  33724. @param endOfAllowableDestTimes events will not be added if their time is equal to
  33725. or greater than this time. (This is after their time has
  33726. been adjusted by the timeAdjustmentDelta)
  33727. */
  33728. void addSequence (const MidiMessageSequence& other,
  33729. double timeAdjustmentDelta,
  33730. double firstAllowableDestTime,
  33731. double endOfAllowableDestTimes);
  33732. /** Makes sure all the note-on and note-off pairs are up-to-date.
  33733. Call this after moving messages about or deleting/adding messages, and it
  33734. will scan the list and make sure all the note-offs in the MidiEventHolder
  33735. structures are pointing at the correct ones.
  33736. */
  33737. void updateMatchedPairs();
  33738. /** Copies all the messages for a particular midi channel to another sequence.
  33739. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  33740. @param destSequence the sequence that the chosen events should be copied to
  33741. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  33742. channel) will also be copied across.
  33743. @see extractSysExMessages
  33744. */
  33745. void extractMidiChannelMessages (int channelNumberToExtract,
  33746. MidiMessageSequence& destSequence,
  33747. bool alsoIncludeMetaEvents) const;
  33748. /** Copies all midi sys-ex messages to another sequence.
  33749. @param destSequence this is the sequence to which any sys-exes in this sequence
  33750. will be added
  33751. @see extractMidiChannelMessages
  33752. */
  33753. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  33754. /** Removes any messages in this sequence that have a specific midi channel.
  33755. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  33756. */
  33757. void deleteMidiChannelMessages (int channelNumberToRemove);
  33758. /** Removes any sys-ex messages from this sequence.
  33759. */
  33760. void deleteSysExMessages();
  33761. /** Adds an offset to the timestamps of all events in the sequence.
  33762. @param deltaTime the amount to add to each timestamp.
  33763. */
  33764. void addTimeToMessages (double deltaTime);
  33765. /** Scans through the sequence to determine the state of any midi controllers at
  33766. a given time.
  33767. This will create a sequence of midi controller changes that can be
  33768. used to set all midi controllers to the state they would be in at the
  33769. specified time within this sequence.
  33770. As well as controllers, it will also recreate the midi program number
  33771. and pitch bend position.
  33772. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  33773. for other channels will be ignored.
  33774. @param time the time at which you want to find out the state - there are
  33775. no explicit units for this time measurement, it's the same units
  33776. as used for the timestamps of the messages
  33777. @param resultMessages an array to which midi controller-change messages will be added. This
  33778. will be the minimum number of controller changes to recreate the
  33779. state at the required time.
  33780. */
  33781. void createControllerUpdatesForTime (int channelNumber, double time,
  33782. OwnedArray<MidiMessage>& resultMessages);
  33783. /** Swaps this sequence with another one. */
  33784. void swapWith (MidiMessageSequence& other) noexcept;
  33785. /** @internal */
  33786. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  33787. const MidiMessageSequence::MidiEventHolder* second) noexcept;
  33788. private:
  33789. friend class MidiFile;
  33790. OwnedArray <MidiEventHolder> list;
  33791. void sort();
  33792. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  33793. };
  33794. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33795. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  33796. /**
  33797. Reads/writes standard midi format files.
  33798. To read a midi file, create a MidiFile object and call its readFrom() method. You
  33799. can then get the individual midi tracks from it using the getTrack() method.
  33800. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  33801. to it using the addTrack() method, and then call its writeTo() method to stream
  33802. it out.
  33803. @see MidiMessageSequence
  33804. */
  33805. class JUCE_API MidiFile
  33806. {
  33807. public:
  33808. /** Creates an empty MidiFile object.
  33809. */
  33810. MidiFile();
  33811. /** Destructor. */
  33812. ~MidiFile();
  33813. /** Returns the number of tracks in the file.
  33814. @see getTrack, addTrack
  33815. */
  33816. int getNumTracks() const noexcept;
  33817. /** Returns a pointer to one of the tracks in the file.
  33818. @returns a pointer to the track, or 0 if the index is out-of-range
  33819. @see getNumTracks, addTrack
  33820. */
  33821. const MidiMessageSequence* getTrack (int index) const noexcept;
  33822. /** Adds a midi track to the file.
  33823. This will make its own internal copy of the sequence that is passed-in.
  33824. @see getNumTracks, getTrack
  33825. */
  33826. void addTrack (const MidiMessageSequence& trackSequence);
  33827. /** Removes all midi tracks from the file.
  33828. @see getNumTracks
  33829. */
  33830. void clear();
  33831. /** Returns the raw time format code that will be written to a stream.
  33832. After reading a midi file, this method will return the time-format that
  33833. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  33834. or setSmpteTimeFormat() methods.
  33835. If the value returned is positive, it indicates the number of midi ticks
  33836. per quarter-note - see setTicksPerQuarterNote().
  33837. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  33838. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  33839. */
  33840. short getTimeFormat() const noexcept;
  33841. /** Sets the time format to use when this file is written to a stream.
  33842. If this is called, the file will be written as bars/beats using the
  33843. specified resolution, rather than SMPTE absolute times, as would be
  33844. used if setSmpteTimeFormat() had been called instead.
  33845. @param ticksPerQuarterNote e.g. 96, 960
  33846. @see setSmpteTimeFormat
  33847. */
  33848. void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;
  33849. /** Sets the time format to use when this file is written to a stream.
  33850. If this is called, the file will be written using absolute times, rather
  33851. than bars/beats as would be the case if setTicksPerBeat() had been called
  33852. instead.
  33853. @param framesPerSecond must be 24, 25, 29 or 30
  33854. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  33855. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  33856. timing, setSmpteTimeFormat (25, 40)
  33857. @see setTicksPerBeat
  33858. */
  33859. void setSmpteTimeFormat (int framesPerSecond,
  33860. int subframeResolution) noexcept;
  33861. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  33862. Useful for finding the positions of all the tempo changes in a file.
  33863. @param tempoChangeEvents a list to which all the events will be added
  33864. */
  33865. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  33866. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  33867. Useful for finding the positions of all the tempo changes in a file.
  33868. @param timeSigEvents a list to which all the events will be added
  33869. */
  33870. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  33871. /** Returns the latest timestamp in any of the tracks.
  33872. (Useful for finding the length of the file).
  33873. */
  33874. double getLastTimestamp() const;
  33875. /** Reads a midi file format stream.
  33876. After calling this, you can get the tracks that were read from the file by using the
  33877. getNumTracks() and getTrack() methods.
  33878. The timestamps of the midi events in the tracks will represent their positions in
  33879. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  33880. method.
  33881. @returns true if the stream was read successfully
  33882. */
  33883. bool readFrom (InputStream& sourceStream);
  33884. /** Writes the midi tracks as a standard midi file.
  33885. @returns true if the operation succeeded.
  33886. */
  33887. bool writeTo (OutputStream& destStream);
  33888. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  33889. This will use the midi time format and tempo/time signature info in the
  33890. tracks to convert all the timestamps to absolute values in seconds.
  33891. */
  33892. void convertTimestampTicksToSeconds();
  33893. private:
  33894. OwnedArray <MidiMessageSequence> tracks;
  33895. short timeFormat;
  33896. void readNextTrack (const uint8* data, int size);
  33897. void writeTrack (OutputStream& mainOut, int trackNum);
  33898. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  33899. };
  33900. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  33901. /*** End of inlined file: juce_MidiFile.h ***/
  33902. #endif
  33903. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  33904. #endif
  33905. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33906. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  33907. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33908. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33909. class MidiKeyboardState;
  33910. /**
  33911. Receives events from a MidiKeyboardState object.
  33912. @see MidiKeyboardState
  33913. */
  33914. class JUCE_API MidiKeyboardStateListener
  33915. {
  33916. public:
  33917. MidiKeyboardStateListener() noexcept {}
  33918. virtual ~MidiKeyboardStateListener() {}
  33919. /** Called when one of the MidiKeyboardState's keys is pressed.
  33920. This will be called synchronously when the state is either processing a
  33921. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33922. when a note is being played with its MidiKeyboardState::noteOn() method.
  33923. Note that this callback could happen from an audio callback thread, so be
  33924. careful not to block, and avoid any UI activity in the callback.
  33925. */
  33926. virtual void handleNoteOn (MidiKeyboardState* source,
  33927. int midiChannel, int midiNoteNumber, float velocity) = 0;
  33928. /** Called when one of the MidiKeyboardState's keys is released.
  33929. This will be called synchronously when the state is either processing a
  33930. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33931. when a note is being played with its MidiKeyboardState::noteOff() method.
  33932. Note that this callback could happen from an audio callback thread, so be
  33933. careful not to block, and avoid any UI activity in the callback.
  33934. */
  33935. virtual void handleNoteOff (MidiKeyboardState* source,
  33936. int midiChannel, int midiNoteNumber) = 0;
  33937. };
  33938. /**
  33939. Represents a piano keyboard, keeping track of which keys are currently pressed.
  33940. This object can parse a stream of midi events, using them to update its idea
  33941. of which keys are pressed for each individiual midi channel.
  33942. When keys go up or down, it can broadcast these events to listener objects.
  33943. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  33944. methods, and midi messages for these events will be merged into the
  33945. midi stream that gets processed by processNextMidiBuffer().
  33946. */
  33947. class JUCE_API MidiKeyboardState
  33948. {
  33949. public:
  33950. MidiKeyboardState();
  33951. ~MidiKeyboardState();
  33952. /** Resets the state of the object.
  33953. All internal data for all the channels is reset, but no events are sent as a
  33954. result.
  33955. If you want to release any keys that are currently down, and to send out note-up
  33956. midi messages for this, use the allNotesOff() method instead.
  33957. */
  33958. void reset();
  33959. /** Returns true if the given midi key is currently held down for the given midi channel.
  33960. The channel number must be between 1 and 16. If you want to see if any notes are
  33961. on for a range of channels, use the isNoteOnForChannels() method.
  33962. */
  33963. bool isNoteOn (int midiChannel, int midiNoteNumber) const noexcept;
  33964. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  33965. The channel mask has a bit set for each midi channel you want to test for - bit
  33966. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  33967. If a note is on for at least one of the specified channels, this returns true.
  33968. */
  33969. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const noexcept;
  33970. /** Turns a specified note on.
  33971. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  33972. next call to processNextMidiBuffer().
  33973. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33974. gone down.
  33975. */
  33976. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  33977. /** Turns a specified note off.
  33978. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  33979. next call to processNextMidiBuffer().
  33980. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33981. gone up.
  33982. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  33983. */
  33984. void noteOff (int midiChannel, int midiNoteNumber);
  33985. /** This will turn off any currently-down notes for the given midi channel.
  33986. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  33987. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  33988. and events being added to the midi stream.
  33989. */
  33990. void allNotesOff (int midiChannel);
  33991. /** Looks at a key-up/down event and uses it to update the state of this object.
  33992. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  33993. instead.
  33994. */
  33995. void processNextMidiEvent (const MidiMessage& message);
  33996. /** Scans a midi stream for up/down events and adds its own events to it.
  33997. This will look for any up/down events and use them to update the internal state,
  33998. synchronously making suitable callbacks to the listeners.
  33999. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  34000. and noteOff() calls will be added into the buffer.
  34001. Only the section of the buffer whose timestamps are between startSample and
  34002. (startSample + numSamples) will be affected, and any events added will be placed
  34003. between these times.
  34004. If you're going to use this method, you'll need to keep calling it regularly for
  34005. it to work satisfactorily.
  34006. To process a single midi event at a time, use the processNextMidiEvent() method
  34007. instead.
  34008. */
  34009. void processNextMidiBuffer (MidiBuffer& buffer,
  34010. int startSample,
  34011. int numSamples,
  34012. bool injectIndirectEvents);
  34013. /** Registers a listener for callbacks when keys go up or down.
  34014. @see removeListener
  34015. */
  34016. void addListener (MidiKeyboardStateListener* listener);
  34017. /** Deregisters a listener.
  34018. @see addListener
  34019. */
  34020. void removeListener (MidiKeyboardStateListener* listener);
  34021. private:
  34022. CriticalSection lock;
  34023. uint16 noteStates [128];
  34024. MidiBuffer eventsToAdd;
  34025. Array <MidiKeyboardStateListener*> listeners;
  34026. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  34027. void noteOffInternal (int midiChannel, int midiNoteNumber);
  34028. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  34029. };
  34030. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  34031. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  34032. #endif
  34033. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  34034. #endif
  34035. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34036. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  34037. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34038. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34039. /**
  34040. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  34041. processing by a block-based audio callback.
  34042. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  34043. so it can easily use a midi input or keyboard component as its source.
  34044. @see MidiMessage, MidiInput
  34045. */
  34046. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  34047. public MidiInputCallback
  34048. {
  34049. public:
  34050. /** Creates a MidiMessageCollector. */
  34051. MidiMessageCollector();
  34052. /** Destructor. */
  34053. ~MidiMessageCollector();
  34054. /** Clears any messages from the queue.
  34055. You need to call this method before starting to use the collector, so that
  34056. it knows the correct sample rate to use.
  34057. */
  34058. void reset (double sampleRate);
  34059. /** Takes an incoming real-time message and adds it to the queue.
  34060. The message's timestamp is taken, and it will be ready for retrieval as part
  34061. of the block returned by the next call to removeNextBlockOfMessages().
  34062. This method is fully thread-safe when overlapping calls are made with
  34063. removeNextBlockOfMessages().
  34064. */
  34065. void addMessageToQueue (const MidiMessage& message);
  34066. /** Removes all the pending messages from the queue as a buffer.
  34067. This will also correct the messages' timestamps to make sure they're in
  34068. the range 0 to numSamples - 1.
  34069. This call should be made regularly by something like an audio processing
  34070. callback, because the time that it happens is used in calculating the
  34071. midi event positions.
  34072. This method is fully thread-safe when overlapping calls are made with
  34073. addMessageToQueue().
  34074. */
  34075. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  34076. /** @internal */
  34077. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  34078. /** @internal */
  34079. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  34080. /** @internal */
  34081. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  34082. private:
  34083. double lastCallbackTime;
  34084. CriticalSection midiCallbackLock;
  34085. MidiBuffer incomingMessages;
  34086. double sampleRate;
  34087. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  34088. };
  34089. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34090. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  34091. #endif
  34092. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  34093. #endif
  34094. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  34095. #endif
  34096. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34097. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  34098. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34099. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34100. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  34101. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34102. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34103. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  34104. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34105. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34106. /*** Start of inlined file: juce_AudioProcessor.h ***/
  34107. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34108. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34109. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  34110. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34111. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34112. class AudioProcessor;
  34113. /**
  34114. Base class for the component that acts as the GUI for an AudioProcessor.
  34115. Derive your editor component from this class, and create an instance of it
  34116. by overriding the AudioProcessor::createEditor() method.
  34117. @see AudioProcessor, GenericAudioProcessorEditor
  34118. */
  34119. class JUCE_API AudioProcessorEditor : public Component
  34120. {
  34121. protected:
  34122. /** Creates an editor for the specified processor.
  34123. */
  34124. AudioProcessorEditor (AudioProcessor* owner);
  34125. public:
  34126. /** Destructor. */
  34127. ~AudioProcessorEditor();
  34128. /** Returns a pointer to the processor that this editor represents. */
  34129. AudioProcessor* getAudioProcessor() const noexcept { return owner; }
  34130. private:
  34131. AudioProcessor* const owner;
  34132. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  34133. };
  34134. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34135. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  34136. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  34137. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34138. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34139. class AudioProcessor;
  34140. /**
  34141. Base class for listeners that want to know about changes to an AudioProcessor.
  34142. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  34143. @see AudioProcessor
  34144. */
  34145. class JUCE_API AudioProcessorListener
  34146. {
  34147. public:
  34148. /** Destructor. */
  34149. virtual ~AudioProcessorListener() {}
  34150. /** Receives a callback when a parameter is changed.
  34151. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  34152. many audio processors will change their parameter during their audio callback.
  34153. This means that not only has your handler code got to be completely thread-safe,
  34154. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  34155. this event on your message thread, use this callback to trigger an AsyncUpdater
  34156. or ChangeBroadcaster which you can respond to on the message thread.
  34157. */
  34158. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  34159. int parameterIndex,
  34160. float newValue) = 0;
  34161. /** Called to indicate that something else in the plugin has changed, like its
  34162. program, number of parameters, etc.
  34163. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34164. call it during their audio callback. This means that not only has your handler code
  34165. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34166. blocking. If you need to handle this event on your message thread, use this callback
  34167. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34168. message thread.
  34169. */
  34170. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  34171. /** Indicates that a parameter change gesture has started.
  34172. E.g. if the user is dragging a slider, this would be called when they first
  34173. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  34174. called when they release it.
  34175. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34176. call it during their audio callback. This means that not only has your handler code
  34177. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34178. blocking. If you need to handle this event on your message thread, use this callback
  34179. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34180. message thread.
  34181. @see audioProcessorParameterChangeGestureEnd
  34182. */
  34183. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  34184. int parameterIndex);
  34185. /** Indicates that a parameter change gesture has finished.
  34186. E.g. if the user is dragging a slider, this would be called when they release
  34187. the mouse button.
  34188. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34189. call it during their audio callback. This means that not only has your handler code
  34190. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34191. blocking. If you need to handle this event on your message thread, use this callback
  34192. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34193. message thread.
  34194. @see audioProcessorParameterChangeGestureBegin
  34195. */
  34196. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  34197. int parameterIndex);
  34198. };
  34199. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34200. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  34201. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  34202. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34203. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34204. /**
  34205. A subclass of AudioPlayHead can supply information about the position and
  34206. status of a moving play head during audio playback.
  34207. One of these can be supplied to an AudioProcessor object so that it can find
  34208. out about the position of the audio that it is rendering.
  34209. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  34210. */
  34211. class JUCE_API AudioPlayHead
  34212. {
  34213. protected:
  34214. AudioPlayHead() {}
  34215. public:
  34216. virtual ~AudioPlayHead() {}
  34217. /** Frame rate types. */
  34218. enum FrameRateType
  34219. {
  34220. fps24 = 0,
  34221. fps25 = 1,
  34222. fps2997 = 2,
  34223. fps30 = 3,
  34224. fps2997drop = 4,
  34225. fps30drop = 5,
  34226. fpsUnknown = 99
  34227. };
  34228. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  34229. */
  34230. struct CurrentPositionInfo
  34231. {
  34232. /** The tempo in BPM */
  34233. double bpm;
  34234. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  34235. int timeSigNumerator;
  34236. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  34237. int timeSigDenominator;
  34238. /** The current play position, in seconds from the start of the edit. */
  34239. double timeInSeconds;
  34240. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  34241. double editOriginTime;
  34242. /** The current play position in pulses-per-quarter-note.
  34243. This is the number of quarter notes since the edit start.
  34244. */
  34245. double ppqPosition;
  34246. /** The position of the start of the last bar, in pulses-per-quarter-note.
  34247. This is the number of quarter notes from the start of the edit to the
  34248. start of the current bar.
  34249. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  34250. it's not available, the value will be 0.
  34251. */
  34252. double ppqPositionOfLastBarStart;
  34253. /** The video frame rate, if applicable. */
  34254. FrameRateType frameRate;
  34255. /** True if the transport is currently playing. */
  34256. bool isPlaying;
  34257. /** True if the transport is currently recording.
  34258. (When isRecording is true, then isPlaying will also be true).
  34259. */
  34260. bool isRecording;
  34261. bool operator== (const CurrentPositionInfo& other) const noexcept;
  34262. bool operator!= (const CurrentPositionInfo& other) const noexcept;
  34263. void resetToDefault();
  34264. };
  34265. /** Fills-in the given structure with details about the transport's
  34266. position at the start of the current processing block.
  34267. */
  34268. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  34269. };
  34270. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34271. /*** End of inlined file: juce_AudioPlayHead.h ***/
  34272. /**
  34273. Base class for audio processing filters or plugins.
  34274. This is intended to act as a base class of audio filter that is general enough to
  34275. be wrapped as a VST, AU, RTAS, etc, or used internally.
  34276. It is also used by the plugin hosting code as the wrapper around an instance
  34277. of a loaded plugin.
  34278. Derive your filter class from this base class, and if you're building a plugin,
  34279. you should implement a global function called createPluginFilter() which creates
  34280. and returns a new instance of your subclass.
  34281. */
  34282. class JUCE_API AudioProcessor
  34283. {
  34284. protected:
  34285. /** Constructor.
  34286. You can also do your initialisation tasks in the initialiseFilterInfo()
  34287. call, which will be made after this object has been created.
  34288. */
  34289. AudioProcessor();
  34290. public:
  34291. /** Destructor. */
  34292. virtual ~AudioProcessor();
  34293. /** Returns the name of this processor.
  34294. */
  34295. virtual const String getName() const = 0;
  34296. /** Called before playback starts, to let the filter prepare itself.
  34297. The sample rate is the target sample rate, and will remain constant until
  34298. playback stops.
  34299. The estimatedSamplesPerBlock value is a HINT about the typical number of
  34300. samples that will be processed for each callback, but isn't any kind
  34301. of guarantee. The actual block sizes that the host uses may be different
  34302. each time the callback happens, and may be more or less than this value.
  34303. */
  34304. virtual void prepareToPlay (double sampleRate,
  34305. int estimatedSamplesPerBlock) = 0;
  34306. /** Called after playback has stopped, to let the filter free up any resources it
  34307. no longer needs.
  34308. */
  34309. virtual void releaseResources() = 0;
  34310. /** Renders the next block.
  34311. When this method is called, the buffer contains a number of channels which is
  34312. at least as great as the maximum number of input and output channels that
  34313. this filter is using. It will be filled with the filter's input data and
  34314. should be replaced with the filter's output.
  34315. So for example if your filter has 2 input channels and 4 output channels, then
  34316. the buffer will contain 4 channels, the first two being filled with the
  34317. input data. Your filter should read these, do its processing, and replace
  34318. the contents of all 4 channels with its output.
  34319. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  34320. all filled with data, and your filter should overwrite the first 2 of these
  34321. with its output. But be VERY careful not to write anything to the last 3
  34322. channels, as these might be mapped to memory that the host assumes is read-only!
  34323. Note that if you have more outputs than inputs, then only those channels that
  34324. correspond to an input channel are guaranteed to contain sensible data - e.g.
  34325. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  34326. but the last two channels may contain garbage, so you should be careful not to
  34327. let this pass through without being overwritten or cleared.
  34328. Also note that the buffer may have more channels than are strictly necessary,
  34329. but your should only read/write from the ones that your filter is supposed to
  34330. be using.
  34331. The number of samples in these buffers is NOT guaranteed to be the same for every
  34332. callback, and may be more or less than the estimated value given to prepareToPlay().
  34333. Your code must be able to cope with variable-sized blocks, or you're going to get
  34334. clicks and crashes!
  34335. If the filter is receiving a midi input, then the midiMessages array will be filled
  34336. with the midi messages for this block. Each message's timestamp will indicate the
  34337. message's time, as a number of samples from the start of the block.
  34338. Any messages left in the midi buffer when this method has finished are assumed to
  34339. be the filter's midi output. This means that your filter should be careful to
  34340. clear any incoming messages from the array if it doesn't want them to be passed-on.
  34341. Be very careful about what you do in this callback - it's going to be called by
  34342. the audio thread, so any kind of interaction with the UI is absolutely
  34343. out of the question. If you change a parameter in here and need to tell your UI to
  34344. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  34345. the UI components register as listeners, and then call sendChangeMessage() inside the
  34346. processBlock() method to send out an asynchronous message. You could also use
  34347. the AsyncUpdater class in a similar way.
  34348. */
  34349. virtual void processBlock (AudioSampleBuffer& buffer,
  34350. MidiBuffer& midiMessages) = 0;
  34351. /** Returns the current AudioPlayHead object that should be used to find
  34352. out the state and position of the playhead.
  34353. You can call this from your processBlock() method, and use the AudioPlayHead
  34354. object to get the details about the time of the start of the block currently
  34355. being processed.
  34356. If the host hasn't supplied a playhead object, this will return 0.
  34357. */
  34358. AudioPlayHead* getPlayHead() const noexcept { return playHead; }
  34359. /** Returns the current sample rate.
  34360. This can be called from your processBlock() method - it's not guaranteed
  34361. to be valid at any other time, and may return 0 if it's unknown.
  34362. */
  34363. double getSampleRate() const noexcept { return sampleRate; }
  34364. /** Returns the current typical block size that is being used.
  34365. This can be called from your processBlock() method - it's not guaranteed
  34366. to be valid at any other time.
  34367. Remember it's not the ONLY block size that may be used when calling
  34368. processBlock, it's just the normal one. The actual block sizes used may be
  34369. larger or smaller than this, and will vary between successive calls.
  34370. */
  34371. int getBlockSize() const noexcept { return blockSize; }
  34372. /** Returns the number of input channels that the host will be sending the filter.
  34373. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  34374. number of channels that your filter would prefer to have, and this method lets
  34375. you know how many the host is actually using.
  34376. Note that this method is only valid during or after the prepareToPlay()
  34377. method call. Until that point, the number of channels will be unknown.
  34378. */
  34379. int getNumInputChannels() const noexcept { return numInputChannels; }
  34380. /** Returns the number of output channels that the host will be sending the filter.
  34381. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  34382. number of channels that your filter would prefer to have, and this method lets
  34383. you know how many the host is actually using.
  34384. Note that this method is only valid during or after the prepareToPlay()
  34385. method call. Until that point, the number of channels will be unknown.
  34386. */
  34387. int getNumOutputChannels() const noexcept { return numOutputChannels; }
  34388. /** Returns the name of one of the input channels, as returned by the host.
  34389. The host might not supply very useful names for channels, and this might be
  34390. something like "1", "2", "left", "right", etc.
  34391. */
  34392. virtual const String getInputChannelName (int channelIndex) const = 0;
  34393. /** Returns the name of one of the output channels, as returned by the host.
  34394. The host might not supply very useful names for channels, and this might be
  34395. something like "1", "2", "left", "right", etc.
  34396. */
  34397. virtual const String getOutputChannelName (int channelIndex) const = 0;
  34398. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  34399. virtual bool isInputChannelStereoPair (int index) const = 0;
  34400. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  34401. virtual bool isOutputChannelStereoPair (int index) const = 0;
  34402. /** This returns the number of samples delay that the filter imposes on the audio
  34403. passing through it.
  34404. The host will call this to find the latency - the filter itself should set this value
  34405. by calling setLatencySamples() as soon as it can during its initialisation.
  34406. */
  34407. int getLatencySamples() const noexcept { return latencySamples; }
  34408. /** The filter should call this to set the number of samples delay that it introduces.
  34409. The filter should call this as soon as it can during initialisation, and can call it
  34410. later if the value changes.
  34411. */
  34412. void setLatencySamples (int newLatency);
  34413. /** Returns true if the processor wants midi messages. */
  34414. virtual bool acceptsMidi() const = 0;
  34415. /** Returns true if the processor produces midi messages. */
  34416. virtual bool producesMidi() const = 0;
  34417. /** This returns a critical section that will automatically be locked while the host
  34418. is calling the processBlock() method.
  34419. Use it from your UI or other threads to lock access to variables that are used
  34420. by the process callback, but obviously be careful not to keep it locked for
  34421. too long, because that could cause stuttering playback. If you need to do something
  34422. that'll take a long time and need the processing to stop while it happens, use the
  34423. suspendProcessing() method instead.
  34424. @see suspendProcessing
  34425. */
  34426. const CriticalSection& getCallbackLock() const noexcept { return callbackLock; }
  34427. /** Enables and disables the processing callback.
  34428. If you need to do something time-consuming on a thread and would like to make sure
  34429. the audio processing callback doesn't happen until you've finished, use this
  34430. to disable the callback and re-enable it again afterwards.
  34431. E.g.
  34432. @code
  34433. void loadNewPatch()
  34434. {
  34435. suspendProcessing (true);
  34436. ..do something that takes ages..
  34437. suspendProcessing (false);
  34438. }
  34439. @endcode
  34440. If the host tries to make an audio callback while processing is suspended, the
  34441. filter will return an empty buffer, but won't block the audio thread like it would
  34442. do if you use the getCallbackLock() critical section to synchronise access.
  34443. If you're going to use this, your processBlock() method must call isSuspended() and
  34444. check whether it's suspended or not. If it is, then it should skip doing any real
  34445. processing, either emitting silence or passing the input through unchanged.
  34446. @see getCallbackLock
  34447. */
  34448. void suspendProcessing (bool shouldBeSuspended);
  34449. /** Returns true if processing is currently suspended.
  34450. @see suspendProcessing
  34451. */
  34452. bool isSuspended() const noexcept { return suspended; }
  34453. /** A plugin can override this to be told when it should reset any playing voices.
  34454. The default implementation does nothing, but a host may call this to tell the
  34455. plugin that it should stop any tails or sounds that have been left running.
  34456. */
  34457. virtual void reset();
  34458. /** Returns true if the processor is being run in an offline mode for rendering.
  34459. If the processor is being run live on realtime signals, this returns false.
  34460. If the mode is unknown, this will assume it's realtime and return false.
  34461. This value may be unreliable until the prepareToPlay() method has been called,
  34462. and could change each time prepareToPlay() is called.
  34463. @see setNonRealtime()
  34464. */
  34465. bool isNonRealtime() const noexcept { return nonRealtime; }
  34466. /** Called by the host to tell this processor whether it's being used in a non-realime
  34467. capacity for offline rendering or bouncing.
  34468. Whatever value is passed-in will be
  34469. */
  34470. void setNonRealtime (bool isNonRealtime) noexcept;
  34471. /** Creates the filter's UI.
  34472. This can return 0 if you want a UI-less filter, in which case the host may create
  34473. a generic UI that lets the user twiddle the parameters directly.
  34474. If you do want to pass back a component, the component should be created and set to
  34475. the correct size before returning it. If you implement this method, you must
  34476. also implement the hasEditor() method and make it return true.
  34477. Remember not to do anything silly like allowing your filter to keep a pointer to
  34478. the component that gets created - it could be deleted later without any warning, which
  34479. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  34480. The correct way to handle the connection between an editor component and its
  34481. filter is to use something like a ChangeBroadcaster so that the editor can
  34482. register itself as a listener, and be told when a change occurs. This lets them
  34483. safely unregister themselves when they are deleted.
  34484. Here are a few things to bear in mind when writing an editor:
  34485. - Initially there won't be an editor, until the user opens one, or they might
  34486. not open one at all. Your filter mustn't rely on it being there.
  34487. - An editor object may be deleted and a replacement one created again at any time.
  34488. - It's safe to assume that an editor will be deleted before its filter.
  34489. @see hasEditor
  34490. */
  34491. virtual AudioProcessorEditor* createEditor() = 0;
  34492. /** Your filter must override this and return true if it can create an editor component.
  34493. @see createEditor
  34494. */
  34495. virtual bool hasEditor() const = 0;
  34496. /** Returns the active editor, if there is one.
  34497. Bear in mind this can return 0, even if an editor has previously been
  34498. opened.
  34499. */
  34500. AudioProcessorEditor* getActiveEditor() const noexcept { return activeEditor; }
  34501. /** Returns the active editor, or if there isn't one, it will create one.
  34502. This may call createEditor() internally to create the component.
  34503. */
  34504. AudioProcessorEditor* createEditorIfNeeded();
  34505. /** This must return the correct value immediately after the object has been
  34506. created, and mustn't change the number of parameters later.
  34507. */
  34508. virtual int getNumParameters() = 0;
  34509. /** Returns the name of a particular parameter. */
  34510. virtual const String getParameterName (int parameterIndex) = 0;
  34511. /** Called by the host to find out the value of one of the filter's parameters.
  34512. The host will expect the value returned to be between 0 and 1.0.
  34513. This could be called quite frequently, so try to make your code efficient.
  34514. It's also likely to be called by non-UI threads, so the code in here should
  34515. be thread-aware.
  34516. */
  34517. virtual float getParameter (int parameterIndex) = 0;
  34518. /** Returns the value of a parameter as a text string. */
  34519. virtual const String getParameterText (int parameterIndex) = 0;
  34520. /** The host will call this method to change the value of one of the filter's parameters.
  34521. The host may call this at any time, including during the audio processing
  34522. callback, so the filter has to process this very fast and avoid blocking.
  34523. If you want to set the value of a parameter internally, e.g. from your
  34524. editor component, then don't call this directly - instead, use the
  34525. setParameterNotifyingHost() method, which will also send a message to
  34526. the host telling it about the change. If the message isn't sent, the host
  34527. won't be able to automate your parameters properly.
  34528. The value passed will be between 0 and 1.0.
  34529. */
  34530. virtual void setParameter (int parameterIndex,
  34531. float newValue) = 0;
  34532. /** Your filter can call this when it needs to change one of its parameters.
  34533. This could happen when the editor or some other internal operation changes
  34534. a parameter. This method will call the setParameter() method to change the
  34535. value, and will then send a message to the host telling it about the change.
  34536. Note that to make sure the host correctly handles automation, you should call
  34537. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  34538. tell the host when the user has started and stopped changing the parameter.
  34539. */
  34540. void setParameterNotifyingHost (int parameterIndex,
  34541. float newValue);
  34542. /** Returns true if the host can automate this parameter.
  34543. By default, this returns true for all parameters.
  34544. */
  34545. virtual bool isParameterAutomatable (int parameterIndex) const;
  34546. /** Should return true if this parameter is a "meta" parameter.
  34547. A meta-parameter is a parameter that changes other params. It is used
  34548. by some hosts (e.g. AudioUnit hosts).
  34549. By default this returns false.
  34550. */
  34551. virtual bool isMetaParameter (int parameterIndex) const;
  34552. /** Sends a signal to the host to tell it that the user is about to start changing this
  34553. parameter.
  34554. This allows the host to know when a parameter is actively being held by the user, and
  34555. it may use this information to help it record automation.
  34556. If you call this, it must be matched by a later call to endParameterChangeGesture().
  34557. */
  34558. void beginParameterChangeGesture (int parameterIndex);
  34559. /** Tells the host that the user has finished changing this parameter.
  34560. This allows the host to know when a parameter is actively being held by the user, and
  34561. it may use this information to help it record automation.
  34562. A call to this method must follow a call to beginParameterChangeGesture().
  34563. */
  34564. void endParameterChangeGesture (int parameterIndex);
  34565. /** The filter can call this when something (apart from a parameter value) has changed.
  34566. It sends a hint to the host that something like the program, number of parameters,
  34567. etc, has changed, and that it should update itself.
  34568. */
  34569. void updateHostDisplay();
  34570. /** Returns the number of preset programs the filter supports.
  34571. The value returned must be valid as soon as this object is created, and
  34572. must not change over its lifetime.
  34573. This value shouldn't be less than 1.
  34574. */
  34575. virtual int getNumPrograms() = 0;
  34576. /** Returns the number of the currently active program.
  34577. */
  34578. virtual int getCurrentProgram() = 0;
  34579. /** Called by the host to change the current program.
  34580. */
  34581. virtual void setCurrentProgram (int index) = 0;
  34582. /** Must return the name of a given program. */
  34583. virtual const String getProgramName (int index) = 0;
  34584. /** Called by the host to rename a program.
  34585. */
  34586. virtual void changeProgramName (int index, const String& newName) = 0;
  34587. /** The host will call this method when it wants to save the filter's internal state.
  34588. This must copy any info about the filter's state into the block of memory provided,
  34589. so that the host can store this and later restore it using setStateInformation().
  34590. Note that there's also a getCurrentProgramStateInformation() method, which only
  34591. stores the current program, not the state of the entire filter.
  34592. See also the helper function copyXmlToBinary() for storing settings as XML.
  34593. @see getCurrentProgramStateInformation
  34594. */
  34595. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  34596. /** The host will call this method if it wants to save the state of just the filter's
  34597. current program.
  34598. Unlike getStateInformation, this should only return the current program's state.
  34599. Not all hosts support this, and if you don't implement it, the base class
  34600. method just calls getStateInformation() instead. If you do implement it, be
  34601. sure to also implement getCurrentProgramStateInformation.
  34602. @see getStateInformation, setCurrentProgramStateInformation
  34603. */
  34604. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  34605. /** This must restore the filter's state from a block of data previously created
  34606. using getStateInformation().
  34607. Note that there's also a setCurrentProgramStateInformation() method, which tries
  34608. to restore just the current program, not the state of the entire filter.
  34609. See also the helper function getXmlFromBinary() for loading settings as XML.
  34610. @see setCurrentProgramStateInformation
  34611. */
  34612. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  34613. /** The host will call this method if it wants to restore the state of just the filter's
  34614. current program.
  34615. Not all hosts support this, and if you don't implement it, the base class
  34616. method just calls setStateInformation() instead. If you do implement it, be
  34617. sure to also implement getCurrentProgramStateInformation.
  34618. @see setStateInformation, getCurrentProgramStateInformation
  34619. */
  34620. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  34621. /** Adds a listener that will be called when an aspect of this processor changes. */
  34622. void addListener (AudioProcessorListener* newListener);
  34623. /** Removes a previously added listener. */
  34624. void removeListener (AudioProcessorListener* listenerToRemove);
  34625. /** Tells the processor to use this playhead object.
  34626. The processor will not take ownership of the object, so the caller must delete it when
  34627. it is no longer being used.
  34628. */
  34629. void setPlayHead (AudioPlayHead* newPlayHead) noexcept;
  34630. /** Not for public use - this is called before deleting an editor component. */
  34631. void editorBeingDeleted (AudioProcessorEditor* editor) noexcept;
  34632. /** Not for public use - this is called to initialise the processor before playing. */
  34633. void setPlayConfigDetails (int numIns, int numOuts,
  34634. double sampleRate,
  34635. int blockSize) noexcept;
  34636. protected:
  34637. /** Helper function that just converts an xml element into a binary blob.
  34638. Use this in your filter's getStateInformation() method if you want to
  34639. store its state as xml.
  34640. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  34641. from a binary blob.
  34642. */
  34643. static void copyXmlToBinary (const XmlElement& xml,
  34644. JUCE_NAMESPACE::MemoryBlock& destData);
  34645. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  34646. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  34647. an XmlElement object that the caller must delete when no longer needed.
  34648. */
  34649. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  34650. /** @internal */
  34651. AudioPlayHead* playHead;
  34652. /** @internal */
  34653. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  34654. private:
  34655. Array <AudioProcessorListener*> listeners;
  34656. Component::SafePointer<AudioProcessorEditor> activeEditor;
  34657. double sampleRate;
  34658. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  34659. bool suspended, nonRealtime;
  34660. CriticalSection callbackLock, listenerLock;
  34661. #if JUCE_DEBUG
  34662. BigInteger changingParams;
  34663. #endif
  34664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  34665. };
  34666. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34667. /*** End of inlined file: juce_AudioProcessor.h ***/
  34668. /*** Start of inlined file: juce_PluginDescription.h ***/
  34669. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34670. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34671. /**
  34672. A small class to represent some facts about a particular type of plugin.
  34673. This class is for storing and managing the details about a plugin without
  34674. actually having to load an instance of it.
  34675. A KnownPluginList contains a list of PluginDescription objects.
  34676. @see KnownPluginList
  34677. */
  34678. class JUCE_API PluginDescription
  34679. {
  34680. public:
  34681. PluginDescription();
  34682. PluginDescription (const PluginDescription& other);
  34683. PluginDescription& operator= (const PluginDescription& other);
  34684. ~PluginDescription();
  34685. /** The name of the plugin. */
  34686. String name;
  34687. /** A more descriptive name for the plugin.
  34688. This may be the same as the 'name' field, but some plugins may provide an
  34689. alternative name.
  34690. */
  34691. String descriptiveName;
  34692. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  34693. */
  34694. String pluginFormatName;
  34695. /** A category, such as "Dynamics", "Reverbs", etc.
  34696. */
  34697. String category;
  34698. /** The manufacturer. */
  34699. String manufacturerName;
  34700. /** The version. This string doesn't have any particular format. */
  34701. String version;
  34702. /** Either the file containing the plugin module, or some other unique way
  34703. of identifying it.
  34704. E.g. for an AU, this would be an ID string that the component manager
  34705. could use to retrieve the plugin. For a VST, it's the file path.
  34706. */
  34707. String fileOrIdentifier;
  34708. /** The last time the plugin file was changed.
  34709. This is handy when scanning for new or changed plugins.
  34710. */
  34711. Time lastFileModTime;
  34712. /** A unique ID for the plugin.
  34713. Note that this might not be unique between formats, e.g. a VST and some
  34714. other format might actually have the same id.
  34715. @see createIdentifierString
  34716. */
  34717. int uid;
  34718. /** True if the plugin identifies itself as a synthesiser. */
  34719. bool isInstrument;
  34720. /** The number of inputs. */
  34721. int numInputChannels;
  34722. /** The number of outputs. */
  34723. int numOutputChannels;
  34724. /** Returns true if the two descriptions refer the the same plugin.
  34725. This isn't quite as simple as them just having the same file (because of
  34726. shell plugins).
  34727. */
  34728. bool isDuplicateOf (const PluginDescription& other) const;
  34729. /** Returns a string that can be saved and used to uniquely identify the
  34730. plugin again.
  34731. This contains less info than the XML encoding, and is independent of the
  34732. plugin's file location, so can be used to store a plugin ID for use
  34733. across different machines.
  34734. */
  34735. const String createIdentifierString() const;
  34736. /** Creates an XML object containing these details.
  34737. @see loadFromXml
  34738. */
  34739. XmlElement* createXml() const;
  34740. /** Reloads the info in this structure from an XML record that was previously
  34741. saved with createXML().
  34742. Returns true if the XML was a valid plugin description.
  34743. */
  34744. bool loadFromXml (const XmlElement& xml);
  34745. private:
  34746. JUCE_LEAK_DETECTOR (PluginDescription);
  34747. };
  34748. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34749. /*** End of inlined file: juce_PluginDescription.h ***/
  34750. /**
  34751. Base class for an active instance of a plugin.
  34752. This derives from the AudioProcessor class, and adds some extra functionality
  34753. that helps when wrapping dynamically loaded plugins.
  34754. @see AudioProcessor, AudioPluginFormat
  34755. */
  34756. class JUCE_API AudioPluginInstance : public AudioProcessor
  34757. {
  34758. public:
  34759. /** Destructor.
  34760. Make sure that you delete any UI components that belong to this plugin before
  34761. deleting the plugin.
  34762. */
  34763. virtual ~AudioPluginInstance();
  34764. /** Fills-in the appropriate parts of this plugin description object.
  34765. */
  34766. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  34767. /** Returns a pointer to some kind of platform-specific data about the plugin.
  34768. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  34769. cast to an AudioUnit handle.
  34770. */
  34771. virtual void* getPlatformSpecificData();
  34772. protected:
  34773. AudioPluginInstance();
  34774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  34775. };
  34776. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34777. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  34778. class PluginDescription;
  34779. /**
  34780. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  34781. Use the static getNumFormats() and getFormat() calls to find the types
  34782. of format that are available.
  34783. */
  34784. class JUCE_API AudioPluginFormat
  34785. {
  34786. public:
  34787. /** Destructor. */
  34788. virtual ~AudioPluginFormat();
  34789. /** Returns the format name.
  34790. E.g. "VST", "AudioUnit", etc.
  34791. */
  34792. virtual const String getName() const = 0;
  34793. /** This tries to create descriptions for all the plugin types available in
  34794. a binary module file.
  34795. The file will be some kind of DLL or bundle.
  34796. Normally there will only be one type returned, but some plugins
  34797. (e.g. VST shells) can use a single DLL to create a set of different plugin
  34798. subtypes, so in that case, each subtype is returned as a separate object.
  34799. */
  34800. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  34801. const String& fileOrIdentifier) = 0;
  34802. /** Tries to recreate a type from a previously generated PluginDescription.
  34803. @see PluginDescription::createInstance
  34804. */
  34805. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  34806. /** Should do a quick check to see if this file or directory might be a plugin of
  34807. this format.
  34808. This is for searching for potential files, so it shouldn't actually try to
  34809. load the plugin or do anything time-consuming.
  34810. */
  34811. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  34812. /** Returns a readable version of the name of the plugin that this identifier refers to.
  34813. */
  34814. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  34815. /** Checks whether this plugin could possibly be loaded.
  34816. It doesn't actually need to load it, just to check whether the file or component
  34817. still exists.
  34818. */
  34819. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  34820. /** Searches a suggested set of directories for any plugins in this format.
  34821. The path might be ignored, e.g. by AUs, which are found by the OS rather
  34822. than manually.
  34823. */
  34824. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  34825. bool recursive) = 0;
  34826. /** Returns the typical places to look for this kind of plugin.
  34827. Note that if this returns no paths, it means that the format can't be scanned-for
  34828. (i.e. it's an internal format that doesn't live in files)
  34829. */
  34830. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  34831. protected:
  34832. AudioPluginFormat() noexcept;
  34833. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  34834. };
  34835. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34836. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  34837. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  34838. /**
  34839. Implements a plugin format manager for AudioUnits.
  34840. */
  34841. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  34842. {
  34843. public:
  34844. AudioUnitPluginFormat();
  34845. ~AudioUnitPluginFormat();
  34846. const String getName() const { return "AudioUnit"; }
  34847. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34848. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34849. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34850. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34851. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34852. bool doesPluginStillExist (const PluginDescription& desc);
  34853. const FileSearchPath getDefaultLocationsToSearch();
  34854. private:
  34855. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  34856. };
  34857. #endif
  34858. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34859. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  34860. #endif
  34861. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34862. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  34863. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34864. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34865. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  34866. // Sorry, this file is just a placeholder at the moment!...
  34867. /**
  34868. Implements a plugin format manager for DirectX plugins.
  34869. */
  34870. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  34871. {
  34872. public:
  34873. DirectXPluginFormat();
  34874. ~DirectXPluginFormat();
  34875. const String getName() const { return "DirectX"; }
  34876. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34877. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34878. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34879. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34880. const FileSearchPath getDefaultLocationsToSearch();
  34881. private:
  34882. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  34883. };
  34884. #endif
  34885. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34886. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  34887. #endif
  34888. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34889. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  34890. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34891. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34892. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  34893. // Sorry, this file is just a placeholder at the moment!...
  34894. /**
  34895. Implements a plugin format manager for DirectX plugins.
  34896. */
  34897. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  34898. {
  34899. public:
  34900. LADSPAPluginFormat();
  34901. ~LADSPAPluginFormat();
  34902. const String getName() const { return "LADSPA"; }
  34903. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34904. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34905. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34906. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34907. const FileSearchPath getDefaultLocationsToSearch();
  34908. private:
  34909. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  34910. };
  34911. #endif
  34912. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34913. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  34914. #endif
  34915. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34916. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  34917. #ifdef __aeffect__
  34918. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34919. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34920. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  34921. events to the list.
  34922. This is used by both the VST hosting code and the plugin wrapper.
  34923. */
  34924. class VSTMidiEventList
  34925. {
  34926. public:
  34927. VSTMidiEventList()
  34928. : numEventsUsed (0), numEventsAllocated (0)
  34929. {
  34930. }
  34931. ~VSTMidiEventList()
  34932. {
  34933. freeEvents();
  34934. }
  34935. void clear()
  34936. {
  34937. numEventsUsed = 0;
  34938. if (events != nullptr)
  34939. events->numEvents = 0;
  34940. }
  34941. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  34942. {
  34943. ensureSize (numEventsUsed + 1);
  34944. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  34945. events->numEvents = ++numEventsUsed;
  34946. if (numBytes <= 4)
  34947. {
  34948. if (e->type == kVstSysExType)
  34949. {
  34950. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34951. e->type = kVstMidiType;
  34952. e->byteSize = sizeof (VstMidiEvent);
  34953. e->noteLength = 0;
  34954. e->noteOffset = 0;
  34955. e->detune = 0;
  34956. e->noteOffVelocity = 0;
  34957. }
  34958. e->deltaFrames = frameOffset;
  34959. memcpy (e->midiData, midiData, numBytes);
  34960. }
  34961. else
  34962. {
  34963. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  34964. if (se->type == kVstSysExType)
  34965. delete[] se->sysexDump;
  34966. se->sysexDump = new char [numBytes];
  34967. memcpy (se->sysexDump, midiData, numBytes);
  34968. se->type = kVstSysExType;
  34969. se->byteSize = sizeof (VstMidiSysexEvent);
  34970. se->deltaFrames = frameOffset;
  34971. se->flags = 0;
  34972. se->dumpBytes = numBytes;
  34973. se->resvd1 = 0;
  34974. se->resvd2 = 0;
  34975. }
  34976. }
  34977. // Handy method to pull the events out of an event buffer supplied by the host
  34978. // or plugin.
  34979. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  34980. {
  34981. for (int i = 0; i < events->numEvents; ++i)
  34982. {
  34983. const VstEvent* const e = events->events[i];
  34984. if (e != nullptr)
  34985. {
  34986. if (e->type == kVstMidiType)
  34987. {
  34988. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  34989. 4, e->deltaFrames);
  34990. }
  34991. else if (e->type == kVstSysExType)
  34992. {
  34993. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  34994. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  34995. e->deltaFrames);
  34996. }
  34997. }
  34998. }
  34999. }
  35000. void ensureSize (int numEventsNeeded)
  35001. {
  35002. if (numEventsNeeded > numEventsAllocated)
  35003. {
  35004. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  35005. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  35006. if (events == nullptr)
  35007. events.calloc (size, 1);
  35008. else
  35009. events.realloc (size, 1);
  35010. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  35011. {
  35012. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  35013. (int) sizeof (VstMidiSysexEvent)));
  35014. e->type = kVstMidiType;
  35015. e->byteSize = sizeof (VstMidiEvent);
  35016. events->events[i] = (VstEvent*) e;
  35017. }
  35018. numEventsAllocated = numEventsNeeded;
  35019. }
  35020. }
  35021. void freeEvents()
  35022. {
  35023. if (events != nullptr)
  35024. {
  35025. for (int i = numEventsAllocated; --i >= 0;)
  35026. {
  35027. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  35028. if (e->type == kVstSysExType)
  35029. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  35030. juce_free (e);
  35031. }
  35032. events.free();
  35033. numEventsUsed = 0;
  35034. numEventsAllocated = 0;
  35035. }
  35036. }
  35037. HeapBlock <VstEvents> events;
  35038. private:
  35039. int numEventsUsed, numEventsAllocated;
  35040. };
  35041. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35042. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35043. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  35044. #endif
  35045. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35046. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  35047. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35048. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35049. #if JUCE_PLUGINHOST_VST
  35050. /**
  35051. Implements a plugin format manager for VSTs.
  35052. */
  35053. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  35054. {
  35055. public:
  35056. VSTPluginFormat();
  35057. ~VSTPluginFormat();
  35058. const String getName() const { return "VST"; }
  35059. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  35060. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  35061. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  35062. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  35063. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  35064. bool doesPluginStillExist (const PluginDescription& desc);
  35065. const FileSearchPath getDefaultLocationsToSearch();
  35066. private:
  35067. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  35068. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  35069. };
  35070. #endif
  35071. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35072. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  35073. #endif
  35074. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  35075. #endif
  35076. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35077. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  35078. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35079. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35080. /**
  35081. This maintains a list of known AudioPluginFormats.
  35082. @see AudioPluginFormat
  35083. */
  35084. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  35085. {
  35086. public:
  35087. AudioPluginFormatManager();
  35088. /** Destructor. */
  35089. ~AudioPluginFormatManager();
  35090. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  35091. /** Adds any formats that it knows about, e.g. VST.
  35092. */
  35093. void addDefaultFormats();
  35094. /** Returns the number of types of format that are available.
  35095. Use getFormat() to get one of them.
  35096. */
  35097. int getNumFormats();
  35098. /** Returns one of the available formats.
  35099. @see getNumFormats
  35100. */
  35101. AudioPluginFormat* getFormat (int index);
  35102. /** Adds a format to the list.
  35103. The object passed in will be owned and deleted by the manager.
  35104. */
  35105. void addFormat (AudioPluginFormat* format);
  35106. /** Tries to load the type for this description, by trying all the formats
  35107. that this manager knows about.
  35108. The caller is responsible for deleting the object that is returned.
  35109. If it can't load the plugin, it returns 0 and leaves a message in the
  35110. errorMessage string.
  35111. */
  35112. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  35113. String& errorMessage) const;
  35114. /** Checks that the file or component for this plugin actually still exists.
  35115. (This won't try to load the plugin)
  35116. */
  35117. bool doesPluginStillExist (const PluginDescription& description) const;
  35118. private:
  35119. OwnedArray <AudioPluginFormat> formats;
  35120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  35121. };
  35122. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35123. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  35124. #endif
  35125. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  35126. #endif
  35127. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35128. /*** Start of inlined file: juce_KnownPluginList.h ***/
  35129. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35130. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35131. /**
  35132. Manages a list of plugin types.
  35133. This can be easily edited, saved and loaded, and used to create instances of
  35134. the plugin types in it.
  35135. @see PluginListComponent
  35136. */
  35137. class JUCE_API KnownPluginList : public ChangeBroadcaster
  35138. {
  35139. public:
  35140. /** Creates an empty list.
  35141. */
  35142. KnownPluginList();
  35143. /** Destructor. */
  35144. ~KnownPluginList();
  35145. /** Clears the list. */
  35146. void clear();
  35147. /** Returns the number of types currently in the list.
  35148. @see getType
  35149. */
  35150. int getNumTypes() const noexcept { return types.size(); }
  35151. /** Returns one of the types.
  35152. @see getNumTypes
  35153. */
  35154. PluginDescription* getType (int index) const noexcept { return types [index]; }
  35155. /** Looks for a type in the list which comes from this file.
  35156. */
  35157. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  35158. /** Looks for a type in the list which matches a plugin type ID.
  35159. The identifierString parameter must have been created by
  35160. PluginDescription::createIdentifierString().
  35161. */
  35162. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  35163. /** Adds a type manually from its description. */
  35164. bool addType (const PluginDescription& type);
  35165. /** Removes a type. */
  35166. void removeType (int index);
  35167. /** Looks for all types that can be loaded from a given file, and adds them
  35168. to the list.
  35169. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  35170. re-tested if it's not already in the list, or if the file's modification
  35171. time has changed since the list was created. If dontRescanIfAlreadyInList is
  35172. false, the file will always be reloaded and tested.
  35173. Returns true if any new types were added, and all the types found in this
  35174. file (even if it was already known and hasn't been re-scanned) get returned
  35175. in the array.
  35176. */
  35177. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  35178. bool dontRescanIfAlreadyInList,
  35179. OwnedArray <PluginDescription>& typesFound,
  35180. AudioPluginFormat& formatToUse);
  35181. /** Returns true if the specified file is already known about and if it
  35182. hasn't been modified since our entry was created.
  35183. */
  35184. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  35185. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  35186. If any types are found in the files, their descriptions are returned in the array.
  35187. */
  35188. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  35189. OwnedArray <PluginDescription>& typesFound);
  35190. /** Sort methods used to change the order of the plugins in the list.
  35191. */
  35192. enum SortMethod
  35193. {
  35194. defaultOrder = 0,
  35195. sortAlphabetically,
  35196. sortByCategory,
  35197. sortByManufacturer,
  35198. sortByFileSystemLocation
  35199. };
  35200. /** Adds all the plugin types to a popup menu so that the user can select one.
  35201. Depending on the sort method, it may add sub-menus for categories,
  35202. manufacturers, etc.
  35203. Use getIndexChosenByMenu() to find out the type that was chosen.
  35204. */
  35205. void addToMenu (PopupMenu& menu,
  35206. const SortMethod sortMethod) const;
  35207. /** Converts a menu item index that has been chosen into its index in this list.
  35208. Returns -1 if it's not an ID that was used.
  35209. @see addToMenu
  35210. */
  35211. int getIndexChosenByMenu (int menuResultCode) const;
  35212. /** Sorts the list. */
  35213. void sort (const SortMethod method);
  35214. /** Creates some XML that can be used to store the state of this list.
  35215. */
  35216. XmlElement* createXml() const;
  35217. /** Recreates the state of this list from its stored XML format.
  35218. */
  35219. void recreateFromXml (const XmlElement& xml);
  35220. private:
  35221. OwnedArray <PluginDescription> types;
  35222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  35223. };
  35224. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35225. /*** End of inlined file: juce_KnownPluginList.h ***/
  35226. #endif
  35227. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  35228. #endif
  35229. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35230. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  35231. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35232. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35233. /**
  35234. Scans a directory for plugins, and adds them to a KnownPluginList.
  35235. To use one of these, create it and call scanNextFile() repeatedly, until
  35236. it returns false.
  35237. */
  35238. class JUCE_API PluginDirectoryScanner
  35239. {
  35240. public:
  35241. /**
  35242. Creates a scanner.
  35243. @param listToAddResultsTo this will get the new types added to it.
  35244. @param formatToLookFor this is the type of format that you want to look for
  35245. @param directoriesToSearch the path to search
  35246. @param searchRecursively true to search recursively
  35247. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  35248. be used as a file to store the names of any plugins
  35249. that crash during initialisation. If there are
  35250. any plugins listed in it, then these will always
  35251. be scanned after all other possible files have
  35252. been tried - in this way, even if there's a few
  35253. dodgy plugins in your path, then a couple of rescans
  35254. will still manage to find all the proper plugins.
  35255. It's probably best to choose a file in the user's
  35256. application data directory (alongside your app's
  35257. settings file) for this. The file format it uses
  35258. is just a list of filenames of the modules that
  35259. failed.
  35260. */
  35261. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  35262. AudioPluginFormat& formatToLookFor,
  35263. FileSearchPath directoriesToSearch,
  35264. bool searchRecursively,
  35265. const File& deadMansPedalFile);
  35266. /** Destructor. */
  35267. ~PluginDirectoryScanner();
  35268. /** Tries the next likely-looking file.
  35269. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  35270. re-tested if it's not already in the list, or if the file's modification
  35271. time has changed since the list was created. If dontRescanIfAlreadyInList is
  35272. false, the file will always be reloaded and tested.
  35273. Returns false when there are no more files to try.
  35274. */
  35275. bool scanNextFile (bool dontRescanIfAlreadyInList);
  35276. /** Skips over the next file without scanning it.
  35277. Returns false when there are no more files to try.
  35278. */
  35279. bool skipNextFile();
  35280. /** Returns the description of the plugin that will be scanned during the next
  35281. call to scanNextFile().
  35282. This is handy if you want to show the user which file is currently getting
  35283. scanned.
  35284. */
  35285. const String getNextPluginFileThatWillBeScanned() const;
  35286. /** Returns the estimated progress, between 0 and 1.
  35287. */
  35288. float getProgress() const { return progress; }
  35289. /** This returns a list of all the filenames of things that looked like being
  35290. a plugin file, but which failed to open for some reason.
  35291. */
  35292. const StringArray& getFailedFiles() const noexcept { return failedFiles; }
  35293. private:
  35294. KnownPluginList& list;
  35295. AudioPluginFormat& format;
  35296. StringArray filesOrIdentifiersToScan;
  35297. File deadMansPedalFile;
  35298. StringArray failedFiles;
  35299. int nextIndex;
  35300. float progress;
  35301. const StringArray getDeadMansPedalFile();
  35302. void setDeadMansPedalFile (const StringArray& newContents);
  35303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  35304. };
  35305. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35306. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  35307. #endif
  35308. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35309. /*** Start of inlined file: juce_PluginListComponent.h ***/
  35310. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35311. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35312. /*** Start of inlined file: juce_ListBox.h ***/
  35313. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  35314. #define __JUCE_LISTBOX_JUCEHEADER__
  35315. class ListViewport;
  35316. /**
  35317. A subclass of this is used to drive a ListBox.
  35318. @see ListBox
  35319. */
  35320. class JUCE_API ListBoxModel
  35321. {
  35322. public:
  35323. /** Destructor. */
  35324. virtual ~ListBoxModel() {}
  35325. /** This has to return the number of items in the list.
  35326. @see ListBox::getNumRows()
  35327. */
  35328. virtual int getNumRows() = 0;
  35329. /** This method must be implemented to draw a row of the list.
  35330. */
  35331. virtual void paintListBoxItem (int rowNumber,
  35332. Graphics& g,
  35333. int width, int height,
  35334. bool rowIsSelected) = 0;
  35335. /** This is used to create or update a custom component to go in a row of the list.
  35336. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  35337. and handle mouse clicks with listBoxItemClicked().
  35338. This method will be called whenever a custom component might need to be updated - e.g.
  35339. when the table is changed, or TableListBox::updateContent() is called.
  35340. If you don't need a custom component for the specified row, then return 0.
  35341. If you do want a custom component, and the existingComponentToUpdate is null, then
  35342. this method must create a suitable new component and return it.
  35343. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35344. by this method. In this case, the method must either update it to make sure it's correctly representing
  35345. the given row (which may be different from the one that the component was created for), or it can
  35346. delete this component and return a new one.
  35347. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  35348. */
  35349. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  35350. Component* existingComponentToUpdate);
  35351. /** This can be overridden to react to the user clicking on a row.
  35352. @see listBoxItemDoubleClicked
  35353. */
  35354. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  35355. /** This can be overridden to react to the user double-clicking on a row.
  35356. @see listBoxItemClicked
  35357. */
  35358. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  35359. /** This can be overridden to react to the user double-clicking on a part of the list where
  35360. there are no rows.
  35361. @see listBoxItemClicked
  35362. */
  35363. virtual void backgroundClicked();
  35364. /** Override this to be informed when rows are selected or deselected.
  35365. This will be called whenever a row is selected or deselected. If a range of
  35366. rows is selected all at once, this will just be called once for that event.
  35367. @param lastRowSelected the last row that the user selected. If no
  35368. rows are currently selected, this may be -1.
  35369. */
  35370. virtual void selectedRowsChanged (int lastRowSelected);
  35371. /** Override this to be informed when the delete key is pressed.
  35372. If no rows are selected when they press the key, this won't be called.
  35373. @param lastRowSelected the last row that had been selected when they pressed the
  35374. key - if there are multiple selections, this might not be
  35375. very useful
  35376. */
  35377. virtual void deleteKeyPressed (int lastRowSelected);
  35378. /** Override this to be informed when the return key is pressed.
  35379. If no rows are selected when they press the key, this won't be called.
  35380. @param lastRowSelected the last row that had been selected when they pressed the
  35381. key - if there are multiple selections, this might not be
  35382. very useful
  35383. */
  35384. virtual void returnKeyPressed (int lastRowSelected);
  35385. /** Override this to be informed when the list is scrolled.
  35386. This might be caused by the user moving the scrollbar, or by programmatic changes
  35387. to the list position.
  35388. */
  35389. virtual void listWasScrolled();
  35390. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  35391. If this returns a non-empty name then when the user drags a row, the listbox will
  35392. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35393. a drag-and-drop operation, using this string as the source description, with the listbox
  35394. itself as the source component.
  35395. @see DragAndDropContainer::startDragging
  35396. */
  35397. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35398. /** You can override this to provide tool tips for specific rows.
  35399. @see TooltipClient
  35400. */
  35401. virtual const String getTooltipForRow (int row);
  35402. };
  35403. /**
  35404. A list of items that can be scrolled vertically.
  35405. To create a list, you'll need to create a subclass of ListBoxModel. This can
  35406. either paint each row of the list and respond to events via callbacks, or for
  35407. more specialised tasks, it can supply a custom component to fill each row.
  35408. @see ComboBox, TableListBox
  35409. */
  35410. class JUCE_API ListBox : public Component,
  35411. public SettableTooltipClient
  35412. {
  35413. public:
  35414. /** Creates a ListBox.
  35415. The model pointer passed-in can be null, in which case you can set it later
  35416. with setModel().
  35417. */
  35418. ListBox (const String& componentName = String::empty,
  35419. ListBoxModel* model = 0);
  35420. /** Destructor. */
  35421. ~ListBox();
  35422. /** Changes the current data model to display. */
  35423. void setModel (ListBoxModel* newModel);
  35424. /** Returns the current list model. */
  35425. ListBoxModel* getModel() const noexcept { return model; }
  35426. /** Causes the list to refresh its content.
  35427. Call this when the number of rows in the list changes, or if you want it
  35428. to call refreshComponentForRow() on all the row components.
  35429. Be careful not to call it from a different thread, though, as it's not
  35430. thread-safe.
  35431. */
  35432. void updateContent();
  35433. /** Turns on multiple-selection of rows.
  35434. By default this is disabled.
  35435. When your row component gets clicked you'll need to call the
  35436. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  35437. clicked and to get it to do the appropriate selection based on whether
  35438. the ctrl/shift keys are held down.
  35439. */
  35440. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  35441. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  35442. This function is here primarily for the ComboBox class to use, but might be
  35443. useful for some other purpose too.
  35444. */
  35445. void setMouseMoveSelectsRows (bool shouldSelect);
  35446. /** Selects a row.
  35447. If the row is already selected, this won't do anything.
  35448. @param rowNumber the row to select
  35449. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  35450. the selected row is off-screen, it'll scroll to make
  35451. sure that row is on-screen
  35452. @param deselectOthersFirst if true and there are multiple selections, these will
  35453. first be deselected before this item is selected
  35454. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  35455. deselectAllRows, selectRangeOfRows
  35456. */
  35457. void selectRow (int rowNumber,
  35458. bool dontScrollToShowThisRow = false,
  35459. bool deselectOthersFirst = true);
  35460. /** Selects a set of rows.
  35461. This will add these rows to the current selection, so you might need to
  35462. clear the current selection first with deselectAllRows()
  35463. @param firstRow the first row to select (inclusive)
  35464. @param lastRow the last row to select (inclusive)
  35465. */
  35466. void selectRangeOfRows (int firstRow,
  35467. int lastRow);
  35468. /** Deselects a row.
  35469. If it's not currently selected, this will do nothing.
  35470. @see selectRow, deselectAllRows
  35471. */
  35472. void deselectRow (int rowNumber);
  35473. /** Deselects any currently selected rows.
  35474. @see deselectRow
  35475. */
  35476. void deselectAllRows();
  35477. /** Selects or deselects a row.
  35478. If the row's currently selected, this deselects it, and vice-versa.
  35479. */
  35480. void flipRowSelection (int rowNumber);
  35481. /** Returns a sparse set indicating the rows that are currently selected.
  35482. @see setSelectedRows
  35483. */
  35484. const SparseSet<int> getSelectedRows() const;
  35485. /** Sets the rows that should be selected, based on an explicit set of ranges.
  35486. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  35487. method will be called. If it's false, no notification will be sent to the model.
  35488. @see getSelectedRows
  35489. */
  35490. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35491. bool sendNotificationEventToModel = true);
  35492. /** Checks whether a row is selected.
  35493. */
  35494. bool isRowSelected (int rowNumber) const;
  35495. /** Returns the number of rows that are currently selected.
  35496. @see getSelectedRow, isRowSelected, getLastRowSelected
  35497. */
  35498. int getNumSelectedRows() const;
  35499. /** Returns the row number of a selected row.
  35500. This will return the row number of the Nth selected row. The row numbers returned will
  35501. be sorted in order from low to high.
  35502. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  35503. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  35504. selected
  35505. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  35506. */
  35507. int getSelectedRow (int index = 0) const;
  35508. /** Returns the last row that the user selected.
  35509. This isn't the same as the highest row number that is currently selected - if the user
  35510. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  35511. If nothing is selected, it will return -1.
  35512. */
  35513. int getLastRowSelected() const;
  35514. /** Multiply-selects rows based on the modifier keys.
  35515. If no modifier keys are down, this will select the given row and
  35516. deselect any others.
  35517. If the ctrl (or command on the Mac) key is down, it'll flip the
  35518. state of the selected row.
  35519. If the shift key is down, it'll select up to the given row from the
  35520. last row selected.
  35521. @see selectRow
  35522. */
  35523. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  35524. const ModifierKeys& modifiers,
  35525. bool isMouseUpEvent);
  35526. /** Scrolls the list to a particular position.
  35527. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  35528. 1.0 scrolls to the bottom.
  35529. If the total number of rows all fit onto the screen at once, then this
  35530. method won't do anything.
  35531. @see getVerticalPosition
  35532. */
  35533. void setVerticalPosition (double newProportion);
  35534. /** Returns the current vertical position as a proportion of the total.
  35535. This can be used in conjunction with setVerticalPosition() to save and restore
  35536. the list's position. It returns a value in the range 0 to 1.
  35537. @see setVerticalPosition
  35538. */
  35539. double getVerticalPosition() const;
  35540. /** Scrolls if necessary to make sure that a particular row is visible.
  35541. */
  35542. void scrollToEnsureRowIsOnscreen (int row);
  35543. /** Returns a pointer to the scrollbar.
  35544. (Unlikely to be useful for most people).
  35545. */
  35546. ScrollBar* getVerticalScrollBar() const noexcept;
  35547. /** Returns a pointer to the scrollbar.
  35548. (Unlikely to be useful for most people).
  35549. */
  35550. ScrollBar* getHorizontalScrollBar() const noexcept;
  35551. /** Finds the row index that contains a given x,y position.
  35552. The position is relative to the ListBox's top-left.
  35553. If no row exists at this position, the method will return -1.
  35554. @see getComponentForRowNumber
  35555. */
  35556. int getRowContainingPosition (int x, int y) const noexcept;
  35557. /** Finds a row index that would be the most suitable place to insert a new
  35558. item for a given position.
  35559. This is useful when the user is e.g. dragging and dropping onto the listbox,
  35560. because it lets you easily choose the best position to insert the item that
  35561. they drop, based on where they drop it.
  35562. If the position is out of range, this will return -1. If the position is
  35563. beyond the end of the list, it will return getNumRows() to indicate the end
  35564. of the list.
  35565. @see getComponentForRowNumber
  35566. */
  35567. int getInsertionIndexForPosition (int x, int y) const noexcept;
  35568. /** Returns the position of one of the rows, relative to the top-left of
  35569. the listbox.
  35570. This may be off-screen, and the range of the row number that is passed-in is
  35571. not checked to see if it's a valid row.
  35572. */
  35573. const Rectangle<int> getRowPosition (int rowNumber,
  35574. bool relativeToComponentTopLeft) const noexcept;
  35575. /** Finds the row component for a given row in the list.
  35576. The component returned will have been created using createRowComponent().
  35577. If the component for this row is off-screen or if the row is out-of-range,
  35578. this will return 0.
  35579. @see getRowContainingPosition
  35580. */
  35581. Component* getComponentForRowNumber (int rowNumber) const noexcept;
  35582. /** Returns the row number that the given component represents.
  35583. If the component isn't one of the list's rows, this will return -1.
  35584. */
  35585. int getRowNumberOfComponent (Component* rowComponent) const noexcept;
  35586. /** Returns the width of a row (which may be less than the width of this component
  35587. if there's a scrollbar).
  35588. */
  35589. int getVisibleRowWidth() const noexcept;
  35590. /** Sets the height of each row in the list.
  35591. The default height is 22 pixels.
  35592. @see getRowHeight
  35593. */
  35594. void setRowHeight (int newHeight);
  35595. /** Returns the height of a row in the list.
  35596. @see setRowHeight
  35597. */
  35598. int getRowHeight() const noexcept { return rowHeight; }
  35599. /** Returns the number of rows actually visible.
  35600. This is the number of whole rows which will fit on-screen, so the value might
  35601. be more than the actual number of rows in the list.
  35602. */
  35603. int getNumRowsOnScreen() const noexcept;
  35604. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35605. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35606. methods.
  35607. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35608. */
  35609. enum ColourIds
  35610. {
  35611. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35612. Make this transparent if you don't want the background to be filled. */
  35613. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35614. Make this transparent to not have an outline. */
  35615. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35616. };
  35617. /** Sets the thickness of a border that will be drawn around the box.
  35618. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35619. @see outlineColourId
  35620. */
  35621. void setOutlineThickness (int outlineThickness);
  35622. /** Returns the thickness of outline that will be drawn around the listbox.
  35623. @see setOutlineColour
  35624. */
  35625. int getOutlineThickness() const noexcept { return outlineThickness; }
  35626. /** Sets a component that the list should use as a header.
  35627. This will position the given component at the top of the list, maintaining the
  35628. height of the component passed-in, but rescaling it horizontally to match the
  35629. width of the items in the listbox.
  35630. The component will be deleted when setHeaderComponent() is called with a
  35631. different component, or when the listbox is deleted.
  35632. */
  35633. void setHeaderComponent (Component* newHeaderComponent);
  35634. /** Changes the width of the rows in the list.
  35635. This can be used to make the list's row components wider than the list itself - the
  35636. width of the rows will be either the width of the list or this value, whichever is
  35637. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35638. appear.
  35639. The default value for this is 0, which means that the rows will always
  35640. be the same width as the list.
  35641. */
  35642. void setMinimumContentWidth (int newMinimumWidth);
  35643. /** Returns the space currently available for the row items, taking into account
  35644. borders, scrollbars, etc.
  35645. */
  35646. int getVisibleContentWidth() const noexcept;
  35647. /** Repaints one of the rows.
  35648. This is a lightweight alternative to calling updateContent, and just causes a
  35649. repaint of the row's area.
  35650. */
  35651. void repaintRow (int rowNumber) noexcept;
  35652. /** This fairly obscure method creates an image that just shows the currently
  35653. selected row components.
  35654. It's a handy method for doing drag-and-drop, as it can be passed to the
  35655. DragAndDropContainer for use as the drag image.
  35656. Note that it will make the row components temporarily invisible, so if you're
  35657. using custom components this could affect them if they're sensitive to that
  35658. sort of thing.
  35659. @see Component::createComponentSnapshot
  35660. */
  35661. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35662. /** Returns the viewport that this ListBox uses.
  35663. You may need to use this to change parameters such as whether scrollbars
  35664. are shown, etc.
  35665. */
  35666. Viewport* getViewport() const noexcept;
  35667. /** @internal */
  35668. bool keyPressed (const KeyPress& key);
  35669. /** @internal */
  35670. bool keyStateChanged (bool isKeyDown);
  35671. /** @internal */
  35672. void paint (Graphics& g);
  35673. /** @internal */
  35674. void paintOverChildren (Graphics& g);
  35675. /** @internal */
  35676. void resized();
  35677. /** @internal */
  35678. void visibilityChanged();
  35679. /** @internal */
  35680. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35681. /** @internal */
  35682. void mouseMove (const MouseEvent&);
  35683. /** @internal */
  35684. void mouseExit (const MouseEvent&);
  35685. /** @internal */
  35686. void mouseUp (const MouseEvent&);
  35687. /** @internal */
  35688. void colourChanged();
  35689. /** @internal */
  35690. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  35691. private:
  35692. friend class ListViewport;
  35693. friend class TableListBox;
  35694. ListBoxModel* model;
  35695. ScopedPointer<ListViewport> viewport;
  35696. ScopedPointer<Component> headerComponent;
  35697. int totalItems, rowHeight, minimumRowWidth;
  35698. int outlineThickness;
  35699. int lastRowSelected;
  35700. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35701. SparseSet <int> selected;
  35702. void selectRowInternal (int rowNumber,
  35703. bool dontScrollToShowThisRow,
  35704. bool deselectOthersFirst,
  35705. bool isMouseClick);
  35706. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35707. };
  35708. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35709. /*** End of inlined file: juce_ListBox.h ***/
  35710. /*** Start of inlined file: juce_TextButton.h ***/
  35711. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35712. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35713. /**
  35714. A button that uses the standard lozenge-shaped background with a line of
  35715. text on it.
  35716. @see Button, DrawableButton
  35717. */
  35718. class JUCE_API TextButton : public Button
  35719. {
  35720. public:
  35721. /** Creates a TextButton.
  35722. @param buttonName the text to put in the button (the component's name is also
  35723. initially set to this string, but these can be changed later
  35724. using the setName() and setButtonText() methods)
  35725. @param toolTip an optional string to use as a toolip
  35726. @see Button
  35727. */
  35728. TextButton (const String& buttonName = String::empty,
  35729. const String& toolTip = String::empty);
  35730. /** Destructor. */
  35731. ~TextButton();
  35732. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35733. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35734. methods.
  35735. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35736. */
  35737. enum ColourIds
  35738. {
  35739. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35740. 'off'). The look-and-feel class might re-interpret this to add
  35741. effects, etc. */
  35742. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35743. 'on'). The look-and-feel class might re-interpret this to add
  35744. effects, etc. */
  35745. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35746. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35747. };
  35748. /** Resizes the button to fit neatly around its current text.
  35749. If newHeight is >= 0, the button's height will be changed to this
  35750. value. If it's less than zero, its height will be unaffected.
  35751. */
  35752. void changeWidthToFitText (int newHeight = -1);
  35753. /** This can be overridden to use different fonts than the default one.
  35754. Note that you'll need to set the font's size appropriately, too.
  35755. */
  35756. virtual const Font getFont();
  35757. protected:
  35758. /** @internal */
  35759. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35760. /** @internal */
  35761. void colourChanged();
  35762. private:
  35763. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35764. };
  35765. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35766. /*** End of inlined file: juce_TextButton.h ***/
  35767. /**
  35768. A component displaying a list of plugins, with options to scan for them,
  35769. add, remove and sort them.
  35770. */
  35771. class JUCE_API PluginListComponent : public Component,
  35772. public ListBoxModel,
  35773. public ChangeListener,
  35774. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35775. public Timer
  35776. {
  35777. public:
  35778. /**
  35779. Creates the list component.
  35780. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35781. The properties file, if supplied, is used to store the user's last search paths.
  35782. */
  35783. PluginListComponent (KnownPluginList& listToRepresent,
  35784. const File& deadMansPedalFile,
  35785. PropertiesFile* propertiesToUse);
  35786. /** Destructor. */
  35787. ~PluginListComponent();
  35788. /** @internal */
  35789. void resized();
  35790. /** @internal */
  35791. bool isInterestedInFileDrag (const StringArray& files);
  35792. /** @internal */
  35793. void filesDropped (const StringArray& files, int, int);
  35794. /** @internal */
  35795. int getNumRows();
  35796. /** @internal */
  35797. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35798. /** @internal */
  35799. void deleteKeyPressed (int lastRowSelected);
  35800. /** @internal */
  35801. void buttonClicked (Button* b);
  35802. /** @internal */
  35803. void changeListenerCallback (ChangeBroadcaster*);
  35804. /** @internal */
  35805. void timerCallback();
  35806. private:
  35807. KnownPluginList& list;
  35808. File deadMansPedalFile;
  35809. ListBox listBox;
  35810. TextButton optionsButton;
  35811. PropertiesFile* propertiesToUse;
  35812. int typeToScan;
  35813. void scanFor (AudioPluginFormat* format);
  35814. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35815. void optionsMenuCallback (int result);
  35816. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35817. };
  35818. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35819. /*** End of inlined file: juce_PluginListComponent.h ***/
  35820. #endif
  35821. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35822. #endif
  35823. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35824. #endif
  35825. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35826. #endif
  35827. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35828. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35829. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35830. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35831. /**
  35832. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35833. Use one of these objects if you want to wire-up a set of AudioProcessors
  35834. and play back the result.
  35835. Processors can be added to the graph as "nodes" using addNode(), and once
  35836. added, you can connect any of their input or output channels to other
  35837. nodes using addConnection().
  35838. To play back a graph through an audio device, you might want to use an
  35839. AudioProcessorPlayer object.
  35840. */
  35841. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35842. public AsyncUpdater
  35843. {
  35844. public:
  35845. /** Creates an empty graph.
  35846. */
  35847. AudioProcessorGraph();
  35848. /** Destructor.
  35849. Any processor objects that have been added to the graph will also be deleted.
  35850. */
  35851. ~AudioProcessorGraph();
  35852. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35853. To create a node, call AudioProcessorGraph::addNode().
  35854. */
  35855. class JUCE_API Node : public ReferenceCountedObject
  35856. {
  35857. public:
  35858. /** The ID number assigned to this node.
  35859. This is assigned by the graph that owns it, and can't be changed.
  35860. */
  35861. const uint32 id;
  35862. /** The actual processor object that this node represents. */
  35863. AudioProcessor* getProcessor() const noexcept { return processor; }
  35864. /** A set of user-definable properties that are associated with this node.
  35865. This can be used to attach values to the node for whatever purpose seems
  35866. useful. For example, you might store an x and y position if your application
  35867. is displaying the nodes on-screen.
  35868. */
  35869. NamedValueSet properties;
  35870. /** A convenient typedef for referring to a pointer to a node object.
  35871. */
  35872. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35873. private:
  35874. friend class AudioProcessorGraph;
  35875. const ScopedPointer<AudioProcessor> processor;
  35876. bool isPrepared;
  35877. Node (uint32 id, AudioProcessor* processor);
  35878. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35879. void unprepare();
  35880. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35881. };
  35882. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35883. To create a connection, use AudioProcessorGraph::addConnection().
  35884. */
  35885. struct JUCE_API Connection
  35886. {
  35887. public:
  35888. /** The ID number of the node which is the input source for this connection.
  35889. @see AudioProcessorGraph::getNodeForId
  35890. */
  35891. uint32 sourceNodeId;
  35892. /** The index of the output channel of the source node from which this
  35893. connection takes its data.
  35894. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35895. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35896. index of an audio output channel in the source node.
  35897. */
  35898. int sourceChannelIndex;
  35899. /** The ID number of the node which is the destination for this connection.
  35900. @see AudioProcessorGraph::getNodeForId
  35901. */
  35902. uint32 destNodeId;
  35903. /** The index of the input channel of the destination node to which this
  35904. connection delivers its data.
  35905. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35906. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35907. index of an audio input channel in the destination node.
  35908. */
  35909. int destChannelIndex;
  35910. private:
  35911. JUCE_LEAK_DETECTOR (Connection);
  35912. };
  35913. /** Deletes all nodes and connections from this graph.
  35914. Any processor objects in the graph will be deleted.
  35915. */
  35916. void clear();
  35917. /** Returns the number of nodes in the graph. */
  35918. int getNumNodes() const { return nodes.size(); }
  35919. /** Returns a pointer to one of the nodes in the graph.
  35920. This will return 0 if the index is out of range.
  35921. @see getNodeForId
  35922. */
  35923. Node* getNode (const int index) const { return nodes [index]; }
  35924. /** Searches the graph for a node with the given ID number and returns it.
  35925. If no such node was found, this returns 0.
  35926. @see getNode
  35927. */
  35928. Node* getNodeForId (const uint32 nodeId) const;
  35929. /** Adds a node to the graph.
  35930. This creates a new node in the graph, for the specified processor. Once you have
  35931. added a processor to the graph, the graph owns it and will delete it later when
  35932. it is no longer needed.
  35933. The optional nodeId parameter lets you specify an ID to use for the node, but
  35934. if the value is already in use, this new node will overwrite the old one.
  35935. If this succeeds, it returns a pointer to the newly-created node.
  35936. */
  35937. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35938. /** Deletes a node within the graph which has the specified ID.
  35939. This will also delete any connections that are attached to this node.
  35940. */
  35941. bool removeNode (uint32 nodeId);
  35942. /** Returns the number of connections in the graph. */
  35943. int getNumConnections() const { return connections.size(); }
  35944. /** Returns a pointer to one of the connections in the graph. */
  35945. const Connection* getConnection (int index) const { return connections [index]; }
  35946. /** Searches for a connection between some specified channels.
  35947. If no such connection is found, this returns 0.
  35948. */
  35949. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35950. int sourceChannelIndex,
  35951. uint32 destNodeId,
  35952. int destChannelIndex) const;
  35953. /** Returns true if there is a connection between any of the channels of
  35954. two specified nodes.
  35955. */
  35956. bool isConnected (uint32 possibleSourceNodeId,
  35957. uint32 possibleDestNodeId) const;
  35958. /** Returns true if it would be legal to connect the specified points.
  35959. */
  35960. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35961. uint32 destNodeId, int destChannelIndex) const;
  35962. /** Attempts to connect two specified channels of two nodes.
  35963. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35964. to an audio one or other such nonsense), then it'll return false.
  35965. */
  35966. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35967. uint32 destNodeId, int destChannelIndex);
  35968. /** Deletes the connection with the specified index.
  35969. Returns true if a connection was actually deleted.
  35970. */
  35971. void removeConnection (int index);
  35972. /** Deletes any connection between two specified points.
  35973. Returns true if a connection was actually deleted.
  35974. */
  35975. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35976. uint32 destNodeId, int destChannelIndex);
  35977. /** Removes all connections from the specified node.
  35978. */
  35979. bool disconnectNode (uint32 nodeId);
  35980. /** Performs a sanity checks of all the connections.
  35981. This might be useful if some of the processors are doing things like changing
  35982. their channel counts, which could render some connections obsolete.
  35983. */
  35984. bool removeIllegalConnections();
  35985. /** A special number that represents the midi channel of a node.
  35986. This is used as a channel index value if you want to refer to the midi input
  35987. or output instead of an audio channel.
  35988. */
  35989. static const int midiChannelIndex;
  35990. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35991. in order to use the audio that comes into and out of the graph itself.
  35992. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35993. node in the graph which delivers the audio that is coming into the parent
  35994. graph. This allows you to stream the data to other nodes and process the
  35995. incoming audio.
  35996. Likewise, one of these in "output" mode can be sent data which it will add to
  35997. the sum of data being sent to the graph's output.
  35998. @see AudioProcessorGraph
  35999. */
  36000. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  36001. {
  36002. public:
  36003. /** Specifies the mode in which this processor will operate.
  36004. */
  36005. enum IODeviceType
  36006. {
  36007. audioInputNode, /**< In this mode, the processor has output channels
  36008. representing all the audio input channels that are
  36009. coming into its parent audio graph. */
  36010. audioOutputNode, /**< In this mode, the processor has input channels
  36011. representing all the audio output channels that are
  36012. going out of its parent audio graph. */
  36013. midiInputNode, /**< In this mode, the processor has a midi output which
  36014. delivers the same midi data that is arriving at its
  36015. parent graph. */
  36016. midiOutputNode /**< In this mode, the processor has a midi input and
  36017. any data sent to it will be passed out of the parent
  36018. graph. */
  36019. };
  36020. /** Returns the mode of this processor. */
  36021. IODeviceType getType() const { return type; }
  36022. /** Returns the parent graph to which this processor belongs, or 0 if it
  36023. hasn't yet been added to one. */
  36024. AudioProcessorGraph* getParentGraph() const { return graph; }
  36025. /** True if this is an audio or midi input. */
  36026. bool isInput() const;
  36027. /** True if this is an audio or midi output. */
  36028. bool isOutput() const;
  36029. AudioGraphIOProcessor (const IODeviceType type);
  36030. ~AudioGraphIOProcessor();
  36031. const String getName() const;
  36032. void fillInPluginDescription (PluginDescription& d) const;
  36033. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  36034. void releaseResources();
  36035. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  36036. const String getInputChannelName (int channelIndex) const;
  36037. const String getOutputChannelName (int channelIndex) const;
  36038. bool isInputChannelStereoPair (int index) const;
  36039. bool isOutputChannelStereoPair (int index) const;
  36040. bool acceptsMidi() const;
  36041. bool producesMidi() const;
  36042. bool hasEditor() const;
  36043. AudioProcessorEditor* createEditor();
  36044. int getNumParameters();
  36045. const String getParameterName (int);
  36046. float getParameter (int);
  36047. const String getParameterText (int);
  36048. void setParameter (int, float);
  36049. int getNumPrograms();
  36050. int getCurrentProgram();
  36051. void setCurrentProgram (int);
  36052. const String getProgramName (int);
  36053. void changeProgramName (int, const String&);
  36054. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  36055. void setStateInformation (const void* data, int sizeInBytes);
  36056. /** @internal */
  36057. void setParentGraph (AudioProcessorGraph* graph);
  36058. private:
  36059. const IODeviceType type;
  36060. AudioProcessorGraph* graph;
  36061. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  36062. };
  36063. // AudioProcessor methods:
  36064. const String getName() const;
  36065. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  36066. void releaseResources();
  36067. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  36068. const String getInputChannelName (int channelIndex) const;
  36069. const String getOutputChannelName (int channelIndex) const;
  36070. bool isInputChannelStereoPair (int index) const;
  36071. bool isOutputChannelStereoPair (int index) const;
  36072. bool acceptsMidi() const;
  36073. bool producesMidi() const;
  36074. bool hasEditor() const { return false; }
  36075. AudioProcessorEditor* createEditor() { return nullptr; }
  36076. int getNumParameters() { return 0; }
  36077. const String getParameterName (int) { return String::empty; }
  36078. float getParameter (int) { return 0; }
  36079. const String getParameterText (int) { return String::empty; }
  36080. void setParameter (int, float) { }
  36081. int getNumPrograms() { return 0; }
  36082. int getCurrentProgram() { return 0; }
  36083. void setCurrentProgram (int) { }
  36084. const String getProgramName (int) { return String::empty; }
  36085. void changeProgramName (int, const String&) { }
  36086. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  36087. void setStateInformation (const void* data, int sizeInBytes);
  36088. /** @internal */
  36089. void handleAsyncUpdate();
  36090. private:
  36091. ReferenceCountedArray <Node> nodes;
  36092. OwnedArray <Connection> connections;
  36093. int lastNodeId;
  36094. AudioSampleBuffer renderingBuffers;
  36095. OwnedArray <MidiBuffer> midiBuffers;
  36096. CriticalSection renderLock;
  36097. Array<void*> renderingOps;
  36098. friend class AudioGraphIOProcessor;
  36099. AudioSampleBuffer* currentAudioInputBuffer;
  36100. AudioSampleBuffer currentAudioOutputBuffer;
  36101. MidiBuffer* currentMidiInputBuffer;
  36102. MidiBuffer currentMidiOutputBuffer;
  36103. void clearRenderingSequence();
  36104. void buildRenderingSequence();
  36105. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  36106. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  36107. };
  36108. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  36109. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  36110. #endif
  36111. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  36112. #endif
  36113. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36114. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  36115. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36116. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36117. /**
  36118. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  36119. To use one of these, just make it the callback used by your AudioIODevice, and
  36120. give it a processor to use by calling setProcessor().
  36121. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  36122. input to send both streams through the processor.
  36123. @see AudioProcessor, AudioProcessorGraph
  36124. */
  36125. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  36126. public MidiInputCallback
  36127. {
  36128. public:
  36129. /**
  36130. */
  36131. AudioProcessorPlayer();
  36132. /** Destructor. */
  36133. virtual ~AudioProcessorPlayer();
  36134. /** Sets the processor that should be played.
  36135. The processor that is passed in will not be deleted or owned by this object.
  36136. To stop anything playing, pass in 0 to this method.
  36137. */
  36138. void setProcessor (AudioProcessor* processorToPlay);
  36139. /** Returns the current audio processor that is being played.
  36140. */
  36141. AudioProcessor* getCurrentProcessor() const { return processor; }
  36142. /** Returns a midi message collector that you can pass midi messages to if you
  36143. want them to be injected into the midi stream that is being sent to the
  36144. processor.
  36145. */
  36146. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  36147. /** @internal */
  36148. void audioDeviceIOCallback (const float** inputChannelData,
  36149. int totalNumInputChannels,
  36150. float** outputChannelData,
  36151. int totalNumOutputChannels,
  36152. int numSamples);
  36153. /** @internal */
  36154. void audioDeviceAboutToStart (AudioIODevice* device);
  36155. /** @internal */
  36156. void audioDeviceStopped();
  36157. /** @internal */
  36158. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  36159. private:
  36160. AudioProcessor* processor;
  36161. CriticalSection lock;
  36162. double sampleRate;
  36163. int blockSize;
  36164. bool isPrepared;
  36165. int numInputChans, numOutputChans;
  36166. float* channels [128];
  36167. AudioSampleBuffer tempBuffer;
  36168. MidiBuffer incomingMidi;
  36169. MidiMessageCollector messageCollector;
  36170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  36171. };
  36172. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36173. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  36174. #endif
  36175. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36176. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  36177. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36178. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36179. /*** Start of inlined file: juce_PropertyPanel.h ***/
  36180. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  36181. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  36182. /*** Start of inlined file: juce_PropertyComponent.h ***/
  36183. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36184. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36185. class EditableProperty;
  36186. /**
  36187. A base class for a component that goes in a PropertyPanel and displays one of
  36188. an item's properties.
  36189. Subclasses of this are used to display a property in various forms, e.g. a
  36190. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  36191. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  36192. A subclass must implement the refresh() method which will be called to tell the
  36193. component to update itself, and is also responsible for calling this it when the
  36194. item that it refers to is changed.
  36195. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  36196. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  36197. */
  36198. class JUCE_API PropertyComponent : public Component,
  36199. public SettableTooltipClient
  36200. {
  36201. public:
  36202. /** Creates a PropertyComponent.
  36203. @param propertyName the name is stored as this component's name, and is
  36204. used as the name displayed next to this component in
  36205. a property panel
  36206. @param preferredHeight the height that the component should be given - some
  36207. items may need to be larger than a normal row height.
  36208. This value can also be set if a subclass changes the
  36209. preferredHeight member variable.
  36210. */
  36211. PropertyComponent (const String& propertyName,
  36212. int preferredHeight = 25);
  36213. /** Destructor. */
  36214. ~PropertyComponent();
  36215. /** Returns this item's preferred height.
  36216. This value is specified either in the constructor or by a subclass changing the
  36217. preferredHeight member variable.
  36218. */
  36219. int getPreferredHeight() const noexcept { return preferredHeight; }
  36220. void setPreferredHeight (int newHeight) noexcept { preferredHeight = newHeight; }
  36221. /** Updates the property component if the item it refers to has changed.
  36222. A subclass must implement this method, and other objects may call it to
  36223. force it to refresh itself.
  36224. The subclass should be economical in the amount of work is done, so for
  36225. example it should check whether it really needs to do a repaint rather than
  36226. just doing one every time this method is called, as it may be called when
  36227. the value being displayed hasn't actually changed.
  36228. */
  36229. virtual void refresh() = 0;
  36230. /** The default paint method fills the background and draws a label for the
  36231. item's name.
  36232. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  36233. */
  36234. void paint (Graphics& g);
  36235. /** The default resize method positions any child component to the right of this
  36236. one, based on the look and feel's default label size.
  36237. */
  36238. void resized();
  36239. /** By default, this just repaints the component. */
  36240. void enablementChanged();
  36241. protected:
  36242. /** Used by the PropertyPanel to determine how high this component needs to be.
  36243. A subclass can update this value in its constructor but shouldn't alter it later
  36244. as changes won't necessarily be picked up.
  36245. */
  36246. int preferredHeight;
  36247. private:
  36248. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  36249. };
  36250. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36251. /*** End of inlined file: juce_PropertyComponent.h ***/
  36252. /**
  36253. A panel that holds a list of PropertyComponent objects.
  36254. This panel displays a list of PropertyComponents, and allows them to be organised
  36255. into collapsible sections.
  36256. To use, simply create one of these and add your properties to it with addProperties()
  36257. or addSection().
  36258. @see PropertyComponent
  36259. */
  36260. class JUCE_API PropertyPanel : public Component
  36261. {
  36262. public:
  36263. /** Creates an empty property panel. */
  36264. PropertyPanel();
  36265. /** Destructor. */
  36266. ~PropertyPanel();
  36267. /** Deletes all property components from the panel.
  36268. */
  36269. void clear();
  36270. /** Adds a set of properties to the panel.
  36271. The components in the list will be owned by this object and will be automatically
  36272. deleted later on when no longer needed.
  36273. These properties are added without them being inside a named section. If you
  36274. want them to be kept together in a collapsible section, use addSection() instead.
  36275. */
  36276. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  36277. /** Adds a set of properties to the panel.
  36278. These properties are added at the bottom of the list, under a section heading with
  36279. a plus/minus button that allows it to be opened and closed.
  36280. The components in the list will be owned by this object and will be automatically
  36281. deleted later on when no longer needed.
  36282. To add properies without them being in a section, use addProperties().
  36283. */
  36284. void addSection (const String& sectionTitle,
  36285. const Array <PropertyComponent*>& newPropertyComponents,
  36286. bool shouldSectionInitiallyBeOpen = true);
  36287. /** Calls the refresh() method of all PropertyComponents in the panel */
  36288. void refreshAll() const;
  36289. /** Returns a list of all the names of sections in the panel.
  36290. These are the sections that have been added with addSection().
  36291. */
  36292. const StringArray getSectionNames() const;
  36293. /** Returns true if the section at this index is currently open.
  36294. The index is from 0 up to the number of items returned by getSectionNames().
  36295. */
  36296. bool isSectionOpen (int sectionIndex) const;
  36297. /** Opens or closes one of the sections.
  36298. The index is from 0 up to the number of items returned by getSectionNames().
  36299. */
  36300. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  36301. /** Enables or disables one of the sections.
  36302. The index is from 0 up to the number of items returned by getSectionNames().
  36303. */
  36304. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  36305. /** Saves the current state of open/closed sections so it can be restored later.
  36306. The caller is responsible for deleting the object that is returned.
  36307. To restore this state, use restoreOpennessState().
  36308. @see restoreOpennessState
  36309. */
  36310. XmlElement* getOpennessState() const;
  36311. /** Restores a previously saved arrangement of open/closed sections.
  36312. This will try to restore a snapshot of the panel's state that was created by
  36313. the getOpennessState() method. If any of the sections named in the original
  36314. XML aren't present, they will be ignored.
  36315. @see getOpennessState
  36316. */
  36317. void restoreOpennessState (const XmlElement& newState);
  36318. /** Sets a message to be displayed when there are no properties in the panel.
  36319. The default message is "nothing selected".
  36320. */
  36321. void setMessageWhenEmpty (const String& newMessage);
  36322. /** Returns the message that is displayed when there are no properties.
  36323. @see setMessageWhenEmpty
  36324. */
  36325. const String& getMessageWhenEmpty() const;
  36326. /** @internal */
  36327. void paint (Graphics& g);
  36328. /** @internal */
  36329. void resized();
  36330. private:
  36331. Viewport viewport;
  36332. class PropertyHolderComponent;
  36333. PropertyHolderComponent* propertyHolderComponent;
  36334. String messageWhenEmpty;
  36335. void updatePropHolderLayout() const;
  36336. void updatePropHolderLayout (int width) const;
  36337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  36338. };
  36339. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  36340. /*** End of inlined file: juce_PropertyPanel.h ***/
  36341. /**
  36342. A type of UI component that displays the parameters of an AudioProcessor as
  36343. a simple list of sliders.
  36344. This can be used for showing an editor for a processor that doesn't supply
  36345. its own custom editor.
  36346. @see AudioProcessor
  36347. */
  36348. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  36349. {
  36350. public:
  36351. GenericAudioProcessorEditor (AudioProcessor* owner);
  36352. ~GenericAudioProcessorEditor();
  36353. void paint (Graphics& g);
  36354. void resized();
  36355. private:
  36356. PropertyPanel panel;
  36357. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  36358. };
  36359. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36360. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  36361. #endif
  36362. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  36363. /*** Start of inlined file: juce_Sampler.h ***/
  36364. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  36365. #define __JUCE_SAMPLER_JUCEHEADER__
  36366. /*** Start of inlined file: juce_Synthesiser.h ***/
  36367. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36368. #define __JUCE_SYNTHESISER_JUCEHEADER__
  36369. /**
  36370. Describes one of the sounds that a Synthesiser can play.
  36371. A synthesiser can contain one or more sounds, and a sound can choose which
  36372. midi notes and channels can trigger it.
  36373. The SynthesiserSound is a passive class that just describes what the sound is -
  36374. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  36375. more than one SynthesiserVoice to play the same sound at the same time.
  36376. @see Synthesiser, SynthesiserVoice
  36377. */
  36378. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  36379. {
  36380. protected:
  36381. SynthesiserSound();
  36382. public:
  36383. /** Destructor. */
  36384. virtual ~SynthesiserSound();
  36385. /** Returns true if this sound should be played when a given midi note is pressed.
  36386. The Synthesiser will use this information when deciding which sounds to trigger
  36387. for a given note.
  36388. */
  36389. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  36390. /** Returns true if the sound should be triggered by midi events on a given channel.
  36391. The Synthesiser will use this information when deciding which sounds to trigger
  36392. for a given note.
  36393. */
  36394. virtual bool appliesToChannel (const int midiChannel) = 0;
  36395. /**
  36396. */
  36397. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  36398. private:
  36399. JUCE_LEAK_DETECTOR (SynthesiserSound);
  36400. };
  36401. /**
  36402. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  36403. A voice plays a single sound at a time, and a synthesiser holds an array of
  36404. voices so that it can play polyphonically.
  36405. @see Synthesiser, SynthesiserSound
  36406. */
  36407. class JUCE_API SynthesiserVoice
  36408. {
  36409. public:
  36410. /** Creates a voice. */
  36411. SynthesiserVoice();
  36412. /** Destructor. */
  36413. virtual ~SynthesiserVoice();
  36414. /** Returns the midi note that this voice is currently playing.
  36415. Returns a value less than 0 if no note is playing.
  36416. */
  36417. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  36418. /** Returns the sound that this voice is currently playing.
  36419. Returns 0 if it's not playing.
  36420. */
  36421. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  36422. /** Must return true if this voice object is capable of playing the given sound.
  36423. If there are different classes of sound, and different classes of voice, a voice can
  36424. choose which ones it wants to take on.
  36425. A typical implementation of this method may just return true if there's only one type
  36426. of voice and sound, or it might check the type of the sound object passed-in and
  36427. see if it's one that it understands.
  36428. */
  36429. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  36430. /** Called to start a new note.
  36431. This will be called during the rendering callback, so must be fast and thread-safe.
  36432. */
  36433. virtual void startNote (const int midiNoteNumber,
  36434. const float velocity,
  36435. SynthesiserSound* sound,
  36436. const int currentPitchWheelPosition) = 0;
  36437. /** Called to stop a note.
  36438. This will be called during the rendering callback, so must be fast and thread-safe.
  36439. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  36440. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  36441. and allow the synth to reassign it another sound.
  36442. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  36443. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  36444. finishes playing (during the rendering callback), it must make sure that it calls
  36445. clearCurrentNote().
  36446. */
  36447. virtual void stopNote (const bool allowTailOff) = 0;
  36448. /** Called to let the voice know that the pitch wheel has been moved.
  36449. This will be called during the rendering callback, so must be fast and thread-safe.
  36450. */
  36451. virtual void pitchWheelMoved (const int newValue) = 0;
  36452. /** Called to let the voice know that a midi controller has been moved.
  36453. This will be called during the rendering callback, so must be fast and thread-safe.
  36454. */
  36455. virtual void controllerMoved (const int controllerNumber,
  36456. const int newValue) = 0;
  36457. /** Renders the next block of data for this voice.
  36458. The output audio data must be added to the current contents of the buffer provided.
  36459. Only the region of the buffer between startSample and (startSample + numSamples)
  36460. should be altered by this method.
  36461. If the voice is currently silent, it should just return without doing anything.
  36462. If the sound that the voice is playing finishes during the course of this rendered
  36463. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  36464. The size of the blocks that are rendered can change each time it is called, and may
  36465. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  36466. the voice's methods will be called to tell it about note and controller events.
  36467. */
  36468. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  36469. int startSample,
  36470. int numSamples) = 0;
  36471. /** Returns true if the voice is currently playing a sound which is mapped to the given
  36472. midi channel.
  36473. If it's not currently playing, this will return false.
  36474. */
  36475. bool isPlayingChannel (int midiChannel) const;
  36476. /** Changes the voice's reference sample rate.
  36477. The rate is set so that subclasses know the output rate and can set their pitch
  36478. accordingly.
  36479. This method is called by the synth, and subclasses can access the current rate with
  36480. the currentSampleRate member.
  36481. */
  36482. void setCurrentPlaybackSampleRate (double newRate);
  36483. protected:
  36484. /** Returns the current target sample rate at which rendering is being done.
  36485. This is available for subclasses so they can pitch things correctly.
  36486. */
  36487. double getSampleRate() const { return currentSampleRate; }
  36488. /** Resets the state of this voice after a sound has finished playing.
  36489. The subclass must call this when it finishes playing a note and becomes available
  36490. to play new ones.
  36491. It must either call it in the stopNote() method, or if the voice is tailing off,
  36492. then it should call it later during the renderNextBlock method, as soon as it
  36493. finishes its tail-off.
  36494. It can also be called at any time during the render callback if the sound happens
  36495. to have finished, e.g. if it's playing a sample and the sample finishes.
  36496. */
  36497. void clearCurrentNote();
  36498. private:
  36499. friend class Synthesiser;
  36500. double currentSampleRate;
  36501. int currentlyPlayingNote;
  36502. uint32 noteOnTime;
  36503. SynthesiserSound::Ptr currentlyPlayingSound;
  36504. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  36505. };
  36506. /**
  36507. Base class for a musical device that can play sounds.
  36508. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  36509. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  36510. which can play back one of these sounds.
  36511. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  36512. set of sounds, and a set of voices it can use to play them. If you only give it
  36513. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  36514. have available.
  36515. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  36516. events that go in will be scanned for note on/off messages, and these are used to
  36517. start and stop the voices playing the appropriate sounds.
  36518. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  36519. noteOff() and other controller methods.
  36520. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  36521. what the target playback rate is. This value is passed on to the voices so that
  36522. they can pitch their output correctly.
  36523. */
  36524. class JUCE_API Synthesiser
  36525. {
  36526. public:
  36527. /** Creates a new synthesiser.
  36528. You'll need to add some sounds and voices before it'll make any sound..
  36529. */
  36530. Synthesiser();
  36531. /** Destructor. */
  36532. virtual ~Synthesiser();
  36533. /** Deletes all voices. */
  36534. void clearVoices();
  36535. /** Returns the number of voices that have been added. */
  36536. int getNumVoices() const { return voices.size(); }
  36537. /** Returns one of the voices that have been added. */
  36538. SynthesiserVoice* getVoice (int index) const;
  36539. /** Adds a new voice to the synth.
  36540. All the voices should be the same class of object and are treated equally.
  36541. The object passed in will be managed by the synthesiser, which will delete
  36542. it later on when no longer needed. The caller should not retain a pointer to the
  36543. voice.
  36544. */
  36545. void addVoice (SynthesiserVoice* newVoice);
  36546. /** Deletes one of the voices. */
  36547. void removeVoice (int index);
  36548. /** Deletes all sounds. */
  36549. void clearSounds();
  36550. /** Returns the number of sounds that have been added to the synth. */
  36551. int getNumSounds() const { return sounds.size(); }
  36552. /** Returns one of the sounds. */
  36553. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  36554. /** Adds a new sound to the synthesiser.
  36555. The object passed in is reference counted, so will be deleted when it is removed
  36556. from the synthesiser, and when no voices are still using it.
  36557. */
  36558. void addSound (const SynthesiserSound::Ptr& newSound);
  36559. /** Removes and deletes one of the sounds. */
  36560. void removeSound (int index);
  36561. /** If set to true, then the synth will try to take over an existing voice if
  36562. it runs out and needs to play another note.
  36563. The value of this boolean is passed into findFreeVoice(), so the result will
  36564. depend on the implementation of this method.
  36565. */
  36566. void setNoteStealingEnabled (bool shouldStealNotes);
  36567. /** Returns true if note-stealing is enabled.
  36568. @see setNoteStealingEnabled
  36569. */
  36570. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  36571. /** Triggers a note-on event.
  36572. The default method here will find all the sounds that want to be triggered by
  36573. this note/channel. For each sound, it'll try to find a free voice, and use the
  36574. voice to start playing the sound.
  36575. Subclasses might want to override this if they need a more complex algorithm.
  36576. This method will be called automatically according to the midi data passed into
  36577. renderNextBlock(), but may be called explicitly too.
  36578. */
  36579. virtual void noteOn (int midiChannel,
  36580. int midiNoteNumber,
  36581. float velocity);
  36582. /** Triggers a note-off event.
  36583. This will turn off any voices that are playing a sound for the given note/channel.
  36584. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36585. (if they can do). If this is false, the notes will all be cut off immediately.
  36586. This method will be called automatically according to the midi data passed into
  36587. renderNextBlock(), but may be called explicitly too.
  36588. */
  36589. virtual void noteOff (int midiChannel,
  36590. int midiNoteNumber,
  36591. bool allowTailOff);
  36592. /** Turns off all notes.
  36593. This will turn off any voices that are playing a sound on the given midi channel.
  36594. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36595. which channel they're playing.
  36596. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36597. (if they can do). If this is false, the notes will all be cut off immediately.
  36598. This method will be called automatically according to the midi data passed into
  36599. renderNextBlock(), but may be called explicitly too.
  36600. */
  36601. virtual void allNotesOff (int midiChannel,
  36602. bool allowTailOff);
  36603. /** Sends a pitch-wheel message.
  36604. This will send a pitch-wheel message to any voices that are playing sounds on
  36605. the given midi channel.
  36606. This method will be called automatically according to the midi data passed into
  36607. renderNextBlock(), but may be called explicitly too.
  36608. @param midiChannel the midi channel for the event
  36609. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36610. */
  36611. virtual void handlePitchWheel (int midiChannel,
  36612. int wheelValue);
  36613. /** Sends a midi controller message.
  36614. This will send a midi controller message to any voices that are playing sounds on
  36615. the given midi channel.
  36616. This method will be called automatically according to the midi data passed into
  36617. renderNextBlock(), but may be called explicitly too.
  36618. @param midiChannel the midi channel for the event
  36619. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36620. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36621. */
  36622. virtual void handleController (int midiChannel,
  36623. int controllerNumber,
  36624. int controllerValue);
  36625. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36626. render.
  36627. This value is propagated to the voices so that they can use it to render the correct
  36628. pitches.
  36629. */
  36630. void setCurrentPlaybackSampleRate (double sampleRate);
  36631. /** Creates the next block of audio output.
  36632. This will process the next numSamples of data from all the voices, and add that output
  36633. to the audio block supplied, starting from the offset specified. Note that the
  36634. data will be added to the current contents of the buffer, so you should clear it
  36635. before calling this method if necessary.
  36636. The midi events in the inputMidi buffer are parsed for note and controller events,
  36637. and these are used to trigger the voices. Note that the startSample offset applies
  36638. both to the audio output buffer and the midi input buffer, so any midi events
  36639. with timestamps outside the specified region will be ignored.
  36640. */
  36641. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36642. const MidiBuffer& inputMidi,
  36643. int startSample,
  36644. int numSamples);
  36645. protected:
  36646. /** This is used to control access to the rendering callback and the note trigger methods. */
  36647. CriticalSection lock;
  36648. OwnedArray <SynthesiserVoice> voices;
  36649. ReferenceCountedArray <SynthesiserSound> sounds;
  36650. /** The last pitch-wheel values for each midi channel. */
  36651. int lastPitchWheelValues [16];
  36652. /** Searches through the voices to find one that's not currently playing, and which
  36653. can play the given sound.
  36654. Returns 0 if all voices are busy and stealing isn't enabled.
  36655. This can be overridden to implement custom voice-stealing algorithms.
  36656. */
  36657. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36658. const bool stealIfNoneAvailable) const;
  36659. /** Starts a specified voice playing a particular sound.
  36660. You'll probably never need to call this, it's used internally by noteOn(), but
  36661. may be needed by subclasses for custom behaviours.
  36662. */
  36663. void startVoice (SynthesiserVoice* voice,
  36664. SynthesiserSound* sound,
  36665. int midiChannel,
  36666. int midiNoteNumber,
  36667. float velocity);
  36668. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36669. // Temporary method here to cause a compiler error - note the new parameters for this method.
  36670. int findFreeVoice (const bool) const { return 0; }
  36671. #endif
  36672. private:
  36673. double sampleRate;
  36674. uint32 lastNoteOnCounter;
  36675. bool shouldStealNotes;
  36676. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36677. };
  36678. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36679. /*** End of inlined file: juce_Synthesiser.h ***/
  36680. /**
  36681. A subclass of SynthesiserSound that represents a sampled audio clip.
  36682. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36683. into memory.
  36684. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36685. give it some SampledSound objects to play.
  36686. @see SamplerVoice, Synthesiser, SynthesiserSound
  36687. */
  36688. class JUCE_API SamplerSound : public SynthesiserSound
  36689. {
  36690. public:
  36691. /** Creates a sampled sound from an audio reader.
  36692. This will attempt to load the audio from the source into memory and store
  36693. it in this object.
  36694. @param name a name for the sample
  36695. @param source the audio to load. This object can be safely deleted by the
  36696. caller after this constructor returns
  36697. @param midiNotes the set of midi keys that this sound should be played on. This
  36698. is used by the SynthesiserSound::appliesToNote() method
  36699. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36700. with its natural rate. All other notes will be pitched
  36701. up or down relative to this one
  36702. @param attackTimeSecs the attack (fade-in) time, in seconds
  36703. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36704. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36705. source, in seconds
  36706. */
  36707. SamplerSound (const String& name,
  36708. AudioFormatReader& source,
  36709. const BigInteger& midiNotes,
  36710. int midiNoteForNormalPitch,
  36711. double attackTimeSecs,
  36712. double releaseTimeSecs,
  36713. double maxSampleLengthSeconds);
  36714. /** Destructor. */
  36715. ~SamplerSound();
  36716. /** Returns the sample's name */
  36717. const String& getName() const { return name; }
  36718. /** Returns the audio sample data.
  36719. This could be 0 if there was a problem loading it.
  36720. */
  36721. AudioSampleBuffer* getAudioData() const { return data; }
  36722. bool appliesToNote (const int midiNoteNumber);
  36723. bool appliesToChannel (const int midiChannel);
  36724. private:
  36725. friend class SamplerVoice;
  36726. String name;
  36727. ScopedPointer <AudioSampleBuffer> data;
  36728. double sourceSampleRate;
  36729. BigInteger midiNotes;
  36730. int length, attackSamples, releaseSamples;
  36731. int midiRootNote;
  36732. JUCE_LEAK_DETECTOR (SamplerSound);
  36733. };
  36734. /**
  36735. A subclass of SynthesiserVoice that can play a SamplerSound.
  36736. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36737. give it some SampledSound objects to play.
  36738. @see SamplerSound, Synthesiser, SynthesiserVoice
  36739. */
  36740. class JUCE_API SamplerVoice : public SynthesiserVoice
  36741. {
  36742. public:
  36743. /** Creates a SamplerVoice.
  36744. */
  36745. SamplerVoice();
  36746. /** Destructor. */
  36747. ~SamplerVoice();
  36748. bool canPlaySound (SynthesiserSound* sound);
  36749. void startNote (const int midiNoteNumber,
  36750. const float velocity,
  36751. SynthesiserSound* sound,
  36752. const int currentPitchWheelPosition);
  36753. void stopNote (const bool allowTailOff);
  36754. void pitchWheelMoved (const int newValue);
  36755. void controllerMoved (const int controllerNumber,
  36756. const int newValue);
  36757. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36758. private:
  36759. double pitchRatio;
  36760. double sourceSamplePosition;
  36761. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36762. bool isInAttack, isInRelease;
  36763. JUCE_LEAK_DETECTOR (SamplerVoice);
  36764. };
  36765. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36766. /*** End of inlined file: juce_Sampler.h ***/
  36767. #endif
  36768. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36769. #endif
  36770. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36771. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36772. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36773. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36774. /** Manages a list of ActionListeners, and can send them messages.
  36775. To quickly add methods to your class that can add/remove action
  36776. listeners and broadcast to them, you can derive from this.
  36777. @see ActionListener, ChangeListener
  36778. */
  36779. class JUCE_API ActionBroadcaster
  36780. {
  36781. public:
  36782. /** Creates an ActionBroadcaster. */
  36783. ActionBroadcaster();
  36784. /** Destructor. */
  36785. virtual ~ActionBroadcaster();
  36786. /** Adds a listener to the list.
  36787. Trying to add a listener that's already on the list will have no effect.
  36788. */
  36789. void addActionListener (ActionListener* listener);
  36790. /** Removes a listener from the list.
  36791. If the listener isn't on the list, this won't have any effect.
  36792. */
  36793. void removeActionListener (ActionListener* listener);
  36794. /** Removes all listeners from the list. */
  36795. void removeAllActionListeners();
  36796. /** Broadcasts a message to all the registered listeners.
  36797. @see ActionListener::actionListenerCallback
  36798. */
  36799. void sendActionMessage (const String& message) const;
  36800. private:
  36801. class CallbackReceiver : public MessageListener
  36802. {
  36803. public:
  36804. CallbackReceiver();
  36805. void handleMessage (const Message&);
  36806. ActionBroadcaster* owner;
  36807. };
  36808. friend class CallbackReceiver;
  36809. CallbackReceiver callback;
  36810. SortedSet <ActionListener*> actionListeners;
  36811. CriticalSection actionListenerLock;
  36812. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36813. };
  36814. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36815. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36816. #endif
  36817. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36818. #endif
  36819. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36820. #endif
  36821. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36822. #endif
  36823. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36824. #endif
  36825. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36826. #endif
  36827. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36828. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36829. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36830. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36831. class InterprocessConnectionServer;
  36832. /**
  36833. Manages a simple two-way messaging connection to another process, using either
  36834. a socket or a named pipe as the transport medium.
  36835. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36836. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36837. and incoming messages will result in a callback via the messageReceived()
  36838. method.
  36839. To open a pipe and wait for another client to connect to it, use the createPipe()
  36840. method.
  36841. To act as a socket server and create connections for one or more client, see the
  36842. InterprocessConnectionServer class.
  36843. @see InterprocessConnectionServer, Socket, NamedPipe
  36844. */
  36845. class JUCE_API InterprocessConnection : public Thread,
  36846. private MessageListener
  36847. {
  36848. public:
  36849. /** Creates a connection.
  36850. Connections are created manually, connecting them with the connectToSocket()
  36851. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36852. when a client wants to connect.
  36853. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36854. connectionLost() and messageReceived() methods will
  36855. always be made using the message thread; if false,
  36856. these will be called immediately on the connection's
  36857. own thread.
  36858. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36859. validity of the data blocks being sent and received. This
  36860. can be any number, but the sender and receiver must obviously
  36861. use matching values or they won't recognise each other.
  36862. */
  36863. InterprocessConnection (bool callbacksOnMessageThread = true,
  36864. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36865. /** Destructor. */
  36866. ~InterprocessConnection();
  36867. /** Tries to connect this object to a socket.
  36868. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36869. object waiting to receive client connections on this port number.
  36870. @param hostName the host computer, either a network address or name
  36871. @param portNumber the socket port number to try to connect to
  36872. @param timeOutMillisecs how long to keep trying before giving up
  36873. @returns true if the connection is established successfully
  36874. @see Socket
  36875. */
  36876. bool connectToSocket (const String& hostName,
  36877. int portNumber,
  36878. int timeOutMillisecs);
  36879. /** Tries to connect the object to an existing named pipe.
  36880. For this to work, another process on the same computer must already have opened
  36881. an InterprocessConnection object and used createPipe() to create a pipe for this
  36882. to connect to.
  36883. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36884. @returns true if it connects successfully.
  36885. @see createPipe, NamedPipe
  36886. */
  36887. bool connectToPipe (const String& pipeName,
  36888. int pipeReceiveMessageTimeoutMs = -1);
  36889. /** Tries to create a new pipe for other processes to connect to.
  36890. This creates a pipe with the given name, so that other processes can use
  36891. connectToPipe() to connect to the other end.
  36892. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36893. If another process is already using this pipe, this will fail and return false.
  36894. */
  36895. bool createPipe (const String& pipeName,
  36896. int pipeReceiveMessageTimeoutMs = -1);
  36897. /** Disconnects and closes any currently-open sockets or pipes. */
  36898. void disconnect();
  36899. /** True if a socket or pipe is currently active. */
  36900. bool isConnected() const;
  36901. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36902. StreamingSocket* getSocket() const noexcept { return socket; }
  36903. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36904. NamedPipe* getPipe() const noexcept { return pipe; }
  36905. /** Returns the name of the machine at the other end of this connection.
  36906. This will return an empty string if the other machine isn't known for
  36907. some reason.
  36908. */
  36909. const String getConnectedHostName() const;
  36910. /** Tries to send a message to the other end of this connection.
  36911. This will fail if it's not connected, or if there's some kind of write error. If
  36912. it succeeds, the connection object at the other end will receive the message by
  36913. a callback to its messageReceived() method.
  36914. @see messageReceived
  36915. */
  36916. bool sendMessage (const MemoryBlock& message);
  36917. /** Called when the connection is first connected.
  36918. If the connection was created with the callbacksOnMessageThread flag set, then
  36919. this will be called on the message thread; otherwise it will be called on a server
  36920. thread.
  36921. */
  36922. virtual void connectionMade() = 0;
  36923. /** Called when the connection is broken.
  36924. If the connection was created with the callbacksOnMessageThread flag set, then
  36925. this will be called on the message thread; otherwise it will be called on a server
  36926. thread.
  36927. */
  36928. virtual void connectionLost() = 0;
  36929. /** Called when a message arrives.
  36930. When the object at the other end of this connection sends us a message with sendMessage(),
  36931. this callback is used to deliver it to us.
  36932. If the connection was created with the callbacksOnMessageThread flag set, then
  36933. this will be called on the message thread; otherwise it will be called on a server
  36934. thread.
  36935. @see sendMessage
  36936. */
  36937. virtual void messageReceived (const MemoryBlock& message) = 0;
  36938. private:
  36939. CriticalSection pipeAndSocketLock;
  36940. ScopedPointer <StreamingSocket> socket;
  36941. ScopedPointer <NamedPipe> pipe;
  36942. bool callbackConnectionState;
  36943. const bool useMessageThread;
  36944. const uint32 magicMessageHeader;
  36945. int pipeReceiveMessageTimeout;
  36946. friend class InterprocessConnectionServer;
  36947. void initialiseWithSocket (StreamingSocket* socket_);
  36948. void initialiseWithPipe (NamedPipe* pipe_);
  36949. void handleMessage (const Message& message);
  36950. void connectionMadeInt();
  36951. void connectionLostInt();
  36952. void deliverDataInt (const MemoryBlock& data);
  36953. bool readNextMessageInt();
  36954. void run();
  36955. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36956. };
  36957. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36958. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36959. #endif
  36960. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36961. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36962. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36963. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36964. /**
  36965. An object that waits for client sockets to connect to a port on this host, and
  36966. creates InterprocessConnection objects for each one.
  36967. To use this, create a class derived from it which implements the createConnectionObject()
  36968. method, so that it creates suitable connection objects for each client that tries
  36969. to connect.
  36970. @see InterprocessConnection
  36971. */
  36972. class JUCE_API InterprocessConnectionServer : private Thread
  36973. {
  36974. public:
  36975. /** Creates an uninitialised server object.
  36976. */
  36977. InterprocessConnectionServer();
  36978. /** Destructor. */
  36979. ~InterprocessConnectionServer();
  36980. /** Starts an internal thread which listens on the given port number.
  36981. While this is running, in another process tries to connect with the
  36982. InterprocessConnection::connectToSocket() method, this object will call
  36983. createConnectionObject() to create a connection to that client.
  36984. Use stop() to stop the thread running.
  36985. @see createConnectionObject, stop
  36986. */
  36987. bool beginWaitingForSocket (int portNumber);
  36988. /** Terminates the listener thread, if it's active.
  36989. @see beginWaitingForSocket
  36990. */
  36991. void stop();
  36992. protected:
  36993. /** Creates a suitable connection object for a client process that wants to
  36994. connect to this one.
  36995. This will be called by the listener thread when a client process tries
  36996. to connect, and must return a new InterprocessConnection object that will
  36997. then run as this end of the connection.
  36998. @see InterprocessConnection
  36999. */
  37000. virtual InterprocessConnection* createConnectionObject() = 0;
  37001. private:
  37002. ScopedPointer <StreamingSocket> socket;
  37003. void run();
  37004. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  37005. };
  37006. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  37007. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  37008. #endif
  37009. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  37010. #endif
  37011. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  37012. #endif
  37013. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  37014. #endif
  37015. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37016. /*** Start of inlined file: juce_MessageManager.h ***/
  37017. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37018. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37019. class Component;
  37020. class MessageManagerLock;
  37021. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  37022. */
  37023. typedef void* (MessageCallbackFunction) (void* userData);
  37024. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  37025. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  37026. */
  37027. class JUCE_API MessageManager
  37028. {
  37029. public:
  37030. /** Returns the global instance of the MessageManager. */
  37031. static MessageManager* getInstance() noexcept;
  37032. /** Runs the event dispatch loop until a stop message is posted.
  37033. This method is only intended to be run by the application's startup routine,
  37034. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  37035. @see stopDispatchLoop
  37036. */
  37037. void runDispatchLoop();
  37038. /** Sends a signal that the dispatch loop should terminate.
  37039. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  37040. will be interrupted and will return.
  37041. @see runDispatchLoop
  37042. */
  37043. void stopDispatchLoop();
  37044. /** Returns true if the stopDispatchLoop() method has been called.
  37045. */
  37046. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  37047. #if JUCE_MODAL_LOOPS_PERMITTED
  37048. /** Synchronously dispatches messages until a given time has elapsed.
  37049. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  37050. otherwise returns true.
  37051. */
  37052. bool runDispatchLoopUntil (int millisecondsToRunFor);
  37053. #endif
  37054. /** Calls a function using the message-thread.
  37055. This can be used by any thread to cause this function to be called-back
  37056. by the message thread. If it's the message-thread that's calling this method,
  37057. then the function will just be called; if another thread is calling, a message
  37058. will be posted to the queue, and this method will block until that message
  37059. is delivered, the function is called, and the result is returned.
  37060. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  37061. thread has a critical section locked, which an unrelated message callback then tries to lock
  37062. before the message thread gets round to processing this callback.
  37063. @param callback the function to call - its signature must be @code
  37064. void* myCallbackFunction (void*) @endcode
  37065. @param userData a user-defined pointer that will be passed to the function that gets called
  37066. @returns the value that the callback function returns.
  37067. @see MessageManagerLock
  37068. */
  37069. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  37070. void* userData);
  37071. /** Returns true if the caller-thread is the message thread. */
  37072. bool isThisTheMessageThread() const noexcept;
  37073. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  37074. (Best to ignore this method unless you really know what you're doing..)
  37075. @see getCurrentMessageThread
  37076. */
  37077. void setCurrentThreadAsMessageThread();
  37078. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  37079. (Best to ignore this method unless you really know what you're doing..)
  37080. @see setCurrentMessageThread
  37081. */
  37082. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  37083. /** Returns true if the caller thread has currenltly got the message manager locked.
  37084. see the MessageManagerLock class for more info about this.
  37085. This will be true if the caller is the message thread, because that automatically
  37086. gains a lock while a message is being dispatched.
  37087. */
  37088. bool currentThreadHasLockedMessageManager() const noexcept;
  37089. /** Sends a message to all other JUCE applications that are running.
  37090. @param messageText the string that will be passed to the actionListenerCallback()
  37091. method of the broadcast listeners in the other app.
  37092. @see registerBroadcastListener, ActionListener
  37093. */
  37094. static void broadcastMessage (const String& messageText);
  37095. /** Registers a listener to get told about broadcast messages.
  37096. The actionListenerCallback() callback's string parameter
  37097. is the message passed into broadcastMessage().
  37098. @see broadcastMessage
  37099. */
  37100. void registerBroadcastListener (ActionListener* listener);
  37101. /** Deregisters a broadcast listener. */
  37102. void deregisterBroadcastListener (ActionListener* listener);
  37103. /** @internal */
  37104. void deliverMessage (Message*);
  37105. /** @internal */
  37106. void deliverBroadcastMessage (const String&);
  37107. /** @internal */
  37108. ~MessageManager() noexcept;
  37109. private:
  37110. MessageManager() noexcept;
  37111. friend class MessageListener;
  37112. friend class ChangeBroadcaster;
  37113. friend class ActionBroadcaster;
  37114. friend class CallbackMessage;
  37115. static MessageManager* instance;
  37116. SortedSet <const MessageListener*> messageListeners;
  37117. ScopedPointer <ActionBroadcaster> broadcaster;
  37118. friend class JUCEApplication;
  37119. bool quitMessagePosted, quitMessageReceived;
  37120. Thread::ThreadID messageThreadId;
  37121. friend class MessageManagerLock;
  37122. Thread::ThreadID volatile threadWithLock;
  37123. CriticalSection lockingLock;
  37124. void postMessageToQueue (Message* message);
  37125. static bool postMessageToSystemQueue (Message*);
  37126. static void* exitModalLoopCallback (void*);
  37127. static void doPlatformSpecificInitialisation();
  37128. static void doPlatformSpecificShutdown();
  37129. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  37130. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  37131. };
  37132. /** Used to make sure that the calling thread has exclusive access to the message loop.
  37133. Because it's not thread-safe to call any of the Component or other UI classes
  37134. from threads other than the message thread, one of these objects can be used to
  37135. lock the message loop and allow this to be done. The message thread will be
  37136. suspended for the lifetime of the MessageManagerLock object, so create one on
  37137. the stack like this: @code
  37138. void MyThread::run()
  37139. {
  37140. someData = 1234;
  37141. const MessageManagerLock mmLock;
  37142. // the event loop will now be locked so it's safe to make a few calls..
  37143. myComponent->setBounds (newBounds);
  37144. myComponent->repaint();
  37145. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  37146. }
  37147. @endcode
  37148. Obviously be careful not to create one of these and leave it lying around, or
  37149. your app will grind to a halt!
  37150. Another caveat is that using this in conjunction with other CriticalSections
  37151. can create lots of interesting ways of producing a deadlock! In particular, if
  37152. your message thread calls stopThread() for a thread that uses these locks,
  37153. you'll get an (occasional) deadlock..
  37154. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  37155. */
  37156. class JUCE_API MessageManagerLock
  37157. {
  37158. public:
  37159. /** Tries to acquire a lock on the message manager.
  37160. The constructor attempts to gain a lock on the message loop, and the lock will be
  37161. kept for the lifetime of this object.
  37162. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  37163. this method will keep checking whether the thread has been given the
  37164. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  37165. without gaining the lock. If you pass a thread, you must check whether the lock was
  37166. successful by calling lockWasGained(). If this is false, your thread is being told to
  37167. die, so you should take evasive action.
  37168. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  37169. careful when doing this, because it's very easy to deadlock if your message thread
  37170. attempts to call stopThread() on a thread just as that thread attempts to get the
  37171. message lock.
  37172. If the calling thread already has the lock, nothing will be done, so it's safe and
  37173. quick to use these locks recursively.
  37174. E.g.
  37175. @code
  37176. void run()
  37177. {
  37178. ...
  37179. while (! threadShouldExit())
  37180. {
  37181. MessageManagerLock mml (Thread::getCurrentThread());
  37182. if (! mml.lockWasGained())
  37183. return; // another thread is trying to kill us!
  37184. ..do some locked stuff here..
  37185. }
  37186. ..and now the MM is now unlocked..
  37187. }
  37188. @endcode
  37189. */
  37190. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  37191. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  37192. instead of a thread.
  37193. See the MessageManagerLock (Thread*) constructor for details on how this works.
  37194. */
  37195. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  37196. /** Releases the current thread's lock on the message manager.
  37197. Make sure this object is created and deleted by the same thread,
  37198. otherwise there are no guarantees what will happen!
  37199. */
  37200. ~MessageManagerLock() noexcept;
  37201. /** Returns true if the lock was successfully acquired.
  37202. (See the constructor that takes a Thread for more info).
  37203. */
  37204. bool lockWasGained() const noexcept { return locked; }
  37205. private:
  37206. class BlockingMessage;
  37207. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  37208. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  37209. bool locked;
  37210. void init (Thread* thread, ThreadPoolJob* job);
  37211. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  37212. };
  37213. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37214. /*** End of inlined file: juce_MessageManager.h ***/
  37215. #endif
  37216. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  37217. /*** Start of inlined file: juce_MultiTimer.h ***/
  37218. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  37219. #define __JUCE_MULTITIMER_JUCEHEADER__
  37220. /**
  37221. A type of timer class that can run multiple timers with different frequencies,
  37222. all of which share a single callback.
  37223. This class is very similar to the Timer class, but allows you run multiple
  37224. separate timers, where each one has a unique ID number. The methods in this
  37225. class are exactly equivalent to those in Timer, but with the addition of
  37226. this ID number.
  37227. To use it, you need to create a subclass of MultiTimer, implementing the
  37228. timerCallback() method. Then you can start timers with startTimer(), and
  37229. each time the callback is triggered, it passes in the ID of the timer that
  37230. caused it.
  37231. @see Timer
  37232. */
  37233. class JUCE_API MultiTimer
  37234. {
  37235. protected:
  37236. /** Creates a MultiTimer.
  37237. When created, no timers are running, so use startTimer() to start things off.
  37238. */
  37239. MultiTimer() noexcept;
  37240. /** Creates a copy of another timer.
  37241. Note that this timer will not contain any running timers, even if the one you're
  37242. copying from was running.
  37243. */
  37244. MultiTimer (const MultiTimer& other) noexcept;
  37245. public:
  37246. /** Destructor. */
  37247. virtual ~MultiTimer();
  37248. /** The user-defined callback routine that actually gets called by each of the
  37249. timers that are running.
  37250. It's perfectly ok to call startTimer() or stopTimer() from within this
  37251. callback to change the subsequent intervals.
  37252. */
  37253. virtual void timerCallback (int timerId) = 0;
  37254. /** Starts a timer and sets the length of interval required.
  37255. If the timer is already started, this will reset it, so the
  37256. time between calling this method and the next timer callback
  37257. will not be less than the interval length passed in.
  37258. @param timerId a unique Id number that identifies the timer to
  37259. start. This is the id that will be passed back
  37260. to the timerCallback() method when this timer is
  37261. triggered
  37262. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  37263. rounded up to 1)
  37264. */
  37265. void startTimer (int timerId, int intervalInMilliseconds) noexcept;
  37266. /** Stops a timer.
  37267. If a timer has been started with the given ID number, it will be cancelled.
  37268. No more callbacks will be made for the specified timer after this method returns.
  37269. If this is called from a different thread, any callbacks that may
  37270. be currently executing may be allowed to finish before the method
  37271. returns.
  37272. */
  37273. void stopTimer (int timerId) noexcept;
  37274. /** Checks whether a timer has been started for a specified ID.
  37275. @returns true if a timer with the given ID is running.
  37276. */
  37277. bool isTimerRunning (int timerId) const noexcept;
  37278. /** Returns the interval for a specified timer ID.
  37279. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  37280. is running for the ID number specified.
  37281. */
  37282. int getTimerInterval (int timerId) const noexcept;
  37283. private:
  37284. class MultiTimerCallback;
  37285. SpinLock timerListLock;
  37286. OwnedArray <MultiTimerCallback> timers;
  37287. MultiTimer& operator= (const MultiTimer&);
  37288. };
  37289. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  37290. /*** End of inlined file: juce_MultiTimer.h ***/
  37291. #endif
  37292. #ifndef __JUCE_TIMER_JUCEHEADER__
  37293. #endif
  37294. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  37295. /*** Start of inlined file: juce_ArrowButton.h ***/
  37296. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  37297. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  37298. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  37299. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37300. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37301. /**
  37302. An effect filter that adds a drop-shadow behind the image's content.
  37303. (This will only work on images/components that aren't opaque, of course).
  37304. When added to a component, this effect will draw a soft-edged
  37305. shadow based on what gets drawn inside it. The shadow will also
  37306. be applied to the component's children.
  37307. For speed, this doesn't use a proper gaussian blur, but cheats by
  37308. using a simple bilinear filter. If you need a really high-quality
  37309. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  37310. @see Component::setComponentEffect
  37311. */
  37312. class JUCE_API DropShadowEffect : public ImageEffectFilter
  37313. {
  37314. public:
  37315. /** Creates a default drop-shadow effect.
  37316. To customise the shadow's appearance, use the setShadowProperties()
  37317. method.
  37318. */
  37319. DropShadowEffect();
  37320. /** Destructor. */
  37321. ~DropShadowEffect();
  37322. /** Sets up parameters affecting the shadow's appearance.
  37323. @param newRadius the (approximate) radius of the blur used
  37324. @param newOpacity the opacity with which the shadow is rendered
  37325. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  37326. component's contents
  37327. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  37328. component's contents
  37329. */
  37330. void setShadowProperties (float newRadius,
  37331. float newOpacity,
  37332. int newShadowOffsetX,
  37333. int newShadowOffsetY);
  37334. /** @internal */
  37335. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  37336. private:
  37337. int offsetX, offsetY;
  37338. float radius, opacity;
  37339. JUCE_LEAK_DETECTOR (DropShadowEffect);
  37340. };
  37341. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37342. /*** End of inlined file: juce_DropShadowEffect.h ***/
  37343. /**
  37344. A button with an arrow in it.
  37345. @see Button
  37346. */
  37347. class JUCE_API ArrowButton : public Button
  37348. {
  37349. public:
  37350. /** Creates an ArrowButton.
  37351. @param buttonName the name to give the button
  37352. @param arrowDirection the direction the arrow should point in, where 0.0 is
  37353. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  37354. @param arrowColour the colour to use for the arrow
  37355. */
  37356. ArrowButton (const String& buttonName,
  37357. float arrowDirection,
  37358. const Colour& arrowColour);
  37359. /** Destructor. */
  37360. ~ArrowButton();
  37361. protected:
  37362. /** @internal */
  37363. void paintButton (Graphics& g,
  37364. bool isMouseOverButton,
  37365. bool isButtonDown);
  37366. /** @internal */
  37367. void buttonStateChanged();
  37368. private:
  37369. Colour colour;
  37370. DropShadowEffect shadow;
  37371. Path path;
  37372. int offset;
  37373. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  37374. };
  37375. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  37376. /*** End of inlined file: juce_ArrowButton.h ***/
  37377. #endif
  37378. #ifndef __JUCE_BUTTON_JUCEHEADER__
  37379. #endif
  37380. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37381. /*** Start of inlined file: juce_DrawableButton.h ***/
  37382. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37383. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37384. /*** Start of inlined file: juce_Drawable.h ***/
  37385. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  37386. #define __JUCE_DRAWABLE_JUCEHEADER__
  37387. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  37388. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37389. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37390. /**
  37391. Expresses a coordinate as a dynamically evaluated expression.
  37392. @see RelativePoint, RelativeRectangle
  37393. */
  37394. class JUCE_API RelativeCoordinate
  37395. {
  37396. public:
  37397. /** Creates a zero coordinate. */
  37398. RelativeCoordinate();
  37399. RelativeCoordinate (const Expression& expression);
  37400. RelativeCoordinate (const RelativeCoordinate& other);
  37401. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  37402. /** Creates an absolute position from the parent origin on either the X or Y axis.
  37403. @param absoluteDistanceFromOrigin the distance from the origin
  37404. */
  37405. RelativeCoordinate (double absoluteDistanceFromOrigin);
  37406. /** Recreates a coordinate from a string description.
  37407. The string will be parsed by ExpressionParser::parse().
  37408. @param stringVersion the expression to use
  37409. @see toString
  37410. */
  37411. RelativeCoordinate (const String& stringVersion);
  37412. /** Destructor. */
  37413. ~RelativeCoordinate();
  37414. bool operator== (const RelativeCoordinate& other) const noexcept;
  37415. bool operator!= (const RelativeCoordinate& other) const noexcept;
  37416. /** Calculates the absolute position of this coordinate.
  37417. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37418. be needed to calculate the result.
  37419. */
  37420. double resolve (const Expression::Scope* evaluationScope) const;
  37421. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  37422. This will recursively check any coordinates upon which this one depends.
  37423. */
  37424. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  37425. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  37426. bool isRecursive (const Expression::Scope* evaluationScope) const;
  37427. /** Returns true if this coordinate depends on any other coordinates for its position. */
  37428. bool isDynamic() const;
  37429. /** Changes the value of this coord to make it resolve to the specified position.
  37430. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  37431. or relative position to whatever value is necessary to make its resultant position
  37432. match the position that is provided.
  37433. */
  37434. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  37435. /** Returns the expression that defines this coordinate. */
  37436. const Expression& getExpression() const { return term; }
  37437. /** Returns a string which represents this coordinate.
  37438. For details of the string syntax, see the constructor notes.
  37439. */
  37440. const String toString() const;
  37441. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  37442. As well as avoiding using string literals in your code, using these preset values
  37443. has the advantage that all instances of the same string will share the same, reference-counted
  37444. String object, so if you have thousands of points which all refer to the same
  37445. anchor points, this can save a significant amount of memory allocation.
  37446. */
  37447. struct Strings
  37448. {
  37449. static const String parent; /**< "parent" */
  37450. static const String left; /**< "left" */
  37451. static const String right; /**< "right" */
  37452. static const String top; /**< "top" */
  37453. static const String bottom; /**< "bottom" */
  37454. static const String x; /**< "x" */
  37455. static const String y; /**< "y" */
  37456. static const String width; /**< "width" */
  37457. static const String height; /**< "height" */
  37458. };
  37459. struct StandardStrings
  37460. {
  37461. enum Type
  37462. {
  37463. left, right, top, bottom,
  37464. x, y, width, height,
  37465. parent,
  37466. unknown
  37467. };
  37468. static Type getTypeOf (const String& s) noexcept;
  37469. };
  37470. private:
  37471. Expression term;
  37472. };
  37473. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37474. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  37475. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37476. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37477. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37478. /*** Start of inlined file: juce_RelativePoint.h ***/
  37479. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  37480. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  37481. /**
  37482. An X-Y position stored as a pair of RelativeCoordinate values.
  37483. @see RelativeCoordinate, RelativeRectangle
  37484. */
  37485. class JUCE_API RelativePoint
  37486. {
  37487. public:
  37488. /** Creates a point at the origin. */
  37489. RelativePoint();
  37490. /** Creates an absolute point, relative to the origin. */
  37491. RelativePoint (const Point<float>& absolutePoint);
  37492. /** Creates an absolute point, relative to the origin. */
  37493. RelativePoint (float absoluteX, float absoluteY);
  37494. /** Creates an absolute point from two coordinates. */
  37495. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  37496. /** Creates a point from a stringified representation.
  37497. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  37498. strings is explained in the RelativeCoordinate class.
  37499. @see toString
  37500. */
  37501. RelativePoint (const String& stringVersion);
  37502. bool operator== (const RelativePoint& other) const noexcept;
  37503. bool operator!= (const RelativePoint& other) const noexcept;
  37504. /** Calculates the absolute position of this point.
  37505. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37506. be needed to calculate the result.
  37507. */
  37508. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  37509. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  37510. Calling this will leave any anchor points unchanged, but will set any absolute
  37511. or relative positions to whatever values are necessary to make the resultant position
  37512. match the position that is provided.
  37513. */
  37514. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  37515. /** Returns a string which represents this point.
  37516. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  37517. coordinates, see the RelativeCoordinate constructor notes.
  37518. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  37519. */
  37520. const String toString() const;
  37521. /** Returns true if this point depends on any other coordinates for its position. */
  37522. bool isDynamic() const;
  37523. // The actual X and Y coords...
  37524. RelativeCoordinate x, y;
  37525. };
  37526. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  37527. /*** End of inlined file: juce_RelativePoint.h ***/
  37528. /*** Start of inlined file: juce_MarkerList.h ***/
  37529. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  37530. #define __JUCE_MARKERLIST_JUCEHEADER__
  37531. class Component;
  37532. /**
  37533. Holds a set of named marker points along a one-dimensional axis.
  37534. This class is used to store sets of X and Y marker points in components.
  37535. @see Component::getMarkers().
  37536. */
  37537. class JUCE_API MarkerList
  37538. {
  37539. public:
  37540. /** Creates an empty marker list. */
  37541. MarkerList();
  37542. /** Creates a copy of another marker list. */
  37543. MarkerList (const MarkerList& other);
  37544. /** Copies another marker list to this one. */
  37545. MarkerList& operator= (const MarkerList& other);
  37546. /** Destructor. */
  37547. ~MarkerList();
  37548. /** Represents a marker in a MarkerList. */
  37549. class JUCE_API Marker
  37550. {
  37551. public:
  37552. /** Creates a copy of another Marker. */
  37553. Marker (const Marker& other);
  37554. /** Creates a Marker with a given name and position. */
  37555. Marker (const String& name, const RelativeCoordinate& position);
  37556. /** The marker's name. */
  37557. String name;
  37558. /** The marker's position.
  37559. The expression used to define the coordinate may use the names of other
  37560. markers, so that markers can be linked in arbitrary ways, but be careful
  37561. not to create recursive loops of markers whose positions are based on each
  37562. other! It can also refer to "parent.right" and "parent.bottom" so that you
  37563. can set markers which are relative to the size of the component that contains
  37564. them.
  37565. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  37566. */
  37567. RelativeCoordinate position;
  37568. /** Returns true if both the names and positions of these two markers match. */
  37569. bool operator== (const Marker&) const noexcept;
  37570. /** Returns true if either the name or position of these two markers differ. */
  37571. bool operator!= (const Marker&) const noexcept;
  37572. };
  37573. /** Returns the number of markers in the list. */
  37574. int getNumMarkers() const noexcept;
  37575. /** Returns one of the markers in the list, by its index. */
  37576. const Marker* getMarker (int index) const noexcept;
  37577. /** Returns a named marker, or 0 if no such name is found.
  37578. Note that name comparisons are case-sensitive.
  37579. */
  37580. const Marker* getMarker (const String& name) const noexcept;
  37581. /** Evaluates the given marker and returns its absolute position.
  37582. The parent component must be supplied in case the marker's expression refers to
  37583. the size of its parent component.
  37584. */
  37585. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  37586. /** Sets the position of a marker.
  37587. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  37588. new marker is added.
  37589. */
  37590. void setMarker (const String& name, const RelativeCoordinate& position);
  37591. /** Deletes the marker at the given list index. */
  37592. void removeMarker (int index);
  37593. /** Deletes the marker with the given name. */
  37594. void removeMarker (const String& name);
  37595. /** Returns true if all the markers in these two lists match exactly. */
  37596. bool operator== (const MarkerList& other) const noexcept;
  37597. /** Returns true if not all the markers in these two lists match exactly. */
  37598. bool operator!= (const MarkerList& other) const noexcept;
  37599. /**
  37600. A class for receiving events when changes are made to a MarkerList.
  37601. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37602. method, and it will be called when markers are moved, added, or deleted.
  37603. @see MarkerList::addListener, MarkerList::removeListener
  37604. */
  37605. class JUCE_API Listener
  37606. {
  37607. public:
  37608. /** Destructor. */
  37609. virtual ~Listener() {}
  37610. /** Called when something in the given marker list changes. */
  37611. virtual void markersChanged (MarkerList* markerList) = 0;
  37612. /** Called when the given marker list is being deleted. */
  37613. virtual void markerListBeingDeleted (MarkerList* markerList);
  37614. };
  37615. /** Registers a listener that will be called when the markers are changed. */
  37616. void addListener (Listener* listener);
  37617. /** Deregisters a previously-registered listener. */
  37618. void removeListener (Listener* listener);
  37619. /** Synchronously calls markersChanged() on all the registered listeners. */
  37620. void markersHaveChanged();
  37621. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37622. class ValueTreeWrapper
  37623. {
  37624. public:
  37625. ValueTreeWrapper (const ValueTree& state);
  37626. ValueTree& getState() noexcept { return state; }
  37627. int getNumMarkers() const;
  37628. const ValueTree getMarkerState (int index) const;
  37629. const ValueTree getMarkerState (const String& name) const;
  37630. bool containsMarker (const ValueTree& state) const;
  37631. const MarkerList::Marker getMarker (const ValueTree& state) const;
  37632. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37633. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37634. void applyTo (MarkerList& markerList);
  37635. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37636. static const Identifier markerTag, nameProperty, posProperty;
  37637. private:
  37638. ValueTree state;
  37639. };
  37640. private:
  37641. OwnedArray<Marker> markers;
  37642. ListenerList<Listener> listeners;
  37643. JUCE_LEAK_DETECTOR (MarkerList);
  37644. };
  37645. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37646. /*** End of inlined file: juce_MarkerList.h ***/
  37647. /**
  37648. Base class for Component::Positioners that are based upon relative coordinates.
  37649. */
  37650. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37651. public ComponentListener,
  37652. public MarkerList::Listener
  37653. {
  37654. public:
  37655. RelativeCoordinatePositionerBase (Component& component_);
  37656. ~RelativeCoordinatePositionerBase();
  37657. void componentMovedOrResized (Component&, bool, bool);
  37658. void componentParentHierarchyChanged (Component&);
  37659. void componentChildrenChanged (Component& component);
  37660. void componentBeingDeleted (Component& component);
  37661. void markersChanged (MarkerList*);
  37662. void markerListBeingDeleted (MarkerList* markerList);
  37663. void apply();
  37664. bool addCoordinate (const RelativeCoordinate& coord);
  37665. bool addPoint (const RelativePoint& point);
  37666. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37667. class ComponentScope : public Expression::Scope
  37668. {
  37669. public:
  37670. ComponentScope (Component& component_);
  37671. const Expression getSymbolValue (const String& symbol) const;
  37672. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37673. const String getScopeUID() const;
  37674. protected:
  37675. Component& component;
  37676. Component* findSiblingComponent (const String& componentID) const;
  37677. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37678. private:
  37679. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37680. };
  37681. protected:
  37682. virtual bool registerCoordinates() = 0;
  37683. virtual void applyToComponentBounds() = 0;
  37684. private:
  37685. class DependencyFinderScope;
  37686. friend class DependencyFinderScope;
  37687. Array <Component*> sourceComponents;
  37688. Array <MarkerList*> sourceMarkerLists;
  37689. bool registeredOk;
  37690. void registerComponentListener (Component& comp);
  37691. void registerMarkerListListener (MarkerList* const list);
  37692. void unregisterListeners();
  37693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37694. };
  37695. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37696. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37697. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37698. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37699. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37700. /**
  37701. Loads and maintains a tree of Components from a ValueTree that represents them.
  37702. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37703. this class lets you register a set of type-handlers for the different components that
  37704. are involved, and then uses these types to re-create a set of components from its
  37705. stored state.
  37706. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37707. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37708. all the items in your tree. Then you can call getComponent() to build the component.
  37709. Once you've got the component you can either take it and delete the ComponentBuilder
  37710. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37711. ValueTree and automatically update the component to reflect these changes.
  37712. */
  37713. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37714. {
  37715. public:
  37716. /** Creates a ComponentBuilder that will use the given state.
  37717. Once you've created your builder, you should use registerTypeHandler() to register some
  37718. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37719. to get the actual component.
  37720. */
  37721. explicit ComponentBuilder (const ValueTree& state);
  37722. /** Destructor. */
  37723. ~ComponentBuilder();
  37724. /** Returns the ValueTree that this builder is working with. */
  37725. ValueTree& getState() noexcept { return state; }
  37726. /** Returns the ValueTree that this builder is working with. */
  37727. const ValueTree& getState() const noexcept { return state; }
  37728. /** Returns the builder's component (creating it if necessary).
  37729. The first time that this method is called, the builder will attempt to create a component
  37730. from the ValueTree, so you must have registered some suitable type handlers before calling
  37731. this. If there's a problem and the component can't be created, this method returns 0.
  37732. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37733. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37734. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37735. call createComponent() instead.
  37736. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37737. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37738. as they may be changed or removed.
  37739. */
  37740. Component* getManagedComponent();
  37741. /** Creates and returns a new instance of the component that the ValueTree represents.
  37742. The caller is responsible for using and deleting the object that is returned. Unlike
  37743. getManagedComponent(), the component that is returned will not be updated by the builder.
  37744. */
  37745. Component* createComponent();
  37746. /**
  37747. The class is a base class for objects that manage the loading of a type of component
  37748. from a ValueTree.
  37749. To store and re-load a tree of components as a ValueTree, each component type must have
  37750. a TypeHandler to represent it.
  37751. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37752. */
  37753. class JUCE_API TypeHandler
  37754. {
  37755. public:
  37756. /** Creates a TypeHandler.
  37757. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37758. */
  37759. explicit TypeHandler (const Identifier& valueTreeType);
  37760. /** Destructor. */
  37761. virtual ~TypeHandler();
  37762. /** Returns the type of the ValueTrees that this handler can parse. */
  37763. const Identifier& getType() const noexcept { return valueTreeType; }
  37764. /** Returns the builder that this type is registered with. */
  37765. ComponentBuilder* getBuilder() const noexcept;
  37766. /** This method must create a new component from the given state, add it to the specified
  37767. parent component (which may be null), and return it.
  37768. The ValueTree will have been pre-checked to make sure that its type matches the type
  37769. that this handler supports.
  37770. There's no need to set the new Component's ID to match that of the state - the builder
  37771. will take care of that itself.
  37772. */
  37773. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37774. /** This method must update an existing component from a new ValueTree state.
  37775. A component that has been created with addNewComponentFromState() may need to be updated
  37776. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37777. whatever's necessary to update the component from the new state provided.
  37778. The ValueTree will have been pre-checked to make sure that its type matches the type
  37779. that this handler supports, and the component will have been created by this type's
  37780. addNewComponentFromState() method.
  37781. */
  37782. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37783. private:
  37784. friend class ComponentBuilder;
  37785. ComponentBuilder* builder;
  37786. const Identifier valueTreeType;
  37787. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37788. };
  37789. /** Adds a type handler that the builder can use when trying to load components.
  37790. @see Drawable::registerDrawableTypeHandlers()
  37791. */
  37792. void registerTypeHandler (TypeHandler* type);
  37793. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37794. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37795. /** Returns the number of registered type handlers.
  37796. @see getHandler, registerTypeHandler
  37797. */
  37798. int getNumHandlers() const noexcept;
  37799. /** Returns one of the registered type handlers.
  37800. @see getNumHandlers, registerTypeHandler
  37801. */
  37802. TypeHandler* getHandler (int index) const noexcept;
  37803. /** This class is used when references to images need to be stored in ValueTrees.
  37804. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37805. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37806. your app.
  37807. When you're loading components from a ValueTree that may need a way of loading images, you
  37808. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37809. trying to load the component.
  37810. @see ComponentBuilder::setImageProvider()
  37811. */
  37812. class JUCE_API ImageProvider
  37813. {
  37814. public:
  37815. ImageProvider() {}
  37816. virtual ~ImageProvider() {}
  37817. /** Retrieves the image associated with this identifier, which could be any
  37818. kind of string, number, filename, etc.
  37819. The image that is returned will be owned by the caller, but it may come
  37820. from the ImageCache.
  37821. */
  37822. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37823. /** Returns an identifier to be used to refer to a given image.
  37824. This is used when a reference to an image is stored in a ValueTree.
  37825. */
  37826. virtual const var getIdentifierForImage (const Image& image) = 0;
  37827. };
  37828. /** Gives the builder an ImageProvider object that the type handlers can use when
  37829. loading images from stored references.
  37830. The object that is passed in is not owned by the builder, so the caller must delete
  37831. it when it is no longer needed, but not while the builder may still be using it. To
  37832. clear the image provider, just call setImageProvider (nullptr).
  37833. */
  37834. void setImageProvider (ImageProvider* newImageProvider) noexcept;
  37835. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37836. ImageProvider* getImageProvider() const noexcept;
  37837. /** Updates the children of a parent component by updating them from the children of
  37838. a given ValueTree.
  37839. */
  37840. void updateChildComponents (Component& parent, const ValueTree& children);
  37841. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37842. for that component.
  37843. */
  37844. static const Identifier idProperty;
  37845. /** @internal */
  37846. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37847. /** @internal */
  37848. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37849. /** @internal */
  37850. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37851. /** @internal */
  37852. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37853. /** @internal */
  37854. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37855. private:
  37856. ValueTree state;
  37857. OwnedArray <TypeHandler> types;
  37858. ScopedPointer<Component> component;
  37859. ImageProvider* imageProvider;
  37860. #if JUCE_DEBUG
  37861. WeakReference<Component> componentRef;
  37862. #endif
  37863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37864. };
  37865. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37866. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37867. class DrawableComposite;
  37868. /**
  37869. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37870. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37871. */
  37872. class JUCE_API Drawable : public Component
  37873. {
  37874. protected:
  37875. /** The base class can't be instantiated directly.
  37876. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37877. */
  37878. Drawable();
  37879. public:
  37880. /** Destructor. */
  37881. virtual ~Drawable();
  37882. /** Creates a deep copy of this Drawable object.
  37883. Use this to create a new copy of this and any sub-objects in the tree.
  37884. */
  37885. virtual Drawable* createCopy() const = 0;
  37886. /** Renders this Drawable object.
  37887. Note that the preferred way to render a drawable in future is by using it
  37888. as a component and adding it to a parent, so you might want to consider that
  37889. before using this method.
  37890. @see drawWithin
  37891. */
  37892. void draw (Graphics& g, float opacity,
  37893. const AffineTransform& transform = AffineTransform::identity) const;
  37894. /** Renders the Drawable at a given offset within the Graphics context.
  37895. The co-ordinates passed-in are used to translate the object relative to its own
  37896. origin before drawing it - this is basically a quick way of saying:
  37897. @code
  37898. draw (g, AffineTransform::translation (x, y)).
  37899. @endcode
  37900. Note that the preferred way to render a drawable in future is by using it
  37901. as a component and adding it to a parent, so you might want to consider that
  37902. before using this method.
  37903. */
  37904. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37905. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37906. changing its aspect-ratio.
  37907. The object can placed arbitrarily within the rectangle based on a Justification type,
  37908. and can either be made as big as possible, or just reduced to fit.
  37909. Note that the preferred way to render a drawable in future is by using it
  37910. as a component and adding it to a parent, so you might want to consider that
  37911. before using this method.
  37912. @param g the graphics context to render onto
  37913. @param destArea the target rectangle to fit the drawable into
  37914. @param placement defines the alignment and rescaling to use to fit
  37915. this object within the target rectangle.
  37916. @param opacity the opacity to use, in the range 0 to 1.0
  37917. */
  37918. void drawWithin (Graphics& g,
  37919. const Rectangle<float>& destArea,
  37920. const RectanglePlacement& placement,
  37921. float opacity) const;
  37922. /** Resets any transformations on this drawable, and positions its origin within
  37923. its parent component.
  37924. */
  37925. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37926. /** Sets a transform for this drawable that will position it within the specified
  37927. area of its parent component.
  37928. */
  37929. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37930. /** Returns the DrawableComposite that contains this object, if there is one. */
  37931. DrawableComposite* getParent() const;
  37932. /** Tries to turn some kind of image file into a drawable.
  37933. The data could be an image that the ImageFileFormat class understands, or it
  37934. could be SVG.
  37935. */
  37936. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37937. /** Tries to turn a stream containing some kind of image data into a drawable.
  37938. The data could be an image that the ImageFileFormat class understands, or it
  37939. could be SVG.
  37940. */
  37941. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37942. /** Tries to turn a file containing some kind of image data into a drawable.
  37943. The data could be an image that the ImageFileFormat class understands, or it
  37944. could be SVG.
  37945. */
  37946. static Drawable* createFromImageFile (const File& file);
  37947. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37948. into a Drawable tree.
  37949. The object returned must be deleted by the caller. If something goes wrong
  37950. while parsing, it may return 0.
  37951. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37952. implementation, but it can return the basic vector objects.
  37953. */
  37954. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37955. /** Tries to create a Drawable from a previously-saved ValueTree.
  37956. The ValueTree must have been created by the createValueTree() method.
  37957. If there are any images used within the drawable, you'll need to provide a valid
  37958. ImageProvider object that can be used to retrieve these images from whatever type
  37959. of identifier is used to represent them.
  37960. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37961. */
  37962. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37963. /** Creates a ValueTree to represent this Drawable.
  37964. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37965. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37966. object that can be used to create storable representations of them.
  37967. */
  37968. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37969. /** Returns the area that this drawble covers.
  37970. The result is expressed in this drawable's own coordinate space, and does not take
  37971. into account any transforms that may be applied to the component.
  37972. */
  37973. virtual const Rectangle<float> getDrawableBounds() const = 0;
  37974. /** Internal class used to manage ValueTrees that represent Drawables. */
  37975. class ValueTreeWrapperBase
  37976. {
  37977. public:
  37978. ValueTreeWrapperBase (const ValueTree& state);
  37979. ValueTree& getState() noexcept { return state; }
  37980. const String getID() const;
  37981. void setID (const String& newID);
  37982. ValueTree state;
  37983. };
  37984. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37985. load all the different Drawable types from a saved state.
  37986. @see ComponentBuilder::registerTypeHandler()
  37987. */
  37988. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37989. protected:
  37990. friend class DrawableComposite;
  37991. friend class DrawableShape;
  37992. /** @internal */
  37993. void transformContextToCorrectOrigin (Graphics& g);
  37994. /** @internal */
  37995. void parentHierarchyChanged();
  37996. /** @internal */
  37997. void setBoundsToEnclose (const Rectangle<float>& area);
  37998. Point<int> originRelativeToComponent;
  37999. #ifndef DOXYGEN
  38000. /** Internal utility class used by Drawables. */
  38001. template <class DrawableType>
  38002. class Positioner : public RelativeCoordinatePositionerBase
  38003. {
  38004. public:
  38005. Positioner (DrawableType& component_)
  38006. : RelativeCoordinatePositionerBase (component_),
  38007. owner (component_)
  38008. {}
  38009. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  38010. void applyToComponentBounds()
  38011. {
  38012. ComponentScope scope (getComponent());
  38013. owner.recalculateCoordinates (&scope);
  38014. }
  38015. void applyNewBounds (const Rectangle<int>&)
  38016. {
  38017. jassertfalse; // drawables can't be resized directly!
  38018. }
  38019. private:
  38020. DrawableType& owner;
  38021. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  38022. };
  38023. #endif
  38024. private:
  38025. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  38026. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  38027. };
  38028. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  38029. /*** End of inlined file: juce_Drawable.h ***/
  38030. /**
  38031. A button that displays a Drawable.
  38032. Up to three Drawable objects can be given to this button, to represent the
  38033. 'normal', 'over' and 'down' states.
  38034. @see Button
  38035. */
  38036. class JUCE_API DrawableButton : public Button
  38037. {
  38038. public:
  38039. enum ButtonStyle
  38040. {
  38041. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  38042. ImageRaw, /**< The button will just display the images in their normal size and position.
  38043. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  38044. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  38045. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  38046. };
  38047. /** Creates a DrawableButton.
  38048. After creating one of these, use setImages() to specify the drawables to use.
  38049. @param buttonName the name to give the component
  38050. @param buttonStyle the layout to use
  38051. @see ButtonStyle, setButtonStyle, setImages
  38052. */
  38053. DrawableButton (const String& buttonName,
  38054. ButtonStyle buttonStyle);
  38055. /** Destructor. */
  38056. ~DrawableButton();
  38057. /** Sets up the images to draw for the various button states.
  38058. The button will keep its own internal copies of these drawables.
  38059. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  38060. will be made of the object passed-in if it is non-zero.
  38061. @param overImage the thing to draw for the button's 'over' state - if this is
  38062. zero, the button's normal image will be used when the mouse is
  38063. over it. An internal copy will be made of the object passed-in
  38064. if it is non-zero.
  38065. @param downImage the thing to draw for the button's 'down' state - if this is
  38066. zero, the 'over' image will be used instead (or the normal image
  38067. as a last resort). An internal copy will be made of the object
  38068. passed-in if it is non-zero.
  38069. @param disabledImage an image to draw when the button is disabled. If this is zero,
  38070. the normal image will be drawn with a reduced opacity instead.
  38071. An internal copy will be made of the object passed-in if it is
  38072. non-zero.
  38073. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  38074. state is 'on'. If this is 0, the normal image is used instead
  38075. @param overImageOn same as the overImage, but this is used when the button's toggle
  38076. state is 'on'. If this is 0, the normalImageOn is drawn instead
  38077. @param downImageOn same as the downImage, but this is used when the button's toggle
  38078. state is 'on'. If this is 0, the overImageOn is drawn instead
  38079. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  38080. state is 'on'. If this is 0, the normal image will be drawn instead
  38081. with a reduced opacity
  38082. */
  38083. void setImages (const Drawable* normalImage,
  38084. const Drawable* overImage = nullptr,
  38085. const Drawable* downImage = nullptr,
  38086. const Drawable* disabledImage = nullptr,
  38087. const Drawable* normalImageOn = nullptr,
  38088. const Drawable* overImageOn = nullptr,
  38089. const Drawable* downImageOn = nullptr,
  38090. const Drawable* disabledImageOn = nullptr);
  38091. /** Changes the button's style.
  38092. @see ButtonStyle
  38093. */
  38094. void setButtonStyle (ButtonStyle newStyle);
  38095. /** Changes the button's background colours.
  38096. The toggledOffColour is the colour to use when the button's toggle state
  38097. is off, and toggledOnColour when it's on.
  38098. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  38099. used to fill the background of the component.
  38100. For an ImageOnButtonBackground style, the colour is used to draw the
  38101. button's lozenge shape and exactly how the colour's used will depend
  38102. on the LookAndFeel.
  38103. */
  38104. void setBackgroundColours (const Colour& toggledOffColour,
  38105. const Colour& toggledOnColour);
  38106. /** Returns the current background colour being used.
  38107. @see setBackgroundColour
  38108. */
  38109. const Colour& getBackgroundColour() const noexcept;
  38110. /** Gives the button an optional amount of space around the edge of the drawable.
  38111. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  38112. ones on a button background. If the button is too small for the given gap, a
  38113. smaller gap will be used.
  38114. By default there's a gap of about 3 pixels.
  38115. */
  38116. void setEdgeIndent (int numPixelsIndent);
  38117. /** Returns the image that the button is currently displaying. */
  38118. Drawable* getCurrentImage() const noexcept;
  38119. Drawable* getNormalImage() const noexcept;
  38120. Drawable* getOverImage() const noexcept;
  38121. Drawable* getDownImage() const noexcept;
  38122. /** A set of colour IDs to use to change the colour of various aspects of the link.
  38123. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38124. methods.
  38125. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38126. */
  38127. enum ColourIds
  38128. {
  38129. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  38130. };
  38131. protected:
  38132. /** @internal */
  38133. void paintButton (Graphics& g,
  38134. bool isMouseOverButton,
  38135. bool isButtonDown);
  38136. /** @internal */
  38137. void buttonStateChanged();
  38138. /** @internal */
  38139. void resized();
  38140. private:
  38141. ButtonStyle style;
  38142. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  38143. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  38144. Drawable* currentImage;
  38145. Colour backgroundOff, backgroundOn;
  38146. int edgeIndent;
  38147. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  38148. };
  38149. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  38150. /*** End of inlined file: juce_DrawableButton.h ***/
  38151. #endif
  38152. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38153. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  38154. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38155. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38156. /**
  38157. A button showing an underlined weblink, that will launch the link
  38158. when it's clicked.
  38159. @see Button
  38160. */
  38161. class JUCE_API HyperlinkButton : public Button
  38162. {
  38163. public:
  38164. /** Creates a HyperlinkButton.
  38165. @param linkText the text that will be displayed in the button - this is
  38166. also set as the Component's name, but the text can be
  38167. changed later with the Button::getButtonText() method
  38168. @param linkURL the URL to launch when the user clicks the button
  38169. */
  38170. HyperlinkButton (const String& linkText,
  38171. const URL& linkURL);
  38172. /** Destructor. */
  38173. ~HyperlinkButton();
  38174. /** Changes the font to use for the text.
  38175. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  38176. to match the size of the component.
  38177. */
  38178. void setFont (const Font& newFont,
  38179. bool resizeToMatchComponentHeight,
  38180. const Justification& justificationType = Justification::horizontallyCentred);
  38181. /** A set of colour IDs to use to change the colour of various aspects of the link.
  38182. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38183. methods.
  38184. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38185. */
  38186. enum ColourIds
  38187. {
  38188. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  38189. };
  38190. /** Changes the URL that the button will trigger. */
  38191. void setURL (const URL& newURL) noexcept;
  38192. /** Returns the URL that the button will trigger. */
  38193. const URL& getURL() const noexcept { return url; }
  38194. /** Resizes the button horizontally to fit snugly around the text.
  38195. This won't affect the button's height.
  38196. */
  38197. void changeWidthToFitText();
  38198. protected:
  38199. /** @internal */
  38200. void clicked();
  38201. /** @internal */
  38202. void colourChanged();
  38203. /** @internal */
  38204. void paintButton (Graphics& g,
  38205. bool isMouseOverButton,
  38206. bool isButtonDown);
  38207. private:
  38208. URL url;
  38209. Font font;
  38210. bool resizeFont;
  38211. Justification justification;
  38212. const Font getFontToUse() const;
  38213. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  38214. };
  38215. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38216. /*** End of inlined file: juce_HyperlinkButton.h ***/
  38217. #endif
  38218. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  38219. /*** Start of inlined file: juce_ImageButton.h ***/
  38220. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  38221. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  38222. /**
  38223. As the title suggests, this is a button containing an image.
  38224. The colour and transparency of the image can be set to vary when the
  38225. button state changes.
  38226. @see Button, ShapeButton, TextButton
  38227. */
  38228. class JUCE_API ImageButton : public Button
  38229. {
  38230. public:
  38231. /** Creates an ImageButton.
  38232. Use setImage() to specify the image to use. The colours and opacities that
  38233. are specified here can be changed later using setDrawingOptions().
  38234. @param name the name to give the component
  38235. */
  38236. explicit ImageButton (const String& name);
  38237. /** Destructor. */
  38238. ~ImageButton();
  38239. /** Sets up the images to draw in various states.
  38240. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  38241. resized to the same dimensions as the normal image
  38242. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  38243. button when the button's size changes
  38244. @param preserveImageProportions if true then any rescaling of the image to fit
  38245. the button will keep the image's x and y proportions
  38246. correct - i.e. it won't distort its shape, although
  38247. this might create gaps around the edges
  38248. @param normalImage the image to use when the button is in its normal state.
  38249. button no longer needs it.
  38250. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  38251. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  38252. normal image - if this colour is transparent, no overlay
  38253. will be drawn. The overlay will be drawn over the top of the
  38254. image, so you can basically add a solid or semi-transparent
  38255. colour to the image to brighten or darken it
  38256. @param overImage the image to use when the mouse is over the button. If
  38257. you want to use the same image as was set in the normalImage
  38258. parameter, this value can be a null image.
  38259. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  38260. is over the button
  38261. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  38262. image when the mouse is over - if this colour is transparent,
  38263. no overlay will be drawn
  38264. @param downImage an image to use when the button is pressed down. If set
  38265. to a null image, the 'over' image will be drawn instead (or the
  38266. normal image if there isn't an 'over' image either).
  38267. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  38268. is pressed
  38269. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  38270. image when the button is pressed down - if this colour is
  38271. transparent, no overlay will be drawn
  38272. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  38273. whenever it's inside the button's bounding rectangle. If
  38274. set to values higher than 0, the mouse will only be
  38275. considered to be over the image when the value of the
  38276. image's alpha channel at that position is greater than
  38277. this level.
  38278. */
  38279. void setImages (bool resizeButtonNowToFitThisImage,
  38280. bool rescaleImagesWhenButtonSizeChanges,
  38281. bool preserveImageProportions,
  38282. const Image& normalImage,
  38283. float imageOpacityWhenNormal,
  38284. const Colour& overlayColourWhenNormal,
  38285. const Image& overImage,
  38286. float imageOpacityWhenOver,
  38287. const Colour& overlayColourWhenOver,
  38288. const Image& downImage,
  38289. float imageOpacityWhenDown,
  38290. const Colour& overlayColourWhenDown,
  38291. float hitTestAlphaThreshold = 0.0f);
  38292. /** Returns the currently set 'normal' image. */
  38293. const Image getNormalImage() const;
  38294. /** Returns the image that's drawn when the mouse is over the button.
  38295. If a valid 'over' image has been set, this will return it; otherwise it'll
  38296. just return the normal image.
  38297. */
  38298. const Image getOverImage() const;
  38299. /** Returns the image that's drawn when the button is held down.
  38300. If a valid 'down' image has been set, this will return it; otherwise it'll
  38301. return the 'over' image or normal image, depending on what's available.
  38302. */
  38303. const Image getDownImage() const;
  38304. protected:
  38305. /** @internal */
  38306. bool hitTest (int x, int y);
  38307. /** @internal */
  38308. void paintButton (Graphics& g,
  38309. bool isMouseOverButton,
  38310. bool isButtonDown);
  38311. private:
  38312. bool scaleImageToFit, preserveProportions;
  38313. unsigned char alphaThreshold;
  38314. int imageX, imageY, imageW, imageH;
  38315. Image normalImage, overImage, downImage;
  38316. float normalOpacity, overOpacity, downOpacity;
  38317. Colour normalOverlay, overOverlay, downOverlay;
  38318. const Image getCurrentImage() const;
  38319. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  38320. };
  38321. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  38322. /*** End of inlined file: juce_ImageButton.h ***/
  38323. #endif
  38324. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  38325. /*** Start of inlined file: juce_ShapeButton.h ***/
  38326. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  38327. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  38328. /**
  38329. A button that contains a filled shape.
  38330. @see Button, ImageButton, TextButton, ArrowButton
  38331. */
  38332. class JUCE_API ShapeButton : public Button
  38333. {
  38334. public:
  38335. /** Creates a ShapeButton.
  38336. @param name a name to give the component - see Component::setName()
  38337. @param normalColour the colour to fill the shape with when the mouse isn't over
  38338. @param overColour the colour to use when the mouse is over the shape
  38339. @param downColour the colour to use when the button is in the pressed-down state
  38340. */
  38341. ShapeButton (const String& name,
  38342. const Colour& normalColour,
  38343. const Colour& overColour,
  38344. const Colour& downColour);
  38345. /** Destructor. */
  38346. ~ShapeButton();
  38347. /** Sets the shape to use.
  38348. @param newShape the shape to use
  38349. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  38350. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  38351. the button is resized
  38352. @param hasDropShadow if true, the button will be given a drop-shadow effect
  38353. */
  38354. void setShape (const Path& newShape,
  38355. bool resizeNowToFitThisShape,
  38356. bool maintainShapeProportions,
  38357. bool hasDropShadow);
  38358. /** Set the colours to use for drawing the shape.
  38359. @param normalColour the colour to fill the shape with when the mouse isn't over
  38360. @param overColour the colour to use when the mouse is over the shape
  38361. @param downColour the colour to use when the button is in the pressed-down state
  38362. */
  38363. void setColours (const Colour& normalColour,
  38364. const Colour& overColour,
  38365. const Colour& downColour);
  38366. /** Sets up an outline to draw around the shape.
  38367. @param outlineColour the colour to use
  38368. @param outlineStrokeWidth the thickness of line to draw
  38369. */
  38370. void setOutline (const Colour& outlineColour,
  38371. float outlineStrokeWidth);
  38372. protected:
  38373. /** @internal */
  38374. void paintButton (Graphics& g,
  38375. bool isMouseOverButton,
  38376. bool isButtonDown);
  38377. private:
  38378. Colour normalColour, overColour, downColour, outlineColour;
  38379. DropShadowEffect shadow;
  38380. Path shape;
  38381. bool maintainShapeProportions;
  38382. float outlineWidth;
  38383. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  38384. };
  38385. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  38386. /*** End of inlined file: juce_ShapeButton.h ***/
  38387. #endif
  38388. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  38389. #endif
  38390. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38391. /*** Start of inlined file: juce_ToggleButton.h ***/
  38392. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38393. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38394. /**
  38395. A button that can be toggled on/off.
  38396. All buttons can be toggle buttons, but this lets you create one of the
  38397. standard ones which has a tick-box and a text label next to it.
  38398. @see Button, DrawableButton, TextButton
  38399. */
  38400. class JUCE_API ToggleButton : public Button
  38401. {
  38402. public:
  38403. /** Creates a ToggleButton.
  38404. @param buttonText the text to put in the button (the component's name is also
  38405. initially set to this string, but these can be changed later
  38406. using the setName() and setButtonText() methods)
  38407. */
  38408. explicit ToggleButton (const String& buttonText = String::empty);
  38409. /** Destructor. */
  38410. ~ToggleButton();
  38411. /** Resizes the button to fit neatly around its current text.
  38412. The button's height won't be affected, only its width.
  38413. */
  38414. void changeWidthToFitText();
  38415. /** A set of colour IDs to use to change the colour of various aspects of the button.
  38416. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38417. methods.
  38418. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38419. */
  38420. enum ColourIds
  38421. {
  38422. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  38423. };
  38424. protected:
  38425. /** @internal */
  38426. void paintButton (Graphics& g,
  38427. bool isMouseOverButton,
  38428. bool isButtonDown);
  38429. /** @internal */
  38430. void colourChanged();
  38431. private:
  38432. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  38433. };
  38434. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38435. /*** End of inlined file: juce_ToggleButton.h ***/
  38436. #endif
  38437. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38438. /*** Start of inlined file: juce_ToolbarButton.h ***/
  38439. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38440. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38441. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  38442. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38443. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38444. /*** Start of inlined file: juce_Toolbar.h ***/
  38445. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  38446. #define __JUCE_TOOLBAR_JUCEHEADER__
  38447. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  38448. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38449. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38450. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  38451. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38452. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38453. /**
  38454. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  38455. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  38456. derive your component from this class, and make sure that it is somewhere inside a
  38457. DragAndDropContainer component.
  38458. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38459. the operating system onto your component, you don't need any of these classes: instead
  38460. see the FileDragAndDropTarget class.
  38461. @see DragAndDropContainer, FileDragAndDropTarget
  38462. */
  38463. class JUCE_API DragAndDropTarget
  38464. {
  38465. public:
  38466. /** Destructor. */
  38467. virtual ~DragAndDropTarget() {}
  38468. /** Callback to check whether this target is interested in the type of object being
  38469. dragged.
  38470. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38471. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38472. @returns true if this component wants to receive the other callbacks regarging this
  38473. type of object; if it returns false, no other callbacks will be made.
  38474. */
  38475. virtual bool isInterestedInDragSource (const String& sourceDescription,
  38476. Component* sourceComponent) = 0;
  38477. /** Callback to indicate that something is being dragged over this component.
  38478. This gets called when the user moves the mouse into this component while dragging
  38479. something.
  38480. Use this callback as a trigger to make your component repaint itself to give the
  38481. user feedback about whether the item can be dropped here or not.
  38482. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38483. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38484. @param x the mouse x position, relative to this component
  38485. @param y the mouse y position, relative to this component
  38486. @see itemDragExit
  38487. */
  38488. virtual void itemDragEnter (const String& sourceDescription,
  38489. Component* sourceComponent,
  38490. int x, int y);
  38491. /** Callback to indicate that the user is dragging something over this component.
  38492. This gets called when the user moves the mouse over this component while dragging
  38493. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  38494. this lets you know what happens in-between.
  38495. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38496. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38497. @param x the mouse x position, relative to this component
  38498. @param y the mouse y position, relative to this component
  38499. */
  38500. virtual void itemDragMove (const String& sourceDescription,
  38501. Component* sourceComponent,
  38502. int x, int y);
  38503. /** Callback to indicate that something has been dragged off the edge of this component.
  38504. This gets called when the user moves the mouse out of this component while dragging
  38505. something.
  38506. If you've used itemDragEnter() to repaint your component and give feedback, use this
  38507. as a signal to repaint it in its normal state.
  38508. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38509. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38510. @see itemDragEnter
  38511. */
  38512. virtual void itemDragExit (const String& sourceDescription,
  38513. Component* sourceComponent);
  38514. /** Callback to indicate that the user has dropped something onto this component.
  38515. When the user drops an item this get called, and you can use the description to
  38516. work out whether your object wants to deal with it or not.
  38517. Note that after this is called, the itemDragExit method may not be called, so you should
  38518. clean up in here if there's anything you need to do when the drag finishes.
  38519. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38520. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38521. @param x the mouse x position, relative to this component
  38522. @param y the mouse y position, relative to this component
  38523. */
  38524. virtual void itemDropped (const String& sourceDescription,
  38525. Component* sourceComponent,
  38526. int x, int y) = 0;
  38527. /** Overriding this allows the target to tell the drag container whether to
  38528. draw the drag image while the cursor is over it.
  38529. By default it returns true, but if you return false, then the normal drag
  38530. image will not be shown when the cursor is over this target.
  38531. */
  38532. virtual bool shouldDrawDragImageWhenOver();
  38533. };
  38534. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38535. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  38536. /**
  38537. Enables drag-and-drop behaviour for a component and all its sub-components.
  38538. For a component to be able to make or receive drag-and-drop events, one of its parent
  38539. components must derive from this class. It's probably best for the top-level
  38540. component to implement it.
  38541. Then to start a drag operation, any sub-component can just call the startDragging()
  38542. method, and this object will take over, tracking the mouse and sending appropriate
  38543. callbacks to any child components derived from DragAndDropTarget which the mouse
  38544. moves over.
  38545. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38546. the operating system onto your component, you don't need any of these classes: you can do this
  38547. simply by overriding Component::filesDropped().
  38548. @see DragAndDropTarget
  38549. */
  38550. class JUCE_API DragAndDropContainer
  38551. {
  38552. public:
  38553. /** Creates a DragAndDropContainer.
  38554. The object that derives from this class must also be a Component.
  38555. */
  38556. DragAndDropContainer();
  38557. /** Destructor. */
  38558. virtual ~DragAndDropContainer();
  38559. /** Begins a drag-and-drop operation.
  38560. This starts a drag-and-drop operation - call it when the user drags the
  38561. mouse in your drag-source component, and this object will track mouse
  38562. movements until the user lets go of the mouse button, and will send
  38563. appropriate messages to DragAndDropTarget objects that the mouse moves
  38564. over.
  38565. findParentDragContainerFor() is a handy method to call to find the
  38566. drag container to use for a component.
  38567. @param sourceDescription a string to use as the description of the thing being
  38568. dragged - this will be passed to the objects that might be
  38569. dropped-onto so they can decide if they want to handle it or
  38570. not
  38571. @param sourceComponent the component that is being dragged
  38572. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  38573. a snapshot of the sourceComponent will be used instead.
  38574. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  38575. window, and can be dragged to DragAndDropTargets that are the
  38576. children of components other than this one.
  38577. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  38578. at which the image should be drawn from the mouse. If it isn't
  38579. specified, then the image will be centred around the mouse. If
  38580. an image hasn't been passed-in, this will be ignored.
  38581. */
  38582. void startDragging (const String& sourceDescription,
  38583. Component* sourceComponent,
  38584. const Image& dragImage = Image::null,
  38585. bool allowDraggingToOtherJuceWindows = false,
  38586. const Point<int>* imageOffsetFromMouse = nullptr);
  38587. /** Returns true if something is currently being dragged. */
  38588. bool isDragAndDropActive() const;
  38589. /** Returns the description of the thing that's currently being dragged.
  38590. If nothing's being dragged, this will return an empty string, otherwise it's the
  38591. string that was passed into startDragging().
  38592. @see startDragging
  38593. */
  38594. const String getCurrentDragDescription() const;
  38595. /** Utility to find the DragAndDropContainer for a given Component.
  38596. This will search up this component's parent hierarchy looking for the first
  38597. parent component which is a DragAndDropContainer.
  38598. It's useful when a component wants to call startDragging but doesn't know
  38599. the DragAndDropContainer it should to use.
  38600. Obviously this may return 0 if it doesn't find a suitable component.
  38601. */
  38602. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38603. /** This performs a synchronous drag-and-drop of a set of files to some external
  38604. application.
  38605. You can call this function in response to a mouseDrag callback, and it will
  38606. block, running its own internal message loop and tracking the mouse, while it
  38607. uses a native operating system drag-and-drop operation to move or copy some
  38608. files to another application.
  38609. @param files a list of filenames to drag
  38610. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38611. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38612. @returns true if the files were successfully dropped somewhere, or false if it
  38613. was interrupted
  38614. @see performExternalDragDropOfText
  38615. */
  38616. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38617. /** This performs a synchronous drag-and-drop of a block of text to some external
  38618. application.
  38619. You can call this function in response to a mouseDrag callback, and it will
  38620. block, running its own internal message loop and tracking the mouse, while it
  38621. uses a native operating system drag-and-drop operation to move or copy some
  38622. text to another application.
  38623. @param text the text to copy
  38624. @returns true if the text was successfully dropped somewhere, or false if it
  38625. was interrupted
  38626. @see performExternalDragDropOfFiles
  38627. */
  38628. static bool performExternalDragDropOfText (const String& text);
  38629. protected:
  38630. /** Override this if you want to be able to perform an external drag a set of files
  38631. when the user drags outside of this container component.
  38632. This method will be called when a drag operation moves outside the Juce-based window,
  38633. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38634. to the array passed in, and return true.
  38635. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  38636. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  38637. @param files on return, the filenames you want to drag
  38638. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38639. it must make a copy of them (see the performExternalDragDropOfFiles()
  38640. method)
  38641. @see performExternalDragDropOfFiles
  38642. */
  38643. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  38644. Component* dragSourceComponent,
  38645. StringArray& files,
  38646. bool& canMoveFiles);
  38647. private:
  38648. friend class DragImageComponent;
  38649. ScopedPointer <Component> dragImageComponent;
  38650. String currentDragDesc;
  38651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38652. };
  38653. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38654. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38655. class ToolbarItemComponent;
  38656. class ToolbarItemFactory;
  38657. /**
  38658. A toolbar component.
  38659. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38660. and looks after their order and layout.
  38661. Items (icon buttons or other custom components) are added to a toolbar using a
  38662. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38663. toolbar might contain more than one instance of a particular item type.
  38664. Toolbars can be interactively customised, allowing the user to drag the items
  38665. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38666. component as a source of new items.
  38667. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38668. */
  38669. class JUCE_API Toolbar : public Component,
  38670. public DragAndDropContainer,
  38671. public DragAndDropTarget,
  38672. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38673. {
  38674. public:
  38675. /** Creates an empty toolbar component.
  38676. To add some icons or other components to your toolbar, you'll need to
  38677. create a ToolbarItemFactory class that can create a suitable set of
  38678. ToolbarItemComponents.
  38679. @see ToolbarItemFactory, ToolbarItemComponents
  38680. */
  38681. Toolbar();
  38682. /** Destructor.
  38683. Any items on the bar will be deleted when the toolbar is deleted.
  38684. */
  38685. ~Toolbar();
  38686. /** Changes the bar's orientation.
  38687. @see isVertical
  38688. */
  38689. void setVertical (bool shouldBeVertical);
  38690. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38691. You can change the bar's orientation with setVertical().
  38692. */
  38693. bool isVertical() const noexcept { return vertical; }
  38694. /** Returns the depth of the bar.
  38695. If the bar is horizontal, this will return its height; if it's vertical, it
  38696. will return its width.
  38697. @see getLength
  38698. */
  38699. int getThickness() const noexcept;
  38700. /** Returns the length of the bar.
  38701. If the bar is horizontal, this will return its width; if it's vertical, it
  38702. will return its height.
  38703. @see getThickness
  38704. */
  38705. int getLength() const noexcept;
  38706. /** Deletes all items from the bar.
  38707. */
  38708. void clear();
  38709. /** Adds an item to the toolbar.
  38710. The factory's ToolbarItemFactory::createItem() will be called by this method
  38711. to create the component that will actually be added to the bar.
  38712. The new item will be inserted at the specified index (if the index is -1, it
  38713. will be added to the right-hand or bottom end of the bar).
  38714. Once added, the component will be automatically deleted by this object when it
  38715. is no longer needed.
  38716. @see ToolbarItemFactory
  38717. */
  38718. void addItem (ToolbarItemFactory& factory,
  38719. int itemId,
  38720. int insertIndex = -1);
  38721. /** Deletes one of the items from the bar.
  38722. */
  38723. void removeToolbarItem (int itemIndex);
  38724. /** Returns the number of items currently on the toolbar.
  38725. @see getItemId, getItemComponent
  38726. */
  38727. int getNumItems() const noexcept;
  38728. /** Returns the ID of the item with the given index.
  38729. If the index is less than zero or greater than the number of items,
  38730. this will return 0.
  38731. @see getNumItems
  38732. */
  38733. int getItemId (int itemIndex) const noexcept;
  38734. /** Returns the component being used for the item with the given index.
  38735. If the index is less than zero or greater than the number of items,
  38736. this will return 0.
  38737. @see getNumItems
  38738. */
  38739. ToolbarItemComponent* getItemComponent (int itemIndex) const noexcept;
  38740. /** Clears this toolbar and adds to it the default set of items that the specified
  38741. factory creates.
  38742. @see ToolbarItemFactory::getDefaultItemSet
  38743. */
  38744. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38745. /** Options for the way items should be displayed.
  38746. @see setStyle, getStyle
  38747. */
  38748. enum ToolbarItemStyle
  38749. {
  38750. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38751. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38752. textOnly /**< Means that the toolbar only display text labels for each item. */
  38753. };
  38754. /** Returns the toolbar's current style.
  38755. @see ToolbarItemStyle, setStyle
  38756. */
  38757. ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38758. /** Changes the toolbar's current style.
  38759. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38760. */
  38761. void setStyle (const ToolbarItemStyle& newStyle);
  38762. /** Flags used by the showCustomisationDialog() method. */
  38763. enum CustomisationFlags
  38764. {
  38765. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38766. show the "icons only" option on its choice of toolbar styles. */
  38767. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38768. show the "icons with text" option on its choice of toolbar styles. */
  38769. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38770. show the "text only" option on its choice of toolbar styles. */
  38771. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38772. show a button to reset the toolbar to its default set of items. */
  38773. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38774. };
  38775. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38776. The dialog contains a ToolbarItemPalette and various controls for editing other
  38777. aspects of the toolbar. This method will block and run the dialog box modally,
  38778. returning when the user closes it.
  38779. The factory is used to determine the set of items that will be shown on the
  38780. palette.
  38781. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38782. enum.
  38783. @see ToolbarItemPalette
  38784. */
  38785. void showCustomisationDialog (ToolbarItemFactory& factory,
  38786. int optionFlags = allCustomisationOptionsEnabled);
  38787. /** Turns on or off the toolbar's editing mode, in which its items can be
  38788. rearranged by the user.
  38789. (In most cases it's easier just to use showCustomisationDialog() instead of
  38790. trying to enable editing directly).
  38791. @see ToolbarItemPalette
  38792. */
  38793. void setEditingActive (bool editingEnabled);
  38794. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38795. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38796. methods.
  38797. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38798. */
  38799. enum ColourIds
  38800. {
  38801. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38802. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38803. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38804. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38805. over them. */
  38806. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38807. held down on them. */
  38808. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38809. when the style is set to iconsWithText or textOnly. */
  38810. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38811. the customisation dialog is active and the mouse moves over them. */
  38812. };
  38813. /** Returns a string that represents the toolbar's current set of items.
  38814. This lets you later restore the same item layout using restoreFromString().
  38815. @see restoreFromString
  38816. */
  38817. const String toString() const;
  38818. /** Restores a set of items that was previously stored in a string by the toString()
  38819. method.
  38820. The factory object is used to create any item components that are needed.
  38821. @see toString
  38822. */
  38823. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38824. const String& savedVersion);
  38825. /** @internal */
  38826. void paint (Graphics& g);
  38827. /** @internal */
  38828. void resized();
  38829. /** @internal */
  38830. void buttonClicked (Button*);
  38831. /** @internal */
  38832. void mouseDown (const MouseEvent&);
  38833. /** @internal */
  38834. bool isInterestedInDragSource (const String&, Component*);
  38835. /** @internal */
  38836. void itemDragMove (const String&, Component*, int, int);
  38837. /** @internal */
  38838. void itemDragExit (const String&, Component*);
  38839. /** @internal */
  38840. void itemDropped (const String&, Component*, int, int);
  38841. /** @internal */
  38842. void updateAllItemPositions (bool animate);
  38843. /** @internal */
  38844. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38845. private:
  38846. ScopedPointer<Button> missingItemsButton;
  38847. bool vertical, isEditingActive;
  38848. ToolbarItemStyle toolbarStyle;
  38849. class MissingItemsComponent;
  38850. friend class MissingItemsComponent;
  38851. OwnedArray <ToolbarItemComponent> items;
  38852. friend class ItemDragAndDropOverlayComponent;
  38853. static const char* const toolbarDragDescriptor;
  38854. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38855. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38856. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38857. };
  38858. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38859. /*** End of inlined file: juce_Toolbar.h ***/
  38860. class ItemDragAndDropOverlayComponent;
  38861. /**
  38862. A component that can be used as one of the items in a Toolbar.
  38863. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38864. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38865. class for further info about creating them.
  38866. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38867. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38868. calling the constructor, and override contentAreaChanged(), in which you can position
  38869. any sub-components you need to add.
  38870. To add basic buttons without writing a special subclass, have a look at the
  38871. ToolbarButton class.
  38872. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38873. */
  38874. class JUCE_API ToolbarItemComponent : public Button
  38875. {
  38876. public:
  38877. /** Constructor.
  38878. @param itemId the ID of the type of toolbar item which this represents
  38879. @param labelText the text to display if the toolbar's style is set to
  38880. Toolbar::iconsWithText or Toolbar::textOnly
  38881. @param isBeingUsedAsAButton set this to false if you don't want the button
  38882. to draw itself with button over/down states when the mouse
  38883. moves over it or clicks
  38884. */
  38885. ToolbarItemComponent (int itemId,
  38886. const String& labelText,
  38887. bool isBeingUsedAsAButton);
  38888. /** Destructor. */
  38889. ~ToolbarItemComponent();
  38890. /** Returns the item type ID that this component represents.
  38891. This value is in the constructor.
  38892. */
  38893. int getItemId() const noexcept { return itemId; }
  38894. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38895. inside one.
  38896. */
  38897. Toolbar* getToolbar() const;
  38898. /** Returns true if this component is currently inside a toolbar which is vertical.
  38899. @see Toolbar::isVertical
  38900. */
  38901. bool isToolbarVertical() const;
  38902. /** Returns the current style setting of this item.
  38903. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38904. @see setStyle, Toolbar::getStyle
  38905. */
  38906. Toolbar::ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38907. /** Changes the current style setting of this item.
  38908. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38909. by the toolbar that holds this item.
  38910. @see setStyle, Toolbar::setStyle
  38911. */
  38912. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38913. /** Returns the area of the component that should be used to display the button image or
  38914. other contents of the item.
  38915. This content area may change when the item's style changes, and may leave a space around the
  38916. edge of the component where the text label can be shown.
  38917. @see contentAreaChanged
  38918. */
  38919. const Rectangle<int> getContentArea() const noexcept { return contentArea; }
  38920. /** This method must return the size criteria for this item, based on a given toolbar
  38921. size and orientation.
  38922. The preferredSize, minSize and maxSize values must all be set by your implementation
  38923. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38924. toolbar, they refer to the item's height.
  38925. The preferredSize is the size that the component would like to be, and this must be
  38926. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38927. the same value.
  38928. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38929. Toolbar::getThickness().
  38930. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38931. vertically.
  38932. */
  38933. virtual bool getToolbarItemSizes (int toolbarThickness,
  38934. bool isToolbarVertical,
  38935. int& preferredSize,
  38936. int& minSize,
  38937. int& maxSize) = 0;
  38938. /** Your subclass should use this method to draw its content area.
  38939. The graphics object that is passed-in will have been clipped and had its origin
  38940. moved to fit the content area as specified get getContentArea(). The width and height
  38941. parameters are the width and height of the content area.
  38942. If the component you're writing isn't a button, you can just do nothing in this method.
  38943. */
  38944. virtual void paintButtonArea (Graphics& g,
  38945. int width, int height,
  38946. bool isMouseOver, bool isMouseDown) = 0;
  38947. /** Callback to indicate that the content area of this item has changed.
  38948. This might be because the component was resized, or because the style changed and
  38949. the space needed for the text label is different.
  38950. See getContentArea() for a description of what the area is.
  38951. */
  38952. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38953. /** Editing modes.
  38954. These are used by setEditingMode(), but will be rarely needed in user code.
  38955. */
  38956. enum ToolbarEditingMode
  38957. {
  38958. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38959. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38960. customisation mode, and the items can be dragged around. */
  38961. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38962. dragged onto a toolbar to add it to that bar.*/
  38963. };
  38964. /** Changes the editing mode of this component.
  38965. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38966. and is unlikely to be of much use in end-user-code.
  38967. */
  38968. void setEditingMode (const ToolbarEditingMode newMode);
  38969. /** Returns the current editing mode of this component.
  38970. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38971. and is unlikely to be of much use in end-user-code.
  38972. */
  38973. ToolbarEditingMode getEditingMode() const noexcept { return mode; }
  38974. /** @internal */
  38975. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38976. /** @internal */
  38977. void resized();
  38978. private:
  38979. friend class Toolbar;
  38980. friend class ItemDragAndDropOverlayComponent;
  38981. const int itemId;
  38982. ToolbarEditingMode mode;
  38983. Toolbar::ToolbarItemStyle toolbarStyle;
  38984. ScopedPointer <Component> overlayComp;
  38985. int dragOffsetX, dragOffsetY;
  38986. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38987. Rectangle<int> contentArea;
  38988. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38989. };
  38990. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38991. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38992. /**
  38993. A type of button designed to go on a toolbar.
  38994. This simple button can have two Drawable objects specified - one for normal
  38995. use and another one (optionally) for the button's "on" state if it's a
  38996. toggle button.
  38997. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38998. */
  38999. class JUCE_API ToolbarButton : public ToolbarItemComponent
  39000. {
  39001. public:
  39002. /** Creates a ToolbarButton.
  39003. @param itemId the ID for this toolbar item type. This is passed through to the
  39004. ToolbarItemComponent constructor
  39005. @param labelText the text to display on the button (if the toolbar is using a style
  39006. that shows text labels). This is passed through to the
  39007. ToolbarItemComponent constructor
  39008. @param normalImage a drawable object that the button should use as its icon. The object
  39009. that is passed-in here will be kept by this object and will be
  39010. deleted when no longer needed or when this button is deleted.
  39011. @param toggledOnImage a drawable object that the button can use as its icon if the button
  39012. is in a toggled-on state (see the Button::getToggleState() method). If
  39013. 0 is passed-in here, then the normal image will be used instead, regardless
  39014. of the toggle state. The object that is passed-in here will be kept by
  39015. this object and will be deleted when no longer needed or when this button
  39016. is deleted.
  39017. */
  39018. ToolbarButton (int itemId,
  39019. const String& labelText,
  39020. Drawable* normalImage,
  39021. Drawable* toggledOnImage);
  39022. /** Destructor. */
  39023. ~ToolbarButton();
  39024. /** @internal */
  39025. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  39026. int& minSize, int& maxSize);
  39027. /** @internal */
  39028. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  39029. /** @internal */
  39030. void contentAreaChanged (const Rectangle<int>& newBounds);
  39031. /** @internal */
  39032. void buttonStateChanged();
  39033. /** @internal */
  39034. void resized();
  39035. /** @internal */
  39036. void enablementChanged();
  39037. private:
  39038. ScopedPointer<Drawable> normalImage, toggledOnImage;
  39039. Drawable* currentImage;
  39040. void updateDrawable();
  39041. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  39042. };
  39043. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  39044. /*** End of inlined file: juce_ToolbarButton.h ***/
  39045. #endif
  39046. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  39047. /*** Start of inlined file: juce_CodeDocument.h ***/
  39048. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  39049. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  39050. class CodeDocumentLine;
  39051. /**
  39052. A class for storing and manipulating a source code file.
  39053. When using a CodeEditorComponent, it takes one of these as its source object.
  39054. The CodeDocument stores its content as an array of lines, which makes it
  39055. quick to insert and delete.
  39056. @see CodeEditorComponent
  39057. */
  39058. class JUCE_API CodeDocument
  39059. {
  39060. public:
  39061. /** Creates a new, empty document.
  39062. */
  39063. CodeDocument();
  39064. /** Destructor. */
  39065. ~CodeDocument();
  39066. /** A position in a code document.
  39067. Using this class you can find a position in a code document and quickly get its
  39068. character position, line, and index. By calling setPositionMaintained (true), the
  39069. position is automatically updated when text is inserted or deleted in the document,
  39070. so that it maintains its original place in the text.
  39071. */
  39072. class JUCE_API Position
  39073. {
  39074. public:
  39075. /** Creates an uninitialised postion.
  39076. Don't attempt to call any methods on this until you've given it an owner document
  39077. to refer to!
  39078. */
  39079. Position() noexcept;
  39080. /** Creates a position based on a line and index in a document.
  39081. Note that this index is NOT the column number, it's the number of characters from the
  39082. start of the line. The "column" number isn't quite the same, because if the line
  39083. contains any tab characters, the relationship of the index to its visual column depends on
  39084. the number of spaces per tab being used!
  39085. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  39086. they will be adjusted to keep them within its limits.
  39087. */
  39088. Position (const CodeDocument* ownerDocument,
  39089. int line, int indexInLine) noexcept;
  39090. /** Creates a position based on a character index in a document.
  39091. This position is placed at the specified number of characters from the start of the
  39092. document. The line and column are auto-calculated.
  39093. If the position is beyond the range of the document, it'll be adjusted to keep it
  39094. inside.
  39095. */
  39096. Position (const CodeDocument* ownerDocument,
  39097. int charactersFromStartOfDocument) noexcept;
  39098. /** Creates a copy of another position.
  39099. This will copy the position, but the new object will not be set to maintain its position,
  39100. even if the source object was set to do so.
  39101. */
  39102. Position (const Position& other) noexcept;
  39103. /** Destructor. */
  39104. ~Position();
  39105. Position& operator= (const Position& other);
  39106. bool operator== (const Position& other) const noexcept;
  39107. bool operator!= (const Position& other) const noexcept;
  39108. /** Points this object at a new position within the document.
  39109. If the position is beyond the range of the document, it'll be adjusted to keep it
  39110. inside.
  39111. @see getPosition, setLineAndIndex
  39112. */
  39113. void setPosition (int charactersFromStartOfDocument);
  39114. /** Returns the position as the number of characters from the start of the document.
  39115. @see setPosition, getLineNumber, getIndexInLine
  39116. */
  39117. int getPosition() const noexcept { return characterPos; }
  39118. /** Moves the position to a new line and index within the line.
  39119. Note that the index is NOT the column at which the position appears in an editor.
  39120. If the line contains any tab characters, the relationship of the index to its
  39121. visual position depends on the number of spaces per tab being used!
  39122. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  39123. they will be adjusted to keep them within its limits.
  39124. */
  39125. void setLineAndIndex (int newLine, int newIndexInLine);
  39126. /** Returns the line number of this position.
  39127. The first line in the document is numbered zero, not one!
  39128. */
  39129. int getLineNumber() const noexcept { return line; }
  39130. /** Returns the number of characters from the start of the line.
  39131. Note that this value is NOT the column at which the position appears in an editor.
  39132. If the line contains any tab characters, the relationship of the index to its
  39133. visual position depends on the number of spaces per tab being used!
  39134. */
  39135. int getIndexInLine() const noexcept { return indexInLine; }
  39136. /** Allows the position to be automatically updated when the document changes.
  39137. If this is set to true, the positon will register with its document so that
  39138. when the document has text inserted or deleted, this position will be automatically
  39139. moved to keep it at the same position in the text.
  39140. */
  39141. void setPositionMaintained (bool isMaintained);
  39142. /** Moves the position forwards or backwards by the specified number of characters.
  39143. @see movedBy
  39144. */
  39145. void moveBy (int characterDelta);
  39146. /** Returns a position which is the same as this one, moved by the specified number of
  39147. characters.
  39148. @see moveBy
  39149. */
  39150. const Position movedBy (int characterDelta) const;
  39151. /** Returns a position which is the same as this one, moved up or down by the specified
  39152. number of lines.
  39153. @see movedBy
  39154. */
  39155. const Position movedByLines (int deltaLines) const;
  39156. /** Returns the character in the document at this position.
  39157. @see getLineText
  39158. */
  39159. const juce_wchar getCharacter() const;
  39160. /** Returns the line from the document that this position is within.
  39161. @see getCharacter, getLineNumber
  39162. */
  39163. const String getLineText() const;
  39164. private:
  39165. CodeDocument* owner;
  39166. int characterPos, line, indexInLine;
  39167. bool positionMaintained;
  39168. };
  39169. /** Returns the full text of the document. */
  39170. const String getAllContent() const;
  39171. /** Returns a section of the document's text. */
  39172. const String getTextBetween (const Position& start, const Position& end) const;
  39173. /** Returns a line from the document. */
  39174. const String getLine (int lineIndex) const noexcept;
  39175. /** Returns the number of characters in the document. */
  39176. int getNumCharacters() const noexcept;
  39177. /** Returns the number of lines in the document. */
  39178. int getNumLines() const noexcept { return lines.size(); }
  39179. /** Returns the number of characters in the longest line of the document. */
  39180. int getMaximumLineLength() noexcept;
  39181. /** Deletes a section of the text.
  39182. This operation is undoable.
  39183. */
  39184. void deleteSection (const Position& startPosition, const Position& endPosition);
  39185. /** Inserts some text into the document at a given position.
  39186. This operation is undoable.
  39187. */
  39188. void insertText (const Position& position, const String& text);
  39189. /** Clears the document and replaces it with some new text.
  39190. This operation is undoable - if you're trying to completely reset the document, you
  39191. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  39192. */
  39193. void replaceAllContent (const String& newContent);
  39194. /** Replaces the editor's contents with the contents of a stream.
  39195. This will also reset the undo history and save point marker.
  39196. */
  39197. bool loadFromStream (InputStream& stream);
  39198. /** Writes the editor's current contents to a stream. */
  39199. bool writeToStream (OutputStream& stream);
  39200. /** Returns the preferred new-line characters for the document.
  39201. This will be either "\n", "\r\n", or (rarely) "\r".
  39202. @see setNewLineCharacters
  39203. */
  39204. const String getNewLineCharacters() const noexcept { return newLineChars; }
  39205. /** Sets the new-line characters that the document should use.
  39206. The string must be either "\n", "\r\n", or (rarely) "\r".
  39207. @see getNewLineCharacters
  39208. */
  39209. void setNewLineCharacters (const String& newLine) noexcept;
  39210. /** Begins a new undo transaction.
  39211. The document itself will not call this internally, so relies on whatever is using the
  39212. document to periodically call this to break up the undo sequence into sensible chunks.
  39213. @see UndoManager::beginNewTransaction
  39214. */
  39215. void newTransaction();
  39216. /** Undo the last operation.
  39217. @see UndoManager::undo
  39218. */
  39219. void undo();
  39220. /** Redo the last operation.
  39221. @see UndoManager::redo
  39222. */
  39223. void redo();
  39224. /** Clears the undo history.
  39225. @see UndoManager::clearUndoHistory
  39226. */
  39227. void clearUndoHistory();
  39228. /** Returns the document's UndoManager */
  39229. UndoManager& getUndoManager() noexcept { return undoManager; }
  39230. /** Makes a note that the document's current state matches the one that is saved.
  39231. After this has been called, hasChangedSinceSavePoint() will return false until
  39232. the document has been altered, and then it'll start returning true. If the document is
  39233. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  39234. will again return false.
  39235. @see hasChangedSinceSavePoint
  39236. */
  39237. void setSavePoint() noexcept;
  39238. /** Returns true if the state of the document differs from the state it was in when
  39239. setSavePoint() was last called.
  39240. @see setSavePoint
  39241. */
  39242. bool hasChangedSinceSavePoint() const noexcept;
  39243. /** Searches for a word-break. */
  39244. const Position findWordBreakAfter (const Position& position) const noexcept;
  39245. /** Searches for a word-break. */
  39246. const Position findWordBreakBefore (const Position& position) const noexcept;
  39247. /** An object that receives callbacks from the CodeDocument when its text changes.
  39248. @see CodeDocument::addListener, CodeDocument::removeListener
  39249. */
  39250. class JUCE_API Listener
  39251. {
  39252. public:
  39253. Listener() {}
  39254. virtual ~Listener() {}
  39255. /** Called by a CodeDocument when it is altered.
  39256. */
  39257. virtual void codeDocumentChanged (const Position& affectedTextStart,
  39258. const Position& affectedTextEnd) = 0;
  39259. };
  39260. /** Registers a listener object to receive callbacks when the document changes.
  39261. If the listener is already registered, this method has no effect.
  39262. @see removeListener
  39263. */
  39264. void addListener (Listener* listener) noexcept;
  39265. /** Deregisters a listener.
  39266. @see addListener
  39267. */
  39268. void removeListener (Listener* listener) noexcept;
  39269. /** Iterates the text in a CodeDocument.
  39270. This class lets you read characters from a CodeDocument. It's designed to be used
  39271. by a SyntaxAnalyser object.
  39272. @see CodeDocument, SyntaxAnalyser
  39273. */
  39274. class JUCE_API Iterator
  39275. {
  39276. public:
  39277. Iterator (CodeDocument* document);
  39278. Iterator (const Iterator& other);
  39279. Iterator& operator= (const Iterator& other) noexcept;
  39280. ~Iterator() noexcept;
  39281. /** Reads the next character and returns it.
  39282. @see peekNextChar
  39283. */
  39284. juce_wchar nextChar();
  39285. /** Reads the next character without advancing the current position. */
  39286. juce_wchar peekNextChar() const;
  39287. /** Advances the position by one character. */
  39288. void skip();
  39289. /** Returns the position of the next character as its position within the
  39290. whole document.
  39291. */
  39292. int getPosition() const noexcept { return position; }
  39293. /** Skips over any whitespace characters until the next character is non-whitespace. */
  39294. void skipWhitespace();
  39295. /** Skips forward until the next character will be the first character on the next line */
  39296. void skipToEndOfLine();
  39297. /** Returns the line number of the next character. */
  39298. int getLine() const noexcept { return line; }
  39299. /** Returns true if the iterator has reached the end of the document. */
  39300. bool isEOF() const noexcept;
  39301. private:
  39302. CodeDocument* document;
  39303. mutable String::CharPointerType charPointer;
  39304. int line, position;
  39305. };
  39306. private:
  39307. friend class CodeDocumentInsertAction;
  39308. friend class CodeDocumentDeleteAction;
  39309. friend class Iterator;
  39310. friend class Position;
  39311. OwnedArray <CodeDocumentLine> lines;
  39312. Array <Position*> positionsToMaintain;
  39313. UndoManager undoManager;
  39314. int currentActionIndex, indexOfSavedState;
  39315. int maximumLineLength;
  39316. ListenerList <Listener> listeners;
  39317. String newLineChars;
  39318. void sendListenerChangeMessage (int startLine, int endLine);
  39319. void insert (const String& text, int insertPos, bool undoable);
  39320. void remove (int startPos, int endPos, bool undoable);
  39321. void checkLastLineStatus();
  39322. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  39323. };
  39324. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  39325. /*** End of inlined file: juce_CodeDocument.h ***/
  39326. #endif
  39327. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39328. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  39329. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39330. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39331. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  39332. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39333. #define __JUCE_CODETOKENISER_JUCEHEADER__
  39334. /**
  39335. A base class for tokenising code so that the syntax can be displayed in a
  39336. code editor.
  39337. @see CodeDocument, CodeEditorComponent
  39338. */
  39339. class JUCE_API CodeTokeniser
  39340. {
  39341. public:
  39342. CodeTokeniser() {}
  39343. virtual ~CodeTokeniser() {}
  39344. /** Reads the next token from the source and returns its token type.
  39345. This must leave the source pointing to the first character in the
  39346. next token.
  39347. */
  39348. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  39349. /** Returns a list of the names of the token types this analyser uses.
  39350. The index in this list must match the token type numbers that are
  39351. returned by readNextToken().
  39352. */
  39353. virtual const StringArray getTokenTypes() = 0;
  39354. /** Returns a suggested syntax highlighting colour for a specified
  39355. token type.
  39356. */
  39357. virtual const Colour getDefaultColour (int tokenType) = 0;
  39358. private:
  39359. JUCE_LEAK_DETECTOR (CodeTokeniser);
  39360. };
  39361. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  39362. /*** End of inlined file: juce_CodeTokeniser.h ***/
  39363. /**
  39364. A text editor component designed specifically for source code.
  39365. This is designed to handle syntax highlighting and fast editing of very large
  39366. files.
  39367. */
  39368. class JUCE_API CodeEditorComponent : public Component,
  39369. public TextInputTarget,
  39370. public Timer,
  39371. public ScrollBar::Listener,
  39372. public CodeDocument::Listener,
  39373. public AsyncUpdater
  39374. {
  39375. public:
  39376. /** Creates an editor for a document.
  39377. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  39378. The object that you pass in is not owned or deleted by the editor - you must
  39379. make sure that it doesn't get deleted while this component is still using it.
  39380. @see CodeDocument
  39381. */
  39382. CodeEditorComponent (CodeDocument& document,
  39383. CodeTokeniser* codeTokeniser);
  39384. /** Destructor. */
  39385. ~CodeEditorComponent();
  39386. /** Returns the code document that this component is editing. */
  39387. CodeDocument& getDocument() const noexcept { return document; }
  39388. /** Loads the given content into the document.
  39389. This will completely reset the CodeDocument object, clear its undo history,
  39390. and fill it with this text.
  39391. */
  39392. void loadContent (const String& newContent);
  39393. /** Returns the standard character width. */
  39394. float getCharWidth() const noexcept { return charWidth; }
  39395. /** Returns the height of a line of text, in pixels. */
  39396. int getLineHeight() const noexcept { return lineHeight; }
  39397. /** Returns the number of whole lines visible on the screen,
  39398. This doesn't include a cut-off line that might be visible at the bottom if the
  39399. component's height isn't an exact multiple of the line-height.
  39400. */
  39401. int getNumLinesOnScreen() const noexcept { return linesOnScreen; }
  39402. /** Returns the number of whole columns visible on the screen.
  39403. This doesn't include any cut-off columns at the right-hand edge.
  39404. */
  39405. int getNumColumnsOnScreen() const noexcept { return columnsOnScreen; }
  39406. /** Returns the current caret position. */
  39407. const CodeDocument::Position getCaretPos() const { return caretPos; }
  39408. /** Returns the position of the caret, relative to the editor's origin. */
  39409. const Rectangle<int> getCaretRectangle();
  39410. /** Moves the caret.
  39411. If selecting is true, the section of the document between the current
  39412. caret position and the new one will become selected. If false, any currently
  39413. selected region will be deselected.
  39414. */
  39415. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  39416. /** Returns the on-screen position of a character in the document.
  39417. The rectangle returned is relative to this component's top-left origin.
  39418. */
  39419. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  39420. /** Finds the character at a given on-screen position.
  39421. The co-ordinates are relative to this component's top-left origin.
  39422. */
  39423. const CodeDocument::Position getPositionAt (int x, int y);
  39424. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  39425. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  39426. void cursorDown (bool selecting);
  39427. void cursorUp (bool selecting);
  39428. void pageDown (bool selecting);
  39429. void pageUp (bool selecting);
  39430. void scrollDown();
  39431. void scrollUp();
  39432. void scrollToLine (int newFirstLineOnScreen);
  39433. void scrollBy (int deltaLines);
  39434. void scrollToColumn (int newFirstColumnOnScreen);
  39435. void scrollToKeepCaretOnScreen();
  39436. void goToStartOfDocument (bool selecting);
  39437. void goToStartOfLine (bool selecting);
  39438. void goToEndOfDocument (bool selecting);
  39439. void goToEndOfLine (bool selecting);
  39440. void deselectAll();
  39441. void selectAll();
  39442. void insertTextAtCaret (const String& textToInsert);
  39443. void insertTabAtCaret();
  39444. void cut();
  39445. void copy();
  39446. void copyThenCut();
  39447. void paste();
  39448. void backspace (bool moveInWholeWordSteps);
  39449. void deleteForward (bool moveInWholeWordSteps);
  39450. void undo();
  39451. void redo();
  39452. const Range<int> getHighlightedRegion() const;
  39453. void setHighlightedRegion (const Range<int>& newRange);
  39454. const String getTextInRange (const Range<int>& range) const;
  39455. /** Changes the current tab settings.
  39456. This lets you change the tab size and whether pressing the tab key inserts a
  39457. tab character, or its equivalent number of spaces.
  39458. */
  39459. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  39460. /** Returns the current number of spaces per tab.
  39461. @see setTabSize
  39462. */
  39463. int getTabSize() const noexcept { return spacesPerTab; }
  39464. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  39465. @see setTabSize
  39466. */
  39467. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  39468. /** Changes the font.
  39469. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  39470. */
  39471. void setFont (const Font& newFont);
  39472. /** Returns the font that the editor is using. */
  39473. const Font& getFont() const noexcept { return font; }
  39474. /** Resets the syntax highlighting colours to the default ones provided by the
  39475. code tokeniser.
  39476. @see CodeTokeniser::getDefaultColour
  39477. */
  39478. void resetToDefaultColours();
  39479. /** Changes one of the syntax highlighting colours.
  39480. The token type values are dependent on the tokeniser being used - use
  39481. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39482. @see getColourForTokenType
  39483. */
  39484. void setColourForTokenType (int tokenType, const Colour& colour);
  39485. /** Returns one of the syntax highlighting colours.
  39486. The token type values are dependent on the tokeniser being used - use
  39487. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39488. @see setColourForTokenType
  39489. */
  39490. const Colour getColourForTokenType (int tokenType) const;
  39491. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39492. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39493. methods.
  39494. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39495. */
  39496. enum ColourIds
  39497. {
  39498. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  39499. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  39500. selected text. */
  39501. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  39502. enabled. */
  39503. };
  39504. /** Changes the size of the scrollbars. */
  39505. void setScrollbarThickness (int thickness);
  39506. /** Returns the thickness of the scrollbars. */
  39507. int getScrollbarThickness() const noexcept { return scrollbarThickness; }
  39508. /** @internal */
  39509. void resized();
  39510. /** @internal */
  39511. void paint (Graphics& g);
  39512. /** @internal */
  39513. bool keyPressed (const KeyPress& key);
  39514. /** @internal */
  39515. void mouseDown (const MouseEvent& e);
  39516. /** @internal */
  39517. void mouseDrag (const MouseEvent& e);
  39518. /** @internal */
  39519. void mouseUp (const MouseEvent& e);
  39520. /** @internal */
  39521. void mouseDoubleClick (const MouseEvent& e);
  39522. /** @internal */
  39523. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39524. /** @internal */
  39525. void focusGained (FocusChangeType cause);
  39526. /** @internal */
  39527. void focusLost (FocusChangeType cause);
  39528. /** @internal */
  39529. void timerCallback();
  39530. /** @internal */
  39531. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  39532. /** @internal */
  39533. void handleAsyncUpdate();
  39534. /** @internal */
  39535. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  39536. const CodeDocument::Position& affectedTextEnd);
  39537. /** @internal */
  39538. bool isTextInputActive() const;
  39539. /** @internal */
  39540. void setTemporaryUnderlining (const Array <Range<int> >&);
  39541. private:
  39542. CodeDocument& document;
  39543. Font font;
  39544. int firstLineOnScreen, gutter, spacesPerTab;
  39545. float charWidth;
  39546. int lineHeight, linesOnScreen, columnsOnScreen;
  39547. int scrollbarThickness, columnToTryToMaintain;
  39548. bool useSpacesForTabs;
  39549. double xOffset;
  39550. CodeDocument::Position caretPos;
  39551. CodeDocument::Position selectionStart, selectionEnd;
  39552. ScopedPointer<CaretComponent> caret;
  39553. ScrollBar verticalScrollBar, horizontalScrollBar;
  39554. enum DragType
  39555. {
  39556. notDragging,
  39557. draggingSelectionStart,
  39558. draggingSelectionEnd
  39559. };
  39560. DragType dragType;
  39561. CodeTokeniser* codeTokeniser;
  39562. Array <Colour> coloursForTokenCategories;
  39563. class CodeEditorLine;
  39564. OwnedArray <CodeEditorLine> lines;
  39565. void rebuildLineTokens();
  39566. OwnedArray <CodeDocument::Iterator> cachedIterators;
  39567. void clearCachedIterators (int firstLineToBeInvalid);
  39568. void updateCachedIterators (int maxLineNum);
  39569. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  39570. void moveLineDelta (int delta, bool selecting);
  39571. void updateCaretPosition();
  39572. void updateScrollBars();
  39573. void scrollToLineInternal (int line);
  39574. void scrollToColumnInternal (double column);
  39575. void newTransaction();
  39576. int indexToColumn (int line, int index) const noexcept;
  39577. int columnToIndex (int line, int column) const noexcept;
  39578. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  39579. };
  39580. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39581. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  39582. #endif
  39583. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39584. #endif
  39585. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39586. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39587. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39588. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39589. /**
  39590. A simple lexical analyser for syntax colouring of C++ code.
  39591. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  39592. */
  39593. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  39594. {
  39595. public:
  39596. CPlusPlusCodeTokeniser();
  39597. ~CPlusPlusCodeTokeniser();
  39598. enum TokenType
  39599. {
  39600. tokenType_error = 0,
  39601. tokenType_comment,
  39602. tokenType_builtInKeyword,
  39603. tokenType_identifier,
  39604. tokenType_integerLiteral,
  39605. tokenType_floatLiteral,
  39606. tokenType_stringLiteral,
  39607. tokenType_operator,
  39608. tokenType_bracket,
  39609. tokenType_punctuation,
  39610. tokenType_preprocessor
  39611. };
  39612. int readNextToken (CodeDocument::Iterator& source);
  39613. const StringArray getTokenTypes();
  39614. const Colour getDefaultColour (int tokenType);
  39615. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39616. static bool isReservedKeyword (const String& token) noexcept;
  39617. private:
  39618. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39619. };
  39620. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39621. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39622. #endif
  39623. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39624. #endif
  39625. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39626. /*** Start of inlined file: juce_ImageComponent.h ***/
  39627. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39628. #define __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39629. /**
  39630. A component that simply displays an image.
  39631. Use setImage to give it an image, and it'll display it - simple as that!
  39632. */
  39633. class JUCE_API ImageComponent : public Component,
  39634. public SettableTooltipClient
  39635. {
  39636. public:
  39637. /** Creates an ImageComponent. */
  39638. ImageComponent (const String& componentName = String::empty);
  39639. /** Destructor. */
  39640. ~ImageComponent();
  39641. /** Sets the image that should be displayed. */
  39642. void setImage (const Image& newImage);
  39643. /** Sets the image that should be displayed, and its placement within the component. */
  39644. void setImage (const Image& newImage,
  39645. const RectanglePlacement& placementToUse);
  39646. /** Returns the current image. */
  39647. const Image getImage() const;
  39648. /** Sets the method of positioning that will be used to fit the image within the component's bounds.
  39649. By default the positioning is centred, and will fit the image inside the component's bounds
  39650. whilst keeping its aspect ratio correct, but you can change it to whatever layout you need.
  39651. */
  39652. void setImagePlacement (const RectanglePlacement& newPlacement);
  39653. /** Returns the current image placement. */
  39654. const RectanglePlacement getImagePlacement() const;
  39655. /** @internal */
  39656. void paint (Graphics& g);
  39657. private:
  39658. Image image;
  39659. RectanglePlacement placement;
  39660. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageComponent);
  39661. };
  39662. #endif // __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39663. /*** End of inlined file: juce_ImageComponent.h ***/
  39664. #endif
  39665. #ifndef __JUCE_LABEL_JUCEHEADER__
  39666. #endif
  39667. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  39668. #endif
  39669. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39670. /*** Start of inlined file: juce_ProgressBar.h ***/
  39671. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39672. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  39673. /**
  39674. A progress bar component.
  39675. To use this, just create one and make it visible. It'll run its own timer
  39676. to keep an eye on a variable that you give it, and will automatically
  39677. redraw itself when the variable changes.
  39678. For an easy way of running a background task with a dialog box showing its
  39679. progress, see the ThreadWithProgressWindow class.
  39680. @see ThreadWithProgressWindow
  39681. */
  39682. class JUCE_API ProgressBar : public Component,
  39683. public SettableTooltipClient,
  39684. private Timer
  39685. {
  39686. public:
  39687. /** Creates a ProgressBar.
  39688. @param progress pass in a reference to a double that you're going to
  39689. update with your task's progress. The ProgressBar will
  39690. monitor the value of this variable and will redraw itself
  39691. when the value changes. The range is from 0 to 1.0. Obviously
  39692. you'd better be careful not to delete this variable while the
  39693. ProgressBar still exists!
  39694. */
  39695. explicit ProgressBar (double& progress);
  39696. /** Destructor. */
  39697. ~ProgressBar();
  39698. /** Turns the percentage display on or off.
  39699. By default this is on, and the progress bar will display a text string showing
  39700. its current percentage.
  39701. */
  39702. void setPercentageDisplay (bool shouldDisplayPercentage);
  39703. /** Gives the progress bar a string to display inside it.
  39704. If you call this, it will turn off the percentage display.
  39705. @see setPercentageDisplay
  39706. */
  39707. void setTextToDisplay (const String& text);
  39708. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  39709. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39710. methods.
  39711. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39712. */
  39713. enum ColourIds
  39714. {
  39715. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  39716. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  39717. classes will probably use variations on this colour. */
  39718. };
  39719. protected:
  39720. /** @internal */
  39721. void paint (Graphics& g);
  39722. /** @internal */
  39723. void lookAndFeelChanged();
  39724. /** @internal */
  39725. void visibilityChanged();
  39726. /** @internal */
  39727. void colourChanged();
  39728. private:
  39729. double& progress;
  39730. double currentValue;
  39731. bool displayPercentage;
  39732. String displayedMessage, currentMessage;
  39733. uint32 lastCallbackTime;
  39734. void timerCallback();
  39735. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  39736. };
  39737. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  39738. /*** End of inlined file: juce_ProgressBar.h ***/
  39739. #endif
  39740. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39741. /*** Start of inlined file: juce_Slider.h ***/
  39742. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39743. #define __JUCE_SLIDER_JUCEHEADER__
  39744. #if JUCE_VC6
  39745. #define Listener LabelListener
  39746. #endif
  39747. /**
  39748. A slider control for changing a value.
  39749. The slider can be horizontal, vertical, or rotary, and can optionally have
  39750. a text-box inside it to show an editable display of the current value.
  39751. To use it, create a Slider object and use the setSliderStyle() method
  39752. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  39753. To define the values that it can be set to, see the setRange() and setValue() methods.
  39754. There are also lots of custom tweaks you can do by subclassing and overriding
  39755. some of the virtual methods, such as changing the scaling, changing the format of
  39756. the text display, custom ways of limiting the values, etc.
  39757. You can register Slider::Listener objects with a slider, and they'll be called when
  39758. the value changes.
  39759. @see Slider::Listener
  39760. */
  39761. class JUCE_API Slider : public Component,
  39762. public SettableTooltipClient,
  39763. public AsyncUpdater,
  39764. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  39765. public LabelListener,
  39766. public ValueListener
  39767. {
  39768. public:
  39769. /** Creates a slider.
  39770. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  39771. setRange(), etc.
  39772. */
  39773. explicit Slider (const String& componentName = String::empty);
  39774. /** Destructor. */
  39775. ~Slider();
  39776. /** The types of slider available.
  39777. @see setSliderStyle, setRotaryParameters
  39778. */
  39779. enum SliderStyle
  39780. {
  39781. LinearHorizontal, /**< A traditional horizontal slider. */
  39782. LinearVertical, /**< A traditional vertical slider. */
  39783. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  39784. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  39785. @see setRotaryParameters */
  39786. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  39787. @see setRotaryParameters */
  39788. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  39789. @see setRotaryParameters */
  39790. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  39791. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39792. @see setMinValue, setMaxValue */
  39793. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39794. @see setMinValue, setMaxValue */
  39795. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  39796. value, with the current value being somewhere between them.
  39797. @see setMinValue, setMaxValue */
  39798. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  39799. value, with the current value being somewhere between them.
  39800. @see setMinValue, setMaxValue */
  39801. };
  39802. /** Changes the type of slider interface being used.
  39803. @param newStyle the type of interface
  39804. @see setRotaryParameters, setVelocityBasedMode,
  39805. */
  39806. void setSliderStyle (SliderStyle newStyle);
  39807. /** Returns the slider's current style.
  39808. @see setSliderStyle
  39809. */
  39810. SliderStyle getSliderStyle() const noexcept { return style; }
  39811. /** Changes the properties of a rotary slider.
  39812. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  39813. the slider's minimum value is represented
  39814. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  39815. the slider's maximum value is represented. This must be
  39816. greater than startAngleRadians
  39817. @param stopAtEnd if true, then when the slider is dragged around past the
  39818. minimum or maximum, it'll stop there; if false, it'll wrap
  39819. back to the opposite value
  39820. */
  39821. void setRotaryParameters (float startAngleRadians,
  39822. float endAngleRadians,
  39823. bool stopAtEnd);
  39824. /** Sets the distance the mouse has to move to drag the slider across
  39825. the full extent of its range.
  39826. This only applies when in modes like RotaryHorizontalDrag, where it's using
  39827. relative mouse movements to adjust the slider.
  39828. */
  39829. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  39830. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  39831. int getMouseDragSensitivity() const noexcept { return pixelsForFullDragExtent; }
  39832. /** Changes the way the the mouse is used when dragging the slider.
  39833. If true, this will turn on velocity-sensitive dragging, so that
  39834. the faster the mouse moves, the bigger the movement to the slider. This
  39835. helps when making accurate adjustments if the slider's range is quite large.
  39836. If false, the slider will just try to snap to wherever the mouse is.
  39837. */
  39838. void setVelocityBasedMode (bool isVelocityBased);
  39839. /** Returns true if velocity-based mode is active.
  39840. @see setVelocityBasedMode
  39841. */
  39842. bool getVelocityBasedMode() const noexcept { return isVelocityBased; }
  39843. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  39844. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  39845. or if you're holding down ctrl.
  39846. @param sensitivity higher values than 1.0 increase the range of acceleration used
  39847. @param threshold the minimum number of pixels that the mouse needs to move for it
  39848. to be treated as a movement
  39849. @param offset values greater than 0.0 increase the minimum speed that will be used when
  39850. the threshold is reached
  39851. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  39852. key to toggle velocity-sensitive mode
  39853. */
  39854. void setVelocityModeParameters (double sensitivity = 1.0,
  39855. int threshold = 1,
  39856. double offset = 0.0,
  39857. bool userCanPressKeyToSwapMode = true);
  39858. /** Returns the velocity sensitivity setting.
  39859. @see setVelocityModeParameters
  39860. */
  39861. double getVelocitySensitivity() const noexcept { return velocityModeSensitivity; }
  39862. /** Returns the velocity threshold setting.
  39863. @see setVelocityModeParameters
  39864. */
  39865. int getVelocityThreshold() const noexcept { return velocityModeThreshold; }
  39866. /** Returns the velocity offset setting.
  39867. @see setVelocityModeParameters
  39868. */
  39869. double getVelocityOffset() const noexcept { return velocityModeOffset; }
  39870. /** Returns the velocity user key setting.
  39871. @see setVelocityModeParameters
  39872. */
  39873. bool getVelocityModeIsSwappable() const noexcept { return userKeyOverridesVelocity; }
  39874. /** Sets up a skew factor to alter the way values are distributed.
  39875. You may want to use a range of values on the slider where more accuracy
  39876. is required towards one end of the range, so this will logarithmically
  39877. spread the values across the length of the slider.
  39878. If the factor is < 1.0, the lower end of the range will fill more of the
  39879. slider's length; if the factor is > 1.0, the upper end of the range
  39880. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  39881. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  39882. method instead.
  39883. @see getSkewFactor, setSkewFactorFromMidPoint
  39884. */
  39885. void setSkewFactor (double factor);
  39886. /** Sets up a skew factor to alter the way values are distributed.
  39887. This allows you to specify the slider value that should appear in the
  39888. centre of the slider's visible range.
  39889. @see setSkewFactor, getSkewFactor
  39890. */
  39891. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  39892. /** Returns the current skew factor.
  39893. See setSkewFactor for more info.
  39894. @see setSkewFactor, setSkewFactorFromMidPoint
  39895. */
  39896. double getSkewFactor() const noexcept { return skewFactor; }
  39897. /** Used by setIncDecButtonsMode().
  39898. */
  39899. enum IncDecButtonMode
  39900. {
  39901. incDecButtonsNotDraggable,
  39902. incDecButtonsDraggable_AutoDirection,
  39903. incDecButtonsDraggable_Horizontal,
  39904. incDecButtonsDraggable_Vertical
  39905. };
  39906. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  39907. can be dragged on the buttons to drag the values.
  39908. By default this is turned off. When enabled, clicking on the buttons still works
  39909. them as normal, but by holding down the mouse on a button and dragging it a little
  39910. distance, it flips into a mode where the value can be dragged. The drag direction can
  39911. either be set explicitly to be vertical or horizontal, or can be set to
  39912. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  39913. are side-by-side or above each other.
  39914. */
  39915. void setIncDecButtonsMode (IncDecButtonMode mode);
  39916. /** The position of the slider's text-entry box.
  39917. @see setTextBoxStyle
  39918. */
  39919. enum TextEntryBoxPosition
  39920. {
  39921. NoTextBox, /**< Doesn't display a text box. */
  39922. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  39923. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  39924. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  39925. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  39926. };
  39927. /** Changes the location and properties of the text-entry box.
  39928. @param newPosition where it should go (or NoTextBox to not have one at all)
  39929. @param isReadOnly if true, it's a read-only display
  39930. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  39931. room for the slider as well!
  39932. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  39933. room for the slider as well!
  39934. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  39935. */
  39936. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  39937. bool isReadOnly,
  39938. int textEntryBoxWidth,
  39939. int textEntryBoxHeight);
  39940. /** Returns the status of the text-box.
  39941. @see setTextBoxStyle
  39942. */
  39943. const TextEntryBoxPosition getTextBoxPosition() const noexcept { return textBoxPos; }
  39944. /** Returns the width used for the text-box.
  39945. @see setTextBoxStyle
  39946. */
  39947. int getTextBoxWidth() const noexcept { return textBoxWidth; }
  39948. /** Returns the height used for the text-box.
  39949. @see setTextBoxStyle
  39950. */
  39951. int getTextBoxHeight() const noexcept { return textBoxHeight; }
  39952. /** Makes the text-box editable.
  39953. By default this is true, and the user can enter values into the textbox,
  39954. but it can be turned off if that's not suitable.
  39955. @see setTextBoxStyle, getValueFromText, getTextFromValue
  39956. */
  39957. void setTextBoxIsEditable (bool shouldBeEditable);
  39958. /** Returns true if the text-box is read-only.
  39959. @see setTextBoxStyle
  39960. */
  39961. bool isTextBoxEditable() const { return editableText; }
  39962. /** If the text-box is editable, this will give it the focus so that the user can
  39963. type directly into it.
  39964. This is basically the effect as the user clicking on it.
  39965. */
  39966. void showTextBox();
  39967. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  39968. focus away from it.
  39969. @param discardCurrentEditorContents if true, the slider's value will be left
  39970. unchanged; if false, the current contents of the
  39971. text editor will be used to set the slider position
  39972. before it is hidden.
  39973. */
  39974. void hideTextBox (bool discardCurrentEditorContents);
  39975. /** Changes the slider's current value.
  39976. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39977. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39978. want to handle it.
  39979. @param newValue the new value to set - this will be restricted by the
  39980. minimum and maximum range, and will be snapped to the
  39981. nearest interval if one has been set
  39982. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39983. any Slider::Listeners or the valueChanged() method
  39984. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39985. synchronously; if false, it will be asynchronous
  39986. */
  39987. void setValue (double newValue,
  39988. bool sendUpdateMessage = true,
  39989. bool sendMessageSynchronously = false);
  39990. /** Returns the slider's current value. */
  39991. double getValue() const;
  39992. /** Returns the Value object that represents the slider's current position.
  39993. You can use this Value object to connect the slider's position to external values or setters,
  39994. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39995. your own Value object.
  39996. @see Value, getMaxValue, getMinValueObject
  39997. */
  39998. Value& getValueObject() { return currentValue; }
  39999. /** Sets the limits that the slider's value can take.
  40000. @param newMinimum the lowest value allowed
  40001. @param newMaximum the highest value allowed
  40002. @param newInterval the steps in which the value is allowed to increase - if this
  40003. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  40004. */
  40005. void setRange (double newMinimum,
  40006. double newMaximum,
  40007. double newInterval = 0);
  40008. /** Returns the current maximum value.
  40009. @see setRange
  40010. */
  40011. double getMaximum() const { return maximum; }
  40012. /** Returns the current minimum value.
  40013. @see setRange
  40014. */
  40015. double getMinimum() const { return minimum; }
  40016. /** Returns the current step-size for values.
  40017. @see setRange
  40018. */
  40019. double getInterval() const { return interval; }
  40020. /** For a slider with two or three thumbs, this returns the lower of its values.
  40021. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40022. A slider with three values also uses the normal getValue() and setValue() methods to
  40023. control the middle value.
  40024. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40025. */
  40026. double getMinValue() const;
  40027. /** For a slider with two or three thumbs, this returns the lower of its values.
  40028. You can use this Value object to connect the slider's position to external values or setters,
  40029. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40030. your own Value object.
  40031. @see Value, getMinValue, getMaxValueObject
  40032. */
  40033. Value& getMinValueObject() noexcept { return valueMin; }
  40034. /** For a slider with two or three thumbs, this sets the lower of its values.
  40035. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40036. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40037. want to handle it.
  40038. @param newValue the new value to set - this will be restricted by the
  40039. minimum and maximum range, and will be snapped to the nearest
  40040. interval if one has been set.
  40041. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40042. any Slider::Listeners or the valueChanged() method
  40043. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40044. synchronously; if false, it will be asynchronous
  40045. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  40046. max value (in a two-value slider) or the mid value (in a three-value
  40047. slider). If false, then if this value goes beyond those values,
  40048. it will push them along with it.
  40049. @see getMinValue, setMaxValue, setValue
  40050. */
  40051. void setMinValue (double newValue,
  40052. bool sendUpdateMessage = true,
  40053. bool sendMessageSynchronously = false,
  40054. bool allowNudgingOfOtherValues = false);
  40055. /** For a slider with two or three thumbs, this returns the higher of its values.
  40056. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40057. A slider with three values also uses the normal getValue() and setValue() methods to
  40058. control the middle value.
  40059. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40060. */
  40061. double getMaxValue() const;
  40062. /** For a slider with two or three thumbs, this returns the higher of its values.
  40063. You can use this Value object to connect the slider's position to external values or setters,
  40064. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40065. your own Value object.
  40066. @see Value, getMaxValue, getMinValueObject
  40067. */
  40068. Value& getMaxValueObject() noexcept { return valueMax; }
  40069. /** For a slider with two or three thumbs, this sets the lower of its values.
  40070. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40071. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40072. want to handle it.
  40073. @param newValue the new value to set - this will be restricted by the
  40074. minimum and maximum range, and will be snapped to the nearest
  40075. interval if one has been set.
  40076. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40077. any Slider::Listeners or the valueChanged() method
  40078. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40079. synchronously; if false, it will be asynchronous
  40080. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  40081. min value (in a two-value slider) or the mid value (in a three-value
  40082. slider). If false, then if this value goes beyond those values,
  40083. it will push them along with it.
  40084. @see getMaxValue, setMinValue, setValue
  40085. */
  40086. void setMaxValue (double newValue,
  40087. bool sendUpdateMessage = true,
  40088. bool sendMessageSynchronously = false,
  40089. bool allowNudgingOfOtherValues = false);
  40090. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  40091. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40092. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40093. want to handle it.
  40094. @param newMinValue the new minimum value to set - this will be snapped to the
  40095. nearest interval if one has been set.
  40096. @param newMaxValue the new minimum value to set - this will be snapped to the
  40097. nearest interval if one has been set.
  40098. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40099. any Slider::Listeners or the valueChanged() method
  40100. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40101. synchronously; if false, it will be asynchronous
  40102. @see setMaxValue, setMinValue, setValue
  40103. */
  40104. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  40105. bool sendUpdateMessage = true,
  40106. bool sendMessageSynchronously = false);
  40107. /** A class for receiving callbacks from a Slider.
  40108. To be told when a slider's value changes, you can register a Slider::Listener
  40109. object using Slider::addListener().
  40110. @see Slider::addListener, Slider::removeListener
  40111. */
  40112. class JUCE_API Listener
  40113. {
  40114. public:
  40115. /** Destructor. */
  40116. virtual ~Listener() {}
  40117. /** Called when the slider's value is changed.
  40118. This may be caused by dragging it, or by typing in its text entry box,
  40119. or by a call to Slider::setValue().
  40120. You can find out the new value using Slider::getValue().
  40121. @see Slider::valueChanged
  40122. */
  40123. virtual void sliderValueChanged (Slider* slider) = 0;
  40124. /** Called when the slider is about to be dragged.
  40125. This is called when a drag begins, then it's followed by multiple calls
  40126. to sliderValueChanged(), and then sliderDragEnded() is called after the
  40127. user lets go.
  40128. @see sliderDragEnded, Slider::startedDragging
  40129. */
  40130. virtual void sliderDragStarted (Slider* slider);
  40131. /** Called after a drag operation has finished.
  40132. @see sliderDragStarted, Slider::stoppedDragging
  40133. */
  40134. virtual void sliderDragEnded (Slider* slider);
  40135. };
  40136. /** Adds a listener to be called when this slider's value changes. */
  40137. void addListener (Listener* listener);
  40138. /** Removes a previously-registered listener. */
  40139. void removeListener (Listener* listener);
  40140. /** This lets you choose whether double-clicking moves the slider to a given position.
  40141. By default this is turned off, but it's handy if you want a double-click to act
  40142. as a quick way of resetting a slider. Just pass in the value you want it to
  40143. go to when double-clicked.
  40144. @see getDoubleClickReturnValue
  40145. */
  40146. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  40147. double valueToSetOnDoubleClick);
  40148. /** Returns the values last set by setDoubleClickReturnValue() method.
  40149. Sets isEnabled to true if double-click is enabled, and returns the value
  40150. that was set.
  40151. @see setDoubleClickReturnValue
  40152. */
  40153. double getDoubleClickReturnValue (bool& isEnabled) const;
  40154. /** Tells the slider whether to keep sending change messages while the user
  40155. is dragging the slider.
  40156. If set to true, a change message will only be sent when the user has
  40157. dragged the slider and let go. If set to false (the default), then messages
  40158. will be continuously sent as they drag it while the mouse button is still
  40159. held down.
  40160. */
  40161. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  40162. /** This lets you change whether the slider thumb jumps to the mouse position
  40163. when you click.
  40164. By default, this is true. If it's false, then the slider moves with relative
  40165. motion when you drag it.
  40166. This only applies to linear bars, and won't affect two- or three- value
  40167. sliders.
  40168. */
  40169. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  40170. /** If enabled, this gives the slider a pop-up bubble which appears while the
  40171. slider is being dragged.
  40172. This can be handy if your slider doesn't have a text-box, so that users can
  40173. see the value just when they're changing it.
  40174. If you pass a component as the parentComponentToUse parameter, the pop-up
  40175. bubble will be added as a child of that component when it's needed. If you
  40176. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  40177. transparent window, so if you're using an OS that can't do transparent windows
  40178. you'll have to add it to a parent component instead).
  40179. */
  40180. void setPopupDisplayEnabled (bool isEnabled,
  40181. Component* parentComponentToUse);
  40182. /** If this is set to true, then right-clicking on the slider will pop-up
  40183. a menu to let the user change the way it works.
  40184. By default this is turned off, but when turned on, the menu will include
  40185. things like velocity sensitivity, and for rotary sliders, whether they
  40186. use a linear or rotary mouse-drag to move them.
  40187. */
  40188. void setPopupMenuEnabled (bool menuEnabled);
  40189. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  40190. By default it's enabled.
  40191. */
  40192. void setScrollWheelEnabled (bool enabled);
  40193. /** Returns a number to indicate which thumb is currently being dragged by the
  40194. mouse.
  40195. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  40196. the maximum-value thumb, or -1 if none is currently down.
  40197. */
  40198. int getThumbBeingDragged() const noexcept { return sliderBeingDragged; }
  40199. /** Callback to indicate that the user is about to start dragging the slider.
  40200. @see Slider::Listener::sliderDragStarted
  40201. */
  40202. virtual void startedDragging();
  40203. /** Callback to indicate that the user has just stopped dragging the slider.
  40204. @see Slider::Listener::sliderDragEnded
  40205. */
  40206. virtual void stoppedDragging();
  40207. /** Callback to indicate that the user has just moved the slider.
  40208. @see Slider::Listener::sliderValueChanged
  40209. */
  40210. virtual void valueChanged();
  40211. /** Subclasses can override this to convert a text string to a value.
  40212. When the user enters something into the text-entry box, this method is
  40213. called to convert it to a value.
  40214. The default routine just tries to convert it to a double.
  40215. @see getTextFromValue
  40216. */
  40217. virtual double getValueFromText (const String& text);
  40218. /** Turns the slider's current value into a text string.
  40219. Subclasses can override this to customise the formatting of the text-entry box.
  40220. The default implementation just turns the value into a string, using
  40221. a number of decimal places based on the range interval. If a suffix string
  40222. has been set using setTextValueSuffix(), this will be appended to the text.
  40223. @see getValueFromText
  40224. */
  40225. virtual const String getTextFromValue (double value);
  40226. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  40227. a string.
  40228. This is used by the default implementation of getTextFromValue(), and is just
  40229. appended to the numeric value. For more advanced formatting, you can override
  40230. getTextFromValue() and do something else.
  40231. */
  40232. void setTextValueSuffix (const String& suffix);
  40233. /** Returns the suffix that was set by setTextValueSuffix(). */
  40234. const String getTextValueSuffix() const;
  40235. /** Allows a user-defined mapping of distance along the slider to its value.
  40236. The default implementation for this performs the skewing operation that
  40237. can be set up in the setSkewFactor() method. Override it if you need
  40238. some kind of custom mapping instead, but make sure you also implement the
  40239. inverse function in valueToProportionOfLength().
  40240. @param proportion a value 0 to 1.0, indicating a distance along the slider
  40241. @returns the slider value that is represented by this position
  40242. @see valueToProportionOfLength
  40243. */
  40244. virtual double proportionOfLengthToValue (double proportion);
  40245. /** Allows a user-defined mapping of value to the position of the slider along its length.
  40246. The default implementation for this performs the skewing operation that
  40247. can be set up in the setSkewFactor() method. Override it if you need
  40248. some kind of custom mapping instead, but make sure you also implement the
  40249. inverse function in proportionOfLengthToValue().
  40250. @param value a valid slider value, between the range of values specified in
  40251. setRange()
  40252. @returns a value 0 to 1.0 indicating the distance along the slider that
  40253. represents this value
  40254. @see proportionOfLengthToValue
  40255. */
  40256. virtual double valueToProportionOfLength (double value);
  40257. /** Returns the X or Y coordinate of a value along the slider's length.
  40258. If the slider is horizontal, this will be the X coordinate of the given
  40259. value, relative to the left of the slider. If it's vertical, then this will
  40260. be the Y coordinate, relative to the top of the slider.
  40261. If the slider is rotary, this will throw an assertion and return 0. If the
  40262. value is out-of-range, it will be constrained to the length of the slider.
  40263. */
  40264. float getPositionOfValue (double value);
  40265. /** This can be overridden to allow the slider to snap to user-definable values.
  40266. If overridden, it will be called when the user tries to move the slider to
  40267. a given position, and allows a subclass to sanity-check this value, possibly
  40268. returning a different value to use instead.
  40269. @param attemptedValue the value the user is trying to enter
  40270. @param userIsDragging true if the user is dragging with the mouse; false if
  40271. they are entering the value using the text box
  40272. @returns the value to use instead
  40273. */
  40274. virtual double snapValue (double attemptedValue, bool userIsDragging);
  40275. /** This can be called to force the text box to update its contents.
  40276. (Not normally needed, as this is done automatically).
  40277. */
  40278. void updateText();
  40279. /** True if the slider moves horizontally. */
  40280. bool isHorizontal() const;
  40281. /** True if the slider moves vertically. */
  40282. bool isVertical() const;
  40283. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  40284. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40285. methods.
  40286. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40287. */
  40288. enum ColourIds
  40289. {
  40290. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  40291. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  40292. and feel class how this is used. */
  40293. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  40294. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  40295. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  40296. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  40297. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  40298. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  40299. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  40300. };
  40301. protected:
  40302. /** @internal */
  40303. void labelTextChanged (Label*);
  40304. /** @internal */
  40305. void paint (Graphics& g);
  40306. /** @internal */
  40307. void resized();
  40308. /** @internal */
  40309. void mouseDown (const MouseEvent& e);
  40310. /** @internal */
  40311. void mouseUp (const MouseEvent& e);
  40312. /** @internal */
  40313. void mouseDrag (const MouseEvent& e);
  40314. /** @internal */
  40315. void mouseDoubleClick (const MouseEvent& e);
  40316. /** @internal */
  40317. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40318. /** @internal */
  40319. void modifierKeysChanged (const ModifierKeys& modifiers);
  40320. /** @internal */
  40321. void buttonClicked (Button* button);
  40322. /** @internal */
  40323. void lookAndFeelChanged();
  40324. /** @internal */
  40325. void enablementChanged();
  40326. /** @internal */
  40327. void focusOfChildComponentChanged (FocusChangeType cause);
  40328. /** @internal */
  40329. void handleAsyncUpdate();
  40330. /** @internal */
  40331. void colourChanged();
  40332. /** @internal */
  40333. void valueChanged (Value& value);
  40334. /** Returns the best number of decimal places to use when displaying numbers.
  40335. This is calculated from the slider's interval setting.
  40336. */
  40337. int getNumDecimalPlacesToDisplay() const noexcept { return numDecimalPlaces; }
  40338. private:
  40339. ListenerList <Listener> listeners;
  40340. Value currentValue, valueMin, valueMax;
  40341. double lastCurrentValue, lastValueMin, lastValueMax;
  40342. double minimum, maximum, interval, doubleClickReturnValue;
  40343. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  40344. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  40345. int velocityModeThreshold;
  40346. float rotaryStart, rotaryEnd;
  40347. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  40348. int mouseDragStartX, mouseDragStartY;
  40349. int sliderRegionStart, sliderRegionSize;
  40350. int sliderBeingDragged;
  40351. int pixelsForFullDragExtent;
  40352. Rectangle<int> sliderRect;
  40353. String textSuffix;
  40354. SliderStyle style;
  40355. TextEntryBoxPosition textBoxPos;
  40356. int textBoxWidth, textBoxHeight;
  40357. IncDecButtonMode incDecButtonMode;
  40358. bool editableText : 1, doubleClickToValue : 1;
  40359. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  40360. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  40361. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  40362. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  40363. ScopedPointer<Label> valueBox;
  40364. ScopedPointer<Button> incButton, decButton;
  40365. class PopupDisplayComponent;
  40366. friend class PopupDisplayComponent;
  40367. friend class ScopedPointer <PopupDisplayComponent>;
  40368. ScopedPointer <PopupDisplayComponent> popupDisplay;
  40369. Component* parentForPopupDisplay;
  40370. float getLinearSliderPos (double value);
  40371. void restoreMouseIfHidden();
  40372. void sendDragStart();
  40373. void sendDragEnd();
  40374. double constrainedValue (double value) const;
  40375. void triggerChangeMessage (bool synchronous);
  40376. bool incDecDragDirectionIsHorizontal() const;
  40377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  40378. };
  40379. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  40380. typedef Slider::Listener SliderListener;
  40381. #if JUCE_VC6
  40382. #undef Listener
  40383. #endif
  40384. #endif // __JUCE_SLIDER_JUCEHEADER__
  40385. /*** End of inlined file: juce_Slider.h ***/
  40386. #endif
  40387. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40388. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  40389. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40390. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40391. /**
  40392. A component that displays a strip of column headings for a table, and allows these
  40393. to be resized, dragged around, etc.
  40394. This is just the component that goes at the top of a table. You can use it
  40395. directly for custom components, or to create a simple table, use the
  40396. TableListBox class.
  40397. To use one of these, create it and use addColumn() to add all the columns that you need.
  40398. Each column must be given a unique ID number that's used to refer to it.
  40399. @see TableListBox, TableHeaderComponent::Listener
  40400. */
  40401. class JUCE_API TableHeaderComponent : public Component,
  40402. private AsyncUpdater
  40403. {
  40404. public:
  40405. /** Creates an empty table header.
  40406. */
  40407. TableHeaderComponent();
  40408. /** Destructor. */
  40409. ~TableHeaderComponent();
  40410. /** A combination of these flags are passed into the addColumn() method to specify
  40411. the properties of a column.
  40412. */
  40413. enum ColumnPropertyFlags
  40414. {
  40415. 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. */
  40416. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  40417. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  40418. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  40419. 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. */
  40420. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  40421. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  40422. /** This set of default flags is used as the default parameter value in addColumn(). */
  40423. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  40424. /** A quick way of combining flags for a column that's not resizable. */
  40425. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  40426. /** A quick way of combining flags for a column that's not resizable or sortable. */
  40427. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  40428. /** A quick way of combining flags for a column that's not sortable. */
  40429. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  40430. };
  40431. /** Adds a column to the table.
  40432. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  40433. registered listeners.
  40434. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  40435. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  40436. a unique ID. This is used to identify the column later on, after the user may have
  40437. changed the order that they appear in
  40438. @param width the initial width of the column, in pixels
  40439. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  40440. if the 'resizable' flag is specified for this column
  40441. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  40442. if the 'resizable' flag is specified for this column
  40443. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  40444. properties of this column
  40445. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  40446. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  40447. all columns, not just the index amongst those that are currently visible
  40448. */
  40449. void addColumn (const String& columnName,
  40450. int columnId,
  40451. int width,
  40452. int minimumWidth = 30,
  40453. int maximumWidth = -1,
  40454. int propertyFlags = defaultFlags,
  40455. int insertIndex = -1);
  40456. /** Removes a column with the given ID.
  40457. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  40458. registered listeners.
  40459. */
  40460. void removeColumn (int columnIdToRemove);
  40461. /** Deletes all columns from the table.
  40462. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  40463. registered listeners.
  40464. */
  40465. void removeAllColumns();
  40466. /** Returns the number of columns in the table.
  40467. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  40468. return the total number of columns, including hidden ones.
  40469. @see isColumnVisible
  40470. */
  40471. int getNumColumns (bool onlyCountVisibleColumns) const;
  40472. /** Returns the name for a column.
  40473. @see setColumnName
  40474. */
  40475. const String getColumnName (int columnId) const;
  40476. /** Changes the name of a column. */
  40477. void setColumnName (int columnId, const String& newName);
  40478. /** Moves a column to a different index in the table.
  40479. @param columnId the column to move
  40480. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  40481. */
  40482. void moveColumn (int columnId, int newVisibleIndex);
  40483. /** Returns the width of one of the columns.
  40484. */
  40485. int getColumnWidth (int columnId) const;
  40486. /** Changes the width of a column.
  40487. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  40488. */
  40489. void setColumnWidth (int columnId, int newWidth);
  40490. /** Shows or hides a column.
  40491. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  40492. @see isColumnVisible
  40493. */
  40494. void setColumnVisible (int columnId, bool shouldBeVisible);
  40495. /** Returns true if this column is currently visible.
  40496. @see setColumnVisible
  40497. */
  40498. bool isColumnVisible (int columnId) const;
  40499. /** Changes the column which is the sort column.
  40500. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  40501. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  40502. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  40503. @see getSortColumnId, isSortedForwards, reSortTable
  40504. */
  40505. void setSortColumnId (int columnId, bool sortForwards);
  40506. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  40507. @see setSortColumnId, isSortedForwards
  40508. */
  40509. int getSortColumnId() const;
  40510. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  40511. @see setSortColumnId
  40512. */
  40513. bool isSortedForwards() const;
  40514. /** Triggers a re-sort of the table according to the current sort-column.
  40515. If you modifiy the table's contents, you can call this to signal that the table needs
  40516. to be re-sorted.
  40517. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  40518. tableSortOrderChanged() method of any listeners).
  40519. */
  40520. void reSortTable();
  40521. /** Returns the total width of all the visible columns in the table.
  40522. */
  40523. int getTotalWidth() const;
  40524. /** Returns the index of a given column.
  40525. If there's no such column ID, this will return -1.
  40526. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  40527. otherwise it'll return the index amongst all the columns, including any hidden ones.
  40528. */
  40529. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  40530. /** Returns the ID of the column at a given index.
  40531. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  40532. otherwise it'll count it amongst all the columns, including any hidden ones.
  40533. If the index is out-of-range, it'll return 0.
  40534. */
  40535. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  40536. /** Returns the rectangle containing of one of the columns.
  40537. The index is an index from 0 to the number of columns that are currently visible (hidden
  40538. ones are not counted). It returns a rectangle showing the position of the column relative
  40539. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  40540. */
  40541. const Rectangle<int> getColumnPosition (int index) const;
  40542. /** Finds the column ID at a given x-position in the component.
  40543. If there is a column at this point this returns its ID, or if not, it will return 0.
  40544. */
  40545. int getColumnIdAtX (int xToFind) const;
  40546. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  40547. entire width of the component.
  40548. By default this is disabled. Turning it on also means that when resizing a column, those
  40549. on the right will be squashed to fit.
  40550. */
  40551. void setStretchToFitActive (bool shouldStretchToFit);
  40552. /** Returns true if stretch-to-fit has been enabled.
  40553. @see setStretchToFitActive
  40554. */
  40555. bool isStretchToFitActive() const;
  40556. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  40557. specified width, keeping their relative proportions the same.
  40558. If the minimum widths of the columns are too wide to fit into this space, it may
  40559. actually end up wider.
  40560. */
  40561. void resizeAllColumnsToFit (int targetTotalWidth);
  40562. /** Enables or disables the pop-up menu.
  40563. The default menu allows the user to show or hide columns. You can add custom
  40564. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  40565. By default the menu is enabled.
  40566. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  40567. */
  40568. void setPopupMenuActive (bool hasMenu);
  40569. /** Returns true if the pop-up menu is enabled.
  40570. @see setPopupMenuActive
  40571. */
  40572. bool isPopupMenuActive() const;
  40573. /** Returns a string that encapsulates the table's current layout.
  40574. This can be restored later using restoreFromString(). It saves the order of
  40575. the columns, the currently-sorted column, and the widths.
  40576. @see restoreFromString
  40577. */
  40578. const String toString() const;
  40579. /** Restores the state of the table, based on a string previously created with
  40580. toString().
  40581. @see toString
  40582. */
  40583. void restoreFromString (const String& storedVersion);
  40584. /**
  40585. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  40586. You can register one of these objects for table events using TableHeaderComponent::addListener()
  40587. and TableHeaderComponent::removeListener().
  40588. @see TableHeaderComponent
  40589. */
  40590. class JUCE_API Listener
  40591. {
  40592. public:
  40593. Listener() {}
  40594. /** Destructor. */
  40595. virtual ~Listener() {}
  40596. /** This is called when some of the table's columns are added, removed, hidden,
  40597. or rearranged.
  40598. */
  40599. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  40600. /** This is called when one or more of the table's columns are resized.
  40601. */
  40602. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  40603. /** This is called when the column by which the table should be sorted is changed.
  40604. */
  40605. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  40606. /** This is called when the user begins or ends dragging one of the columns around.
  40607. When the user starts dragging a column, this is called with the ID of that
  40608. column. When they finish dragging, it is called again with 0 as the ID.
  40609. */
  40610. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  40611. int columnIdNowBeingDragged);
  40612. };
  40613. /** Adds a listener to be informed about things that happen to the header. */
  40614. void addListener (Listener* newListener);
  40615. /** Removes a previously-registered listener. */
  40616. void removeListener (Listener* listenerToRemove);
  40617. /** This can be overridden to handle a mouse-click on one of the column headers.
  40618. The default implementation will use this click to call getSortColumnId() and
  40619. change the sort order.
  40620. */
  40621. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  40622. /** This can be overridden to add custom items to the pop-up menu.
  40623. If you override this, you should call the superclass's method to add its
  40624. column show/hide items, if you want them on the menu as well.
  40625. Then to handle the result, override reactToMenuItem().
  40626. @see reactToMenuItem
  40627. */
  40628. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  40629. /** Override this to handle any custom items that you have added to the
  40630. pop-up menu with an addMenuItems() override.
  40631. If the menuReturnId isn't one of your own custom menu items, you'll need to
  40632. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  40633. handle the items that it had added.
  40634. @see addMenuItems
  40635. */
  40636. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  40637. /** @internal */
  40638. void paint (Graphics& g);
  40639. /** @internal */
  40640. void resized();
  40641. /** @internal */
  40642. void mouseMove (const MouseEvent&);
  40643. /** @internal */
  40644. void mouseEnter (const MouseEvent&);
  40645. /** @internal */
  40646. void mouseExit (const MouseEvent&);
  40647. /** @internal */
  40648. void mouseDown (const MouseEvent&);
  40649. /** @internal */
  40650. void mouseDrag (const MouseEvent&);
  40651. /** @internal */
  40652. void mouseUp (const MouseEvent&);
  40653. /** @internal */
  40654. const MouseCursor getMouseCursor();
  40655. /** Can be overridden for more control over the pop-up menu behaviour. */
  40656. virtual void showColumnChooserMenu (int columnIdClicked);
  40657. private:
  40658. struct ColumnInfo
  40659. {
  40660. String name;
  40661. int id, propertyFlags, width, minimumWidth, maximumWidth;
  40662. double lastDeliberateWidth;
  40663. bool isVisible() const;
  40664. };
  40665. OwnedArray <ColumnInfo> columns;
  40666. Array <Listener*> listeners;
  40667. ScopedPointer <Component> dragOverlayComp;
  40668. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  40669. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  40670. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  40671. ColumnInfo* getInfoForId (int columnId) const;
  40672. int visibleIndexToTotalIndex (int visibleIndex) const;
  40673. void sendColumnsChanged();
  40674. void handleAsyncUpdate();
  40675. void beginDrag (const MouseEvent&);
  40676. void endDrag (int finalIndex);
  40677. int getResizeDraggerAt (int mouseX) const;
  40678. void updateColumnUnderMouse (int x, int y);
  40679. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  40680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  40681. };
  40682. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  40683. typedef TableHeaderComponent::Listener TableHeaderListener;
  40684. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40685. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  40686. #endif
  40687. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40688. /*** Start of inlined file: juce_TableListBox.h ***/
  40689. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40690. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  40691. /**
  40692. One of these is used by a TableListBox as the data model for the table's contents.
  40693. The virtual methods that you override in this class take care of drawing the
  40694. table cells, and reacting to events.
  40695. @see TableListBox
  40696. */
  40697. class JUCE_API TableListBoxModel
  40698. {
  40699. public:
  40700. TableListBoxModel() {}
  40701. /** Destructor. */
  40702. virtual ~TableListBoxModel() {}
  40703. /** This must return the number of rows currently in the table.
  40704. If the number of rows changes, you must call TableListBox::updateContent() to
  40705. cause it to refresh the list.
  40706. */
  40707. virtual int getNumRows() = 0;
  40708. /** This must draw the background behind one of the rows in the table.
  40709. The graphics context has its origin at the row's top-left, and your method
  40710. should fill the area specified by the width and height parameters.
  40711. */
  40712. virtual void paintRowBackground (Graphics& g,
  40713. int rowNumber,
  40714. int width, int height,
  40715. bool rowIsSelected) = 0;
  40716. /** This must draw one of the cells.
  40717. The graphics context's origin will already be set to the top-left of the cell,
  40718. whose size is specified by (width, height).
  40719. */
  40720. virtual void paintCell (Graphics& g,
  40721. int rowNumber,
  40722. int columnId,
  40723. int width, int height,
  40724. bool rowIsSelected) = 0;
  40725. /** This is used to create or update a custom component to go in a cell.
  40726. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  40727. and handle mouse clicks with cellClicked().
  40728. This method will be called whenever a custom component might need to be updated - e.g.
  40729. when the table is changed, or TableListBox::updateContent() is called.
  40730. If you don't need a custom component for the specified cell, then return 0.
  40731. If you do want a custom component, and the existingComponentToUpdate is null, then
  40732. this method must create a new component suitable for the cell, and return it.
  40733. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  40734. by this method. In this case, the method must either update it to make sure it's correctly representing
  40735. the given cell (which may be different from the one that the component was created for), or it can
  40736. delete this component and return a new one.
  40737. */
  40738. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  40739. Component* existingComponentToUpdate);
  40740. /** This callback is made when the user clicks on one of the cells in the table.
  40741. The mouse event's coordinates will be relative to the entire table row.
  40742. @see cellDoubleClicked, backgroundClicked
  40743. */
  40744. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  40745. /** This callback is made when the user clicks on one of the cells in the table.
  40746. The mouse event's coordinates will be relative to the entire table row.
  40747. @see cellClicked, backgroundClicked
  40748. */
  40749. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  40750. /** This can be overridden to react to the user double-clicking on a part of the list where
  40751. there are no rows.
  40752. @see cellClicked
  40753. */
  40754. virtual void backgroundClicked();
  40755. /** This callback is made when the table's sort order is changed.
  40756. This could be because the user has clicked a column header, or because the
  40757. TableHeaderComponent::setSortColumnId() method was called.
  40758. If you implement this, your method should re-sort the table using the given
  40759. column as the key.
  40760. */
  40761. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  40762. /** Returns the best width for one of the columns.
  40763. If you implement this method, you should measure the width of all the items
  40764. in this column, and return the best size.
  40765. Returning 0 means that the column shouldn't be changed.
  40766. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  40767. */
  40768. virtual int getColumnAutoSizeWidth (int columnId);
  40769. /** Returns a tooltip for a particular cell in the table.
  40770. */
  40771. virtual const String getCellTooltip (int rowNumber, int columnId);
  40772. /** Override this to be informed when rows are selected or deselected.
  40773. @see ListBox::selectedRowsChanged()
  40774. */
  40775. virtual void selectedRowsChanged (int lastRowSelected);
  40776. /** Override this to be informed when the delete key is pressed.
  40777. @see ListBox::deleteKeyPressed()
  40778. */
  40779. virtual void deleteKeyPressed (int lastRowSelected);
  40780. /** Override this to be informed when the return key is pressed.
  40781. @see ListBox::returnKeyPressed()
  40782. */
  40783. virtual void returnKeyPressed (int lastRowSelected);
  40784. /** Override this to be informed when the list is scrolled.
  40785. This might be caused by the user moving the scrollbar, or by programmatic changes
  40786. to the list position.
  40787. */
  40788. virtual void listWasScrolled();
  40789. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  40790. If this returns a non-empty name then when the user drags a row, the table will try to
  40791. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  40792. drag-and-drop operation, using this string as the source description, and the listbox
  40793. itself as the source component.
  40794. @see DragAndDropContainer::startDragging
  40795. */
  40796. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  40797. };
  40798. /**
  40799. A table of cells, using a TableHeaderComponent as its header.
  40800. This component makes it easy to create a table by providing a TableListBoxModel as
  40801. the data source.
  40802. @see TableListBoxModel, TableHeaderComponent
  40803. */
  40804. class JUCE_API TableListBox : public ListBox,
  40805. private ListBoxModel,
  40806. private TableHeaderComponent::Listener
  40807. {
  40808. public:
  40809. /** Creates a TableListBox.
  40810. The model pointer passed-in can be null, in which case you can set it later
  40811. with setModel().
  40812. */
  40813. TableListBox (const String& componentName = String::empty,
  40814. TableListBoxModel* model = 0);
  40815. /** Destructor. */
  40816. ~TableListBox();
  40817. /** Changes the TableListBoxModel that is being used for this table.
  40818. */
  40819. void setModel (TableListBoxModel* newModel);
  40820. /** Returns the model currently in use. */
  40821. TableListBoxModel* getModel() const { return model; }
  40822. /** Returns the header component being used in this table. */
  40823. TableHeaderComponent& getHeader() const { return *header; }
  40824. /** Sets the header component to use for the table.
  40825. The table will take ownership of the component that you pass in, and will delete it
  40826. when it's no longer needed.
  40827. */
  40828. void setHeader (TableHeaderComponent* newHeader);
  40829. /** Changes the height of the table header component.
  40830. @see getHeaderHeight
  40831. */
  40832. void setHeaderHeight (int newHeight);
  40833. /** Returns the height of the table header.
  40834. @see setHeaderHeight
  40835. */
  40836. int getHeaderHeight() const;
  40837. /** Resizes a column to fit its contents.
  40838. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  40839. and applies that to the column.
  40840. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  40841. */
  40842. void autoSizeColumn (int columnId);
  40843. /** Calls autoSizeColumn() for all columns in the table. */
  40844. void autoSizeAllColumns();
  40845. /** Enables or disables the auto size options on the popup menu.
  40846. By default, these are enabled.
  40847. */
  40848. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  40849. /** True if the auto-size options should be shown on the menu.
  40850. @see setAutoSizeMenuOptionsShown
  40851. */
  40852. bool isAutoSizeMenuOptionShown() const;
  40853. /** Returns the position of one of the cells in the table.
  40854. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  40855. the table component's top-left. The row number isn't checked to see if it's
  40856. in-range, but the column ID must exist or this will return an empty rectangle.
  40857. If relativeToComponentTopLeft is false, the co-ords are relative to the
  40858. top-left of the table's top-left cell.
  40859. */
  40860. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  40861. bool relativeToComponentTopLeft) const;
  40862. /** Returns the component that currently represents a given cell.
  40863. If the component for this cell is off-screen or if the position is out-of-range,
  40864. this may return 0.
  40865. @see getCellPosition
  40866. */
  40867. Component* getCellComponent (int columnId, int rowNumber) const;
  40868. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  40869. @see ListBox::scrollToEnsureRowIsOnscreen
  40870. */
  40871. void scrollToEnsureColumnIsOnscreen (int columnId);
  40872. /** @internal */
  40873. int getNumRows();
  40874. /** @internal */
  40875. void paintListBoxItem (int, Graphics&, int, int, bool);
  40876. /** @internal */
  40877. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  40878. /** @internal */
  40879. void selectedRowsChanged (int lastRowSelected);
  40880. /** @internal */
  40881. void deleteKeyPressed (int currentSelectedRow);
  40882. /** @internal */
  40883. void returnKeyPressed (int currentSelectedRow);
  40884. /** @internal */
  40885. void backgroundClicked();
  40886. /** @internal */
  40887. void listWasScrolled();
  40888. /** @internal */
  40889. void tableColumnsChanged (TableHeaderComponent*);
  40890. /** @internal */
  40891. void tableColumnsResized (TableHeaderComponent*);
  40892. /** @internal */
  40893. void tableSortOrderChanged (TableHeaderComponent*);
  40894. /** @internal */
  40895. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  40896. /** @internal */
  40897. void resized();
  40898. private:
  40899. TableHeaderComponent* header;
  40900. TableListBoxModel* model;
  40901. int columnIdNowBeingDragged;
  40902. bool autoSizeOptionsShown;
  40903. void updateColumnComponents() const;
  40904. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  40905. };
  40906. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  40907. /*** End of inlined file: juce_TableListBox.h ***/
  40908. #endif
  40909. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  40910. #endif
  40911. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  40912. #endif
  40913. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  40914. #endif
  40915. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40916. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  40917. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40918. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40919. /**
  40920. A factory object which can create ToolbarItemComponent objects.
  40921. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  40922. that it can create.
  40923. Each type of item is identified by a unique ID, and multiple instances of an
  40924. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  40925. bars).
  40926. @see Toolbar, ToolbarItemComponent, ToolbarButton
  40927. */
  40928. class JUCE_API ToolbarItemFactory
  40929. {
  40930. public:
  40931. ToolbarItemFactory();
  40932. /** Destructor. */
  40933. virtual ~ToolbarItemFactory();
  40934. /** A set of reserved item ID values, used for the built-in item types.
  40935. */
  40936. enum SpecialItemIds
  40937. {
  40938. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  40939. can be placed between sets of items to break them into groups. */
  40940. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  40941. items.*/
  40942. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  40943. either side of it, filling any available space. */
  40944. };
  40945. /** Must return a list of the IDs for all the item types that this factory can create.
  40946. The ids should be added to the array that is passed-in.
  40947. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  40948. and the predefined IDs in the SpecialItemIds enum.
  40949. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  40950. to this list if you want your toolbar to be able to contain those items.
  40951. The list returned here is used by the ToolbarItemPalette class to obtain its list
  40952. of available items, and their order on the palette will reflect the order in which
  40953. they appear on this list.
  40954. @see ToolbarItemPalette
  40955. */
  40956. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  40957. /** Must return the set of items that should be added to a toolbar as its default set.
  40958. This method is used by Toolbar::addDefaultItems() to determine which items to
  40959. create.
  40960. The items that your method adds to the array that is passed-in will be added to the
  40961. toolbar in the same order. Items can appear in the list more than once.
  40962. */
  40963. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  40964. /** Must create an instance of one of the items that the factory lists in its
  40965. getAllToolbarItemIds() method.
  40966. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  40967. method, except for the built-in item types from the SpecialItemIds enum, which
  40968. are created internally by the toolbar code.
  40969. Try not to keep a pointer to the object that is returned, as it will be deleted
  40970. automatically by the toolbar, and remember that multiple instances of the same
  40971. item type are likely to exist at the same time.
  40972. */
  40973. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  40974. };
  40975. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40976. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  40977. #endif
  40978. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40979. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  40980. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40981. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40982. /**
  40983. A component containing a list of toolbar items, which the user can drag onto
  40984. a toolbar to add them.
  40985. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  40986. which automatically shows one of these in a dialog box with lots of extra controls.
  40987. @see Toolbar
  40988. */
  40989. class JUCE_API ToolbarItemPalette : public Component,
  40990. public DragAndDropContainer
  40991. {
  40992. public:
  40993. /** Creates a palette of items for a given factory, with the aim of adding them
  40994. to the specified toolbar.
  40995. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  40996. set of items that are shown in this palette.
  40997. The toolbar and factory must not be deleted while this object exists.
  40998. */
  40999. ToolbarItemPalette (ToolbarItemFactory& factory,
  41000. Toolbar* toolbar);
  41001. /** Destructor. */
  41002. ~ToolbarItemPalette();
  41003. /** @internal */
  41004. void resized();
  41005. private:
  41006. ToolbarItemFactory& factory;
  41007. Toolbar* toolbar;
  41008. Viewport viewport;
  41009. OwnedArray <ToolbarItemComponent> items;
  41010. friend class Toolbar;
  41011. void replaceComponent (ToolbarItemComponent* comp);
  41012. void addComponent (int itemId, int index);
  41013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  41014. };
  41015. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41016. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  41017. #endif
  41018. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41019. /*** Start of inlined file: juce_TreeView.h ***/
  41020. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41021. #define __JUCE_TREEVIEW_JUCEHEADER__
  41022. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  41023. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41024. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41025. /**
  41026. Components derived from this class can have files dropped onto them by an external application.
  41027. @see DragAndDropContainer
  41028. */
  41029. class JUCE_API FileDragAndDropTarget
  41030. {
  41031. public:
  41032. /** Destructor. */
  41033. virtual ~FileDragAndDropTarget() {}
  41034. /** Callback to check whether this target is interested in the set of files being offered.
  41035. Note that this will be called repeatedly when the user is dragging the mouse around over your
  41036. component, so don't do anything time-consuming in here, like opening the files to have a look
  41037. inside them!
  41038. @param files the set of (absolute) pathnames of the files that the user is dragging
  41039. @returns true if this component wants to receive the other callbacks regarging this
  41040. type of object; if it returns false, no other callbacks will be made.
  41041. */
  41042. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  41043. /** Callback to indicate that some files are being dragged over this component.
  41044. This gets called when the user moves the mouse into this component while dragging.
  41045. Use this callback as a trigger to make your component repaint itself to give the
  41046. user feedback about whether the files can be dropped here or not.
  41047. @param files the set of (absolute) pathnames of the files that the user is dragging
  41048. @param x the mouse x position, relative to this component
  41049. @param y the mouse y position, relative to this component
  41050. */
  41051. virtual void fileDragEnter (const StringArray& files, int x, int y);
  41052. /** Callback to indicate that the user is dragging some files over this component.
  41053. This gets called when the user moves the mouse over this component while dragging.
  41054. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  41055. this lets you know what happens in-between.
  41056. @param files the set of (absolute) pathnames of the files that the user is dragging
  41057. @param x the mouse x position, relative to this component
  41058. @param y the mouse y position, relative to this component
  41059. */
  41060. virtual void fileDragMove (const StringArray& files, int x, int y);
  41061. /** Callback to indicate that the mouse has moved away from this component.
  41062. This gets called when the user moves the mouse out of this component while dragging
  41063. the files.
  41064. If you've used fileDragEnter() to repaint your component and give feedback, use this
  41065. as a signal to repaint it in its normal state.
  41066. @param files the set of (absolute) pathnames of the files that the user is dragging
  41067. */
  41068. virtual void fileDragExit (const StringArray& files);
  41069. /** Callback to indicate that the user has dropped the files onto this component.
  41070. When the user drops the files, this get called, and you can use the files in whatever
  41071. way is appropriate.
  41072. Note that after this is called, the fileDragExit method may not be called, so you should
  41073. clean up in here if there's anything you need to do when the drag finishes.
  41074. @param files the set of (absolute) pathnames of the files that the user is dragging
  41075. @param x the mouse x position, relative to this component
  41076. @param y the mouse y position, relative to this component
  41077. */
  41078. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  41079. };
  41080. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41081. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  41082. class TreeView;
  41083. /**
  41084. An item in a treeview.
  41085. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  41086. own sub-items.
  41087. To implement an item that contains sub-items, override the itemOpennessChanged()
  41088. method so that when it is opened, it adds the new sub-items to itself using the
  41089. addSubItem method. Depending on the nature of the item it might choose to only
  41090. do this the first time it's opened, or it might want to refresh itself each time.
  41091. It also has the option of deleting its sub-items when it is closed, or leaving them
  41092. in place.
  41093. */
  41094. class JUCE_API TreeViewItem
  41095. {
  41096. public:
  41097. /** Constructor. */
  41098. TreeViewItem();
  41099. /** Destructor. */
  41100. virtual ~TreeViewItem();
  41101. /** Returns the number of sub-items that have been added to this item.
  41102. Note that this doesn't mean much if the node isn't open.
  41103. @see getSubItem, mightContainSubItems, addSubItem
  41104. */
  41105. int getNumSubItems() const noexcept;
  41106. /** Returns one of the item's sub-items.
  41107. Remember that the object returned might get deleted at any time when its parent
  41108. item is closed or refreshed, depending on the nature of the items you're using.
  41109. @see getNumSubItems
  41110. */
  41111. TreeViewItem* getSubItem (int index) const noexcept;
  41112. /** Removes any sub-items. */
  41113. void clearSubItems();
  41114. /** Adds a sub-item.
  41115. @param newItem the object to add to the item's sub-item list. Once added, these can be
  41116. found using getSubItem(). When the items are later removed with
  41117. removeSubItem() (or when this item is deleted), they will be deleted.
  41118. @param insertPosition the index which the new item should have when it's added. If this
  41119. value is less than 0, the item will be added to the end of the list.
  41120. */
  41121. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  41122. /** Removes one of the sub-items.
  41123. @param index the item to remove
  41124. @param deleteItem if true, the item that is removed will also be deleted.
  41125. */
  41126. void removeSubItem (int index, bool deleteItem = true);
  41127. /** Returns the TreeView to which this item belongs. */
  41128. TreeView* getOwnerView() const noexcept { return ownerView; }
  41129. /** Returns the item within which this item is contained. */
  41130. TreeViewItem* getParentItem() const noexcept { return parentItem; }
  41131. /** True if this item is currently open in the treeview. */
  41132. bool isOpen() const noexcept;
  41133. /** Opens or closes the item.
  41134. When opened or closed, the item's itemOpennessChanged() method will be called,
  41135. and a subclass should use this callback to create and add any sub-items that
  41136. it needs to.
  41137. @see itemOpennessChanged, mightContainSubItems
  41138. */
  41139. void setOpen (bool shouldBeOpen);
  41140. /** True if this item is currently selected.
  41141. Use this when painting the node, to decide whether to draw it as selected or not.
  41142. */
  41143. bool isSelected() const noexcept;
  41144. /** Selects or deselects the item.
  41145. This will cause a callback to itemSelectionChanged()
  41146. */
  41147. void setSelected (bool shouldBeSelected,
  41148. bool deselectOtherItemsFirst);
  41149. /** Returns the rectangle that this item occupies.
  41150. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  41151. top-left of the TreeView comp, so this will depend on the scroll-position of
  41152. the tree. If false, it is relative to the top-left of the topmost item in the
  41153. tree (so this would be unaffected by scrolling the view).
  41154. */
  41155. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const noexcept;
  41156. /** Sends a signal to the treeview to make it refresh itself.
  41157. Call this if your items have changed and you want the tree to update to reflect
  41158. this.
  41159. */
  41160. void treeHasChanged() const noexcept;
  41161. /** Sends a repaint message to redraw just this item.
  41162. Note that you should only call this if you want to repaint a superficial change. If
  41163. you're altering the tree's nodes, you should instead call treeHasChanged().
  41164. */
  41165. void repaintItem() const;
  41166. /** Returns the row number of this item in the tree.
  41167. The row number of an item will change according to which items are open.
  41168. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  41169. */
  41170. int getRowNumberInTree() const noexcept;
  41171. /** Returns true if all the item's parent nodes are open.
  41172. This is useful to check whether the item might actually be visible or not.
  41173. */
  41174. bool areAllParentsOpen() const noexcept;
  41175. /** Changes whether lines are drawn to connect any sub-items to this item.
  41176. By default, line-drawing is turned on.
  41177. */
  41178. void setLinesDrawnForSubItems (bool shouldDrawLines) noexcept;
  41179. /** Tells the tree whether this item can potentially be opened.
  41180. If your item could contain sub-items, this should return true; if it returns
  41181. false then the tree will not try to open the item. This determines whether or
  41182. not the item will be drawn with a 'plus' button next to it.
  41183. */
  41184. virtual bool mightContainSubItems() = 0;
  41185. /** Returns a string to uniquely identify this item.
  41186. If you're planning on using the TreeView::getOpennessState() method, then
  41187. these strings will be used to identify which nodes are open. The string
  41188. should be unique amongst the item's sibling items, but it's ok for there
  41189. to be duplicates at other levels of the tree.
  41190. If you're not going to store the state, then it's ok not to bother implementing
  41191. this method.
  41192. */
  41193. virtual const String getUniqueName() const;
  41194. /** Called when an item is opened or closed.
  41195. When setOpen() is called and the item has specified that it might
  41196. have sub-items with the mightContainSubItems() method, this method
  41197. is called to let the item create or manage its sub-items.
  41198. So when this is called with isNowOpen set to true (i.e. when the item is being
  41199. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  41200. refresh its sub-item list.
  41201. When this is called with isNowOpen set to false, the subclass might want
  41202. to use clearSubItems() to save on space, or it might choose to leave them,
  41203. depending on the nature of the tree.
  41204. You could also use this callback as a trigger to start a background process
  41205. which asynchronously creates sub-items and adds them, if that's more
  41206. appropriate for the task in hand.
  41207. @see mightContainSubItems
  41208. */
  41209. virtual void itemOpennessChanged (bool isNowOpen);
  41210. /** Must return the width required by this item.
  41211. If your item needs to have a particular width in pixels, return that value; if
  41212. you'd rather have it just fill whatever space is available in the treeview,
  41213. return -1.
  41214. If all your items return -1, no horizontal scrollbar will be shown, but if any
  41215. items have fixed widths and extend beyond the width of the treeview, a
  41216. scrollbar will appear.
  41217. Each item can be a different width, but if they change width, you should call
  41218. treeHasChanged() to update the tree.
  41219. */
  41220. virtual int getItemWidth() const { return -1; }
  41221. /** Must return the height required by this item.
  41222. This is the height in pixels that the item will take up. Items in the tree
  41223. can be different heights, but if they change height, you should call
  41224. treeHasChanged() to update the tree.
  41225. */
  41226. virtual int getItemHeight() const { return 20; }
  41227. /** You can override this method to return false if you don't want to allow the
  41228. user to select this item.
  41229. */
  41230. virtual bool canBeSelected() const { return true; }
  41231. /** Creates a component that will be used to represent this item.
  41232. You don't have to implement this method - if it returns 0 then no component
  41233. will be used for the item, and you can just draw it using the paintItem()
  41234. callback. But if you do return a component, it will be positioned in the
  41235. treeview so that it can be used to represent this item.
  41236. The component returned will be managed by the treeview, so always return
  41237. a new component, and don't keep a reference to it, as the treeview will
  41238. delete it later when it goes off the screen or is no longer needed. Also
  41239. bear in mind that if the component keeps a reference to the item that
  41240. created it, that item could be deleted before the component. Its position
  41241. and size will be completely managed by the tree, so don't attempt to move it
  41242. around.
  41243. Something you may want to do with your component is to give it a pointer to
  41244. the TreeView that created it. This is perfectly safe, and there's no danger
  41245. of it becoming a dangling pointer because the TreeView will always delete
  41246. the component before it is itself deleted.
  41247. As long as you stick to these rules you can return whatever kind of
  41248. component you like. It's most useful if you're doing things like drag-and-drop
  41249. of items, or want to use a Label component to edit item names, etc.
  41250. */
  41251. virtual Component* createItemComponent() { return nullptr; }
  41252. /** Draws the item's contents.
  41253. You can choose to either implement this method and draw each item, or you
  41254. can use createItemComponent() to create a component that will represent the
  41255. item.
  41256. If all you need in your tree is to be able to draw the items and detect when
  41257. the user selects or double-clicks one of them, it's probably enough to
  41258. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  41259. complicated interactions, you may need to use createItemComponent() instead.
  41260. @param g the graphics context to draw into
  41261. @param width the width of the area available for drawing
  41262. @param height the height of the area available for drawing
  41263. */
  41264. virtual void paintItem (Graphics& g, int width, int height);
  41265. /** Draws the item's open/close button.
  41266. If you don't implement this method, the default behaviour is to
  41267. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  41268. it for custom effects.
  41269. */
  41270. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  41271. /** Called when the user clicks on this item.
  41272. If you're using createItemComponent() to create a custom component for the
  41273. item, the mouse-clicks might not make it through to the treeview, but this
  41274. is how you find out about clicks when just drawing each item individually.
  41275. The associated mouse-event details are passed in, so you can find out about
  41276. which button, where it was, etc.
  41277. @see itemDoubleClicked
  41278. */
  41279. virtual void itemClicked (const MouseEvent& e);
  41280. /** Called when the user double-clicks on this item.
  41281. If you're using createItemComponent() to create a custom component for the
  41282. item, the mouse-clicks might not make it through to the treeview, but this
  41283. is how you find out about clicks when just drawing each item individually.
  41284. The associated mouse-event details are passed in, so you can find out about
  41285. which button, where it was, etc.
  41286. If not overridden, the base class method here will open or close the item as
  41287. if the 'plus' button had been clicked.
  41288. @see itemClicked
  41289. */
  41290. virtual void itemDoubleClicked (const MouseEvent& e);
  41291. /** Called when the item is selected or deselected.
  41292. Use this if you want to do something special when the item's selectedness
  41293. changes. By default it'll get repainted when this happens.
  41294. */
  41295. virtual void itemSelectionChanged (bool isNowSelected);
  41296. /** The item can return a tool tip string here if it wants to.
  41297. @see TooltipClient
  41298. */
  41299. virtual const String getTooltip();
  41300. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  41301. If this returns a non-empty name then when the user drags an item, the treeview will
  41302. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  41303. a drag-and-drop operation, using this string as the source description, with the treeview
  41304. itself as the source component.
  41305. If you need more complex drag-and-drop behaviour, you can use custom components for
  41306. the items, and use those to trigger the drag.
  41307. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  41308. isInterestedInFileDrag(), etc.
  41309. @see DragAndDropContainer::startDragging
  41310. */
  41311. virtual const String getDragSourceDescription();
  41312. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  41313. method and return true.
  41314. If you return true and allow some files to be dropped, you'll also need to implement the
  41315. filesDropped() method to do something with them.
  41316. Note that this will be called often, so make your implementation very quick! There's
  41317. certainly no time to try opening the files and having a think about what's inside them!
  41318. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  41319. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  41320. */
  41321. virtual bool isInterestedInFileDrag (const StringArray& files);
  41322. /** When files are dropped into this item, this callback is invoked.
  41323. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  41324. The insertIndex value indicates where in the list of sub-items the files were dropped.
  41325. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  41326. */
  41327. virtual void filesDropped (const StringArray& files, int insertIndex);
  41328. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  41329. If you implement this method, you'll also need to implement itemDropped() in order to handle
  41330. the items when they are dropped.
  41331. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  41332. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  41333. */
  41334. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  41335. /** When a things are dropped into this item, this callback is invoked.
  41336. For this to work, you need to have also implemented isInterestedInDragSource().
  41337. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  41338. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  41339. */
  41340. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  41341. /** Sets a flag to indicate that the item wants to be allowed
  41342. to draw all the way across to the left edge of the treeview.
  41343. By default this is false, which means that when the paintItem()
  41344. method is called, its graphics context is clipped to only allow
  41345. drawing within the item's rectangle. If this flag is set to true,
  41346. then the graphics context isn't clipped on its left side, so it
  41347. can draw all the way across to the left margin. Note that the
  41348. context will still have its origin in the same place though, so
  41349. the coordinates of anything to its left will be negative. It's
  41350. mostly useful if you want to draw a wider bar behind the
  41351. highlighted item.
  41352. */
  41353. void setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept;
  41354. /** Saves the current state of open/closed nodes so it can be restored later.
  41355. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  41356. and records it as XML. To identify node objects it uses the
  41357. TreeViewItem::getUniqueName() method to create named paths. This
  41358. means that the same state of open/closed nodes can be restored to a
  41359. completely different instance of the tree, as long as it contains nodes
  41360. whose unique names are the same.
  41361. You'd normally want to use TreeView::getOpennessState() rather than call it
  41362. for a specific item, but this can be handy if you need to briefly save the state
  41363. for a section of the tree.
  41364. The caller is responsible for deleting the object that is returned.
  41365. @see TreeView::getOpennessState, restoreOpennessState
  41366. */
  41367. XmlElement* getOpennessState() const noexcept;
  41368. /** Restores the openness of this item and all its sub-items from a saved state.
  41369. See TreeView::restoreOpennessState for more details.
  41370. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  41371. for a specific item, but this can be handy if you need to briefly save the state
  41372. for a section of the tree.
  41373. @see TreeView::restoreOpennessState, getOpennessState
  41374. */
  41375. void restoreOpennessState (const XmlElement& xml) noexcept;
  41376. /** Returns the index of this item in its parent's sub-items. */
  41377. int getIndexInParent() const noexcept;
  41378. /** Returns true if this item is the last of its parent's sub-itens. */
  41379. bool isLastOfSiblings() const noexcept;
  41380. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  41381. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  41382. The string takes the form of a path, constructed from the getUniqueName() of this
  41383. item and all its parents, so these must all be correctly implemented for it to work.
  41384. @see TreeView::findItemFromIdentifierString, getUniqueName
  41385. */
  41386. const String getItemIdentifierString() const;
  41387. /**
  41388. This handy class takes a copy of a TreeViewItem's openness when you create it,
  41389. and restores that openness state when its destructor is called.
  41390. This can very handy when you're refreshing sub-items - e.g.
  41391. @code
  41392. void MyTreeViewItem::updateChildItems()
  41393. {
  41394. OpennessRestorer openness (*this); // saves the openness state here..
  41395. clearSubItems();
  41396. // add a bunch of sub-items here which may or may not be the same as the ones that
  41397. // were previously there
  41398. addSubItem (...
  41399. // ..and at this point, the old openness is restored, so any items that haven't
  41400. // changed will have their old openness retained.
  41401. }
  41402. @endcode
  41403. */
  41404. class OpennessRestorer
  41405. {
  41406. public:
  41407. OpennessRestorer (TreeViewItem& treeViewItem);
  41408. ~OpennessRestorer();
  41409. private:
  41410. TreeViewItem& treeViewItem;
  41411. ScopedPointer <XmlElement> oldOpenness;
  41412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  41413. };
  41414. private:
  41415. TreeView* ownerView;
  41416. TreeViewItem* parentItem;
  41417. OwnedArray <TreeViewItem> subItems;
  41418. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  41419. int uid;
  41420. bool selected : 1;
  41421. bool redrawNeeded : 1;
  41422. bool drawLinesInside : 1;
  41423. bool drawsInLeftMargin : 1;
  41424. unsigned int openness : 2;
  41425. friend class TreeView;
  41426. friend class TreeViewContentComponent;
  41427. void updatePositions (int newY);
  41428. int getIndentX() const noexcept;
  41429. void setOwnerView (TreeView* newOwner) noexcept;
  41430. void paintRecursively (Graphics& g, int width);
  41431. TreeViewItem* getTopLevelItem() noexcept;
  41432. TreeViewItem* findItemRecursively (int y) noexcept;
  41433. TreeViewItem* getDeepestOpenParentItem() noexcept;
  41434. int getNumRows() const noexcept;
  41435. TreeViewItem* getItemOnRow (int index) noexcept;
  41436. void deselectAllRecursively();
  41437. int countSelectedItemsRecursively (int depth) const noexcept;
  41438. TreeViewItem* getSelectedItemWithIndex (int index) noexcept;
  41439. TreeViewItem* getNextVisibleItem (bool recurse) const noexcept;
  41440. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  41441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  41442. };
  41443. /**
  41444. A tree-view component.
  41445. Use one of these to hold and display a structure of TreeViewItem objects.
  41446. */
  41447. class JUCE_API TreeView : public Component,
  41448. public SettableTooltipClient,
  41449. public FileDragAndDropTarget,
  41450. public DragAndDropTarget,
  41451. private AsyncUpdater
  41452. {
  41453. public:
  41454. /** Creates an empty treeview.
  41455. Once you've got a treeview component, you'll need to give it something to
  41456. display, using the setRootItem() method.
  41457. */
  41458. TreeView (const String& componentName = String::empty);
  41459. /** Destructor. */
  41460. ~TreeView();
  41461. /** Sets the item that is displayed in the treeview.
  41462. A tree has a single root item which contains as many sub-items as it needs. If
  41463. you want the tree to contain a number of root items, you should still use a single
  41464. root item above these, but hide it using setRootItemVisible().
  41465. You can pass in 0 to this method to clear the tree and remove its current root item.
  41466. The object passed in will not be deleted by the treeview, it's up to the caller
  41467. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  41468. this item until you've removed it from the tree, either by calling setRootItem (nullptr),
  41469. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  41470. to delete it.
  41471. */
  41472. void setRootItem (TreeViewItem* newRootItem);
  41473. /** Returns the tree's root item.
  41474. This will be the last object passed to setRootItem(), or 0 if none has been set.
  41475. */
  41476. TreeViewItem* getRootItem() const noexcept { return rootItem; }
  41477. /** This will remove and delete the current root item.
  41478. It's a convenient way of deleting the item and calling setRootItem (nullptr).
  41479. */
  41480. void deleteRootItem();
  41481. /** Changes whether the tree's root item is shown or not.
  41482. If the root item is hidden, only its sub-items will be shown in the treeview - this
  41483. lets you make the tree look as if it's got many root items. If it's hidden, this call
  41484. will also make sure the root item is open (otherwise the treeview would look empty).
  41485. */
  41486. void setRootItemVisible (bool shouldBeVisible);
  41487. /** Returns true if the root item is visible.
  41488. @see setRootItemVisible
  41489. */
  41490. bool isRootItemVisible() const noexcept { return rootItemVisible; }
  41491. /** Sets whether items are open or closed by default.
  41492. Normally, items are closed until the user opens them, but you can use this
  41493. to make them default to being open until explicitly closed.
  41494. @see areItemsOpenByDefault
  41495. */
  41496. void setDefaultOpenness (bool isOpenByDefault);
  41497. /** Returns true if the tree's items default to being open.
  41498. @see setDefaultOpenness
  41499. */
  41500. bool areItemsOpenByDefault() const noexcept { return defaultOpenness; }
  41501. /** This sets a flag to indicate that the tree can be used for multi-selection.
  41502. You can always select multiple items internally by calling the
  41503. TreeViewItem::setSelected() method, but this flag indicates whether the user
  41504. is allowed to multi-select by clicking on the tree.
  41505. By default it is disabled.
  41506. @see isMultiSelectEnabled
  41507. */
  41508. void setMultiSelectEnabled (bool canMultiSelect);
  41509. /** Returns whether multi-select has been enabled for the tree.
  41510. @see setMultiSelectEnabled
  41511. */
  41512. bool isMultiSelectEnabled() const noexcept { return multiSelectEnabled; }
  41513. /** Sets a flag to indicate whether to hide the open/close buttons.
  41514. @see areOpenCloseButtonsVisible
  41515. */
  41516. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  41517. /** Returns whether open/close buttons are shown.
  41518. @see setOpenCloseButtonsVisible
  41519. */
  41520. bool areOpenCloseButtonsVisible() const noexcept { return openCloseButtonsVisible; }
  41521. /** Deselects any items that are currently selected. */
  41522. void clearSelectedItems();
  41523. /** Returns the number of items that are currently selected.
  41524. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  41525. tree will be recursed.
  41526. @see getSelectedItem, clearSelectedItems
  41527. */
  41528. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const noexcept;
  41529. /** Returns one of the selected items in the tree.
  41530. @param index the index, 0 to (getNumSelectedItems() - 1)
  41531. */
  41532. TreeViewItem* getSelectedItem (int index) const noexcept;
  41533. /** Returns the number of rows the tree is using.
  41534. This will depend on which items are open.
  41535. @see TreeViewItem::getRowNumberInTree()
  41536. */
  41537. int getNumRowsInTree() const;
  41538. /** Returns the item on a particular row of the tree.
  41539. If the index is out of range, this will return 0.
  41540. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  41541. */
  41542. TreeViewItem* getItemOnRow (int index) const;
  41543. /** Returns the item that contains a given y position.
  41544. The y is relative to the top of the TreeView component.
  41545. */
  41546. TreeViewItem* getItemAt (int yPosition) const noexcept;
  41547. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  41548. void scrollToKeepItemVisible (TreeViewItem* item);
  41549. /** Returns the treeview's Viewport object. */
  41550. Viewport* getViewport() const noexcept;
  41551. /** Returns the number of pixels by which each nested level of the tree is indented.
  41552. @see setIndentSize
  41553. */
  41554. int getIndentSize() const noexcept { return indentSize; }
  41555. /** Changes the distance by which each nested level of the tree is indented.
  41556. @see getIndentSize
  41557. */
  41558. void setIndentSize (int newIndentSize);
  41559. /** Searches the tree for an item with the specified identifier.
  41560. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  41561. If no such item exists, this will return false. If the item is found, all of its items
  41562. will be automatically opened.
  41563. */
  41564. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  41565. /** Saves the current state of open/closed nodes so it can be restored later.
  41566. This takes a snapshot of which nodes have been explicitly opened or closed,
  41567. and records it as XML. To identify node objects it uses the
  41568. TreeViewItem::getUniqueName() method to create named paths. This
  41569. means that the same state of open/closed nodes can be restored to a
  41570. completely different instance of the tree, as long as it contains nodes
  41571. whose unique names are the same.
  41572. The caller is responsible for deleting the object that is returned.
  41573. @param alsoIncludeScrollPosition if this is true, the state will also
  41574. include information about where the
  41575. tree has been scrolled to vertically,
  41576. so this can also be restored
  41577. @see restoreOpennessState
  41578. */
  41579. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  41580. /** Restores a previously saved arrangement of open/closed nodes.
  41581. This will try to restore a snapshot of the tree's state that was created by
  41582. the getOpennessState() method. If any of the nodes named in the original
  41583. XML aren't present in this tree, they will be ignored.
  41584. @see getOpennessState
  41585. */
  41586. void restoreOpennessState (const XmlElement& newState);
  41587. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  41588. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41589. methods.
  41590. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41591. */
  41592. enum ColourIds
  41593. {
  41594. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  41595. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  41596. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  41597. };
  41598. /** @internal */
  41599. void paint (Graphics& g);
  41600. /** @internal */
  41601. void resized();
  41602. /** @internal */
  41603. bool keyPressed (const KeyPress& key);
  41604. /** @internal */
  41605. void colourChanged();
  41606. /** @internal */
  41607. void enablementChanged();
  41608. /** @internal */
  41609. bool isInterestedInFileDrag (const StringArray& files);
  41610. /** @internal */
  41611. void fileDragEnter (const StringArray& files, int x, int y);
  41612. /** @internal */
  41613. void fileDragMove (const StringArray& files, int x, int y);
  41614. /** @internal */
  41615. void fileDragExit (const StringArray& files);
  41616. /** @internal */
  41617. void filesDropped (const StringArray& files, int x, int y);
  41618. /** @internal */
  41619. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  41620. /** @internal */
  41621. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  41622. /** @internal */
  41623. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  41624. /** @internal */
  41625. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  41626. /** @internal */
  41627. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  41628. private:
  41629. friend class TreeViewItem;
  41630. friend class TreeViewContentComponent;
  41631. class TreeViewport;
  41632. class InsertPointHighlight;
  41633. class TargetGroupHighlight;
  41634. friend class ScopedPointer<TreeViewport>;
  41635. friend class ScopedPointer<InsertPointHighlight>;
  41636. friend class ScopedPointer<TargetGroupHighlight>;
  41637. ScopedPointer<TreeViewport> viewport;
  41638. CriticalSection nodeAlterationLock;
  41639. TreeViewItem* rootItem;
  41640. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  41641. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  41642. int indentSize;
  41643. bool defaultOpenness : 1;
  41644. bool needsRecalculating : 1;
  41645. bool rootItemVisible : 1;
  41646. bool multiSelectEnabled : 1;
  41647. bool openCloseButtonsVisible : 1;
  41648. void itemsChanged() noexcept;
  41649. void handleAsyncUpdate();
  41650. void moveSelectedRow (int delta);
  41651. void updateButtonUnderMouse (const MouseEvent& e);
  41652. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) noexcept;
  41653. void hideDragHighlight() noexcept;
  41654. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  41655. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  41656. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  41657. const StringArray& files, const String& sourceDescription,
  41658. Component* sourceComponent) const noexcept;
  41659. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  41660. };
  41661. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  41662. /*** End of inlined file: juce_TreeView.h ***/
  41663. #endif
  41664. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41665. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41666. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41667. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41668. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  41669. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41670. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41671. /*** Start of inlined file: juce_FileFilter.h ***/
  41672. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  41673. #define __JUCE_FILEFILTER_JUCEHEADER__
  41674. /**
  41675. Interface for deciding which files are suitable for something.
  41676. For example, this is used by DirectoryContentsList to select which files
  41677. go into the list.
  41678. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  41679. */
  41680. class JUCE_API FileFilter
  41681. {
  41682. public:
  41683. /** Creates a filter with the given description.
  41684. The description can be returned later with the getDescription() method.
  41685. */
  41686. FileFilter (const String& filterDescription);
  41687. /** Destructor. */
  41688. virtual ~FileFilter();
  41689. /** Returns the description that the filter was created with. */
  41690. const String& getDescription() const noexcept;
  41691. /** Should return true if this file is suitable for inclusion in whatever context
  41692. the object is being used.
  41693. */
  41694. virtual bool isFileSuitable (const File& file) const = 0;
  41695. /** Should return true if this directory is suitable for inclusion in whatever context
  41696. the object is being used.
  41697. */
  41698. virtual bool isDirectorySuitable (const File& file) const = 0;
  41699. protected:
  41700. String description;
  41701. };
  41702. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  41703. /*** End of inlined file: juce_FileFilter.h ***/
  41704. /**
  41705. A class to asynchronously scan for details about the files in a directory.
  41706. This keeps a list of files and some information about them, using a background
  41707. thread to scan for more files. As files are found, it broadcasts change messages
  41708. to tell any listeners.
  41709. @see FileListComponent, FileBrowserComponent
  41710. */
  41711. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  41712. public TimeSliceClient
  41713. {
  41714. public:
  41715. /** Creates a directory list.
  41716. To set the directory it should point to, use setDirectory(), which will
  41717. also start it scanning for files on the background thread.
  41718. When the background thread finds and adds new files to this list, the
  41719. ChangeBroadcaster class will send a change message, so you can register
  41720. listeners and update them when the list changes.
  41721. @param fileFilter an optional filter to select which files are
  41722. included in the list. If this is 0, then all files
  41723. and directories are included. Make sure that the
  41724. filter doesn't get deleted during the lifetime of this
  41725. object
  41726. @param threadToUse a thread object that this list can use
  41727. to scan for files as a background task. Make sure
  41728. that the thread you give it has been started, or you
  41729. won't get any files!
  41730. */
  41731. DirectoryContentsList (const FileFilter* fileFilter,
  41732. TimeSliceThread& threadToUse);
  41733. /** Destructor. */
  41734. ~DirectoryContentsList();
  41735. /** Sets the directory to look in for files.
  41736. If the directory that's passed in is different to the current one, this will
  41737. also start the background thread scanning it for files.
  41738. */
  41739. void setDirectory (const File& directory,
  41740. bool includeDirectories,
  41741. bool includeFiles);
  41742. /** Returns the directory that's currently being used. */
  41743. const File& getDirectory() const;
  41744. /** Clears the list, and stops the thread scanning for files. */
  41745. void clear();
  41746. /** Clears the list and restarts scanning the directory for files. */
  41747. void refresh();
  41748. /** True if the background thread hasn't yet finished scanning for files. */
  41749. bool isStillLoading() const;
  41750. /** Tells the list whether or not to ignore hidden files.
  41751. By default these are ignored.
  41752. */
  41753. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  41754. /** Returns true if hidden files are ignored.
  41755. @see setIgnoresHiddenFiles
  41756. */
  41757. bool ignoresHiddenFiles() const;
  41758. /** Contains cached information about one of the files in a DirectoryContentsList.
  41759. */
  41760. struct FileInfo
  41761. {
  41762. /** The filename.
  41763. This isn't a full pathname, it's just the last part of the path, same as you'd
  41764. get from File::getFileName().
  41765. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  41766. */
  41767. String filename;
  41768. /** File size in bytes. */
  41769. int64 fileSize;
  41770. /** File modification time.
  41771. As supplied by File::getLastModificationTime().
  41772. */
  41773. Time modificationTime;
  41774. /** File creation time.
  41775. As supplied by File::getCreationTime().
  41776. */
  41777. Time creationTime;
  41778. /** True if the file is a directory. */
  41779. bool isDirectory;
  41780. /** True if the file is read-only. */
  41781. bool isReadOnly;
  41782. };
  41783. /** Returns the number of files currently available in the list.
  41784. The info about one of these files can be retrieved with getFileInfo() or
  41785. getFile().
  41786. Obviously as the background thread runs and scans the directory for files, this
  41787. number will change.
  41788. @see getFileInfo, getFile
  41789. */
  41790. int getNumFiles() const;
  41791. /** Returns the cached information about one of the files in the list.
  41792. If the index is in-range, this will return true and will copy the file's details
  41793. to the structure that is passed-in.
  41794. If it returns false, then the index wasn't in range, and the structure won't
  41795. be affected.
  41796. @see getNumFiles, getFile
  41797. */
  41798. bool getFileInfo (int index, FileInfo& resultInfo) const;
  41799. /** Returns one of the files in the list.
  41800. @param index should be less than getNumFiles(). If this is out-of-range, the
  41801. return value will be File::nonexistent
  41802. @see getNumFiles, getFileInfo
  41803. */
  41804. const File getFile (int index) const;
  41805. /** Returns the file filter being used.
  41806. The filter is specified in the constructor.
  41807. */
  41808. const FileFilter* getFilter() const { return fileFilter; }
  41809. /** @internal */
  41810. int useTimeSlice();
  41811. /** @internal */
  41812. TimeSliceThread& getTimeSliceThread() { return thread; }
  41813. /** @internal */
  41814. static int compareElements (const DirectoryContentsList::FileInfo* first,
  41815. const DirectoryContentsList::FileInfo* second);
  41816. private:
  41817. File root;
  41818. const FileFilter* fileFilter;
  41819. TimeSliceThread& thread;
  41820. int fileTypeFlags;
  41821. CriticalSection fileListLock;
  41822. OwnedArray <FileInfo> files;
  41823. ScopedPointer <DirectoryIterator> fileFindHandle;
  41824. bool volatile shouldStop;
  41825. void changed();
  41826. bool checkNextFile (bool& hasChanged);
  41827. bool addFile (const File& file, bool isDir,
  41828. const int64 fileSize, const Time& modTime,
  41829. const Time& creationTime, bool isReadOnly);
  41830. void setTypeFlags (int newFlags);
  41831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  41832. };
  41833. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41834. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  41835. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  41836. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41837. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41838. /**
  41839. A listener for user selection events in a file browser.
  41840. This is used by a FileBrowserComponent or FileListComponent.
  41841. */
  41842. class JUCE_API FileBrowserListener
  41843. {
  41844. public:
  41845. /** Destructor. */
  41846. virtual ~FileBrowserListener();
  41847. /** Callback when the user selects a different file in the browser. */
  41848. virtual void selectionChanged() = 0;
  41849. /** Callback when the user clicks on a file in the browser. */
  41850. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  41851. /** Callback when the user double-clicks on a file in the browser. */
  41852. virtual void fileDoubleClicked (const File& file) = 0;
  41853. };
  41854. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41855. /*** End of inlined file: juce_FileBrowserListener.h ***/
  41856. /**
  41857. A base class for components that display a list of the files in a directory.
  41858. @see DirectoryContentsList
  41859. */
  41860. class JUCE_API DirectoryContentsDisplayComponent
  41861. {
  41862. public:
  41863. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  41864. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  41865. /** Destructor. */
  41866. virtual ~DirectoryContentsDisplayComponent();
  41867. /** Returns the number of files the user has got selected.
  41868. @see getSelectedFile
  41869. */
  41870. virtual int getNumSelectedFiles() const = 0;
  41871. /** Returns one of the files that the user has currently selected.
  41872. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  41873. @see getNumSelectedFiles
  41874. */
  41875. virtual const File getSelectedFile (int index) const = 0;
  41876. /** Deselects any selected files. */
  41877. virtual void deselectAllFiles() = 0;
  41878. /** Scrolls this view to the top. */
  41879. virtual void scrollToTop() = 0;
  41880. /** Adds a listener to be told when files are selected or clicked.
  41881. @see removeListener
  41882. */
  41883. void addListener (FileBrowserListener* listener);
  41884. /** Removes a listener.
  41885. @see addListener
  41886. */
  41887. void removeListener (FileBrowserListener* listener);
  41888. /** A set of colour IDs to use to change the colour of various aspects of the list.
  41889. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41890. methods.
  41891. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41892. */
  41893. enum ColourIds
  41894. {
  41895. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  41896. textColourId = 0x1000541, /**< The colour for the text. */
  41897. };
  41898. /** @internal */
  41899. void sendSelectionChangeMessage();
  41900. /** @internal */
  41901. void sendDoubleClickMessage (const File& file);
  41902. /** @internal */
  41903. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  41904. protected:
  41905. DirectoryContentsList& fileList;
  41906. ListenerList <FileBrowserListener> listeners;
  41907. private:
  41908. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  41909. };
  41910. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41911. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41912. #endif
  41913. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41914. #endif
  41915. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41916. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  41917. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41918. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41919. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  41920. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41921. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41922. /**
  41923. Base class for components that live inside a file chooser dialog box and
  41924. show previews of the files that get selected.
  41925. One of these allows special extra information to be displayed for files
  41926. in a dialog box as the user selects them. Each time the current file or
  41927. directory is changed, the selectedFileChanged() method will be called
  41928. to allow it to update itself appropriately.
  41929. @see FileChooser, ImagePreviewComponent
  41930. */
  41931. class JUCE_API FilePreviewComponent : public Component
  41932. {
  41933. public:
  41934. /** Creates a FilePreviewComponent. */
  41935. FilePreviewComponent();
  41936. /** Destructor. */
  41937. ~FilePreviewComponent();
  41938. /** Called to indicate that the user's currently selected file has changed.
  41939. @param newSelectedFile the newly selected file or directory, which may be
  41940. File::nonexistent if none is selected.
  41941. */
  41942. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  41943. private:
  41944. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  41945. };
  41946. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41947. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  41948. /**
  41949. A component for browsing and selecting a file or directory to open or save.
  41950. This contains a FileListComponent and adds various boxes and controls for
  41951. navigating and selecting a file. It can work in different modes so that it can
  41952. be used for loading or saving a file, or for choosing a directory.
  41953. @see FileChooserDialogBox, FileChooser, FileListComponent
  41954. */
  41955. class JUCE_API FileBrowserComponent : public Component,
  41956. public ChangeBroadcaster,
  41957. private FileBrowserListener,
  41958. private TextEditorListener,
  41959. private ButtonListener,
  41960. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  41961. private FileFilter
  41962. {
  41963. public:
  41964. /** Various options for the browser.
  41965. A combination of these is passed into the FileBrowserComponent constructor.
  41966. */
  41967. enum FileChooserFlags
  41968. {
  41969. openMode = 1, /**< specifies that the component should allow the user to
  41970. choose an existing file with the intention of opening it. */
  41971. saveMode = 2, /**< specifies that the component should allow the user to specify
  41972. the name of a file that will be used to save something. */
  41973. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  41974. conjunction with canSelectDirectories). */
  41975. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  41976. conjuction with canSelectFiles). */
  41977. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  41978. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  41979. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  41980. };
  41981. /** Creates a FileBrowserComponent.
  41982. @param flags A combination of flags from the FileChooserFlags enumeration,
  41983. used to specify the component's behaviour. The flags must contain
  41984. either openMode or saveMode, and canSelectFiles and/or
  41985. canSelectDirectories.
  41986. @param initialFileOrDirectory The file or directory that should be selected when
  41987. the component begins. If this is File::nonexistent,
  41988. a default directory will be chosen.
  41989. @param fileFilter an optional filter to use to determine which files
  41990. are shown. If this is 0 then all files are displayed. Note
  41991. that a pointer is kept internally to this object, so
  41992. make sure that it is not deleted before the browser object
  41993. is deleted.
  41994. @param previewComp an optional preview component that will be used to
  41995. show previews of files that the user selects
  41996. */
  41997. FileBrowserComponent (int flags,
  41998. const File& initialFileOrDirectory,
  41999. const FileFilter* fileFilter,
  42000. FilePreviewComponent* previewComp);
  42001. /** Destructor. */
  42002. ~FileBrowserComponent();
  42003. /** Returns the number of files that the user has got selected.
  42004. If multiple select isn't active, this will only be 0 or 1. To get the complete
  42005. list of files they've chosen, pass an index to getCurrentFile().
  42006. */
  42007. int getNumSelectedFiles() const noexcept;
  42008. /** Returns one of the files that the user has chosen.
  42009. If the box has multi-select enabled, the index lets you specify which of the files
  42010. to get - see getNumSelectedFiles() to find out how many files were chosen.
  42011. @see getHighlightedFile
  42012. */
  42013. const File getSelectedFile (int index) const noexcept;
  42014. /** Deselects any files that are currently selected.
  42015. */
  42016. void deselectAllFiles();
  42017. /** Returns true if the currently selected file(s) are usable.
  42018. This can be used to decide whether the user can press "ok" for the
  42019. current file. What it does depends on the mode, so for example in an "open"
  42020. mode, this only returns true if a file has been selected and if it exists.
  42021. In a "save" mode, a non-existent file would also be valid.
  42022. */
  42023. bool currentFileIsValid() const;
  42024. /** This returns the last item in the view that the user has highlighted.
  42025. This may be different from getCurrentFile(), which returns the value
  42026. that is shown in the filename box, and if there are multiple selections,
  42027. this will only return one of them.
  42028. @see getSelectedFile
  42029. */
  42030. const File getHighlightedFile() const noexcept;
  42031. /** Returns the directory whose contents are currently being shown in the listbox. */
  42032. const File getRoot() const;
  42033. /** Changes the directory that's being shown in the listbox. */
  42034. void setRoot (const File& newRootDirectory);
  42035. /** Equivalent to pressing the "up" button to browse the parent directory. */
  42036. void goUp();
  42037. /** Refreshes the directory that's currently being listed. */
  42038. void refresh();
  42039. /** Changes the filter that's being used to sift the files. */
  42040. void setFileFilter (const FileFilter* newFileFilter);
  42041. /** Returns a verb to describe what should happen when the file is accepted.
  42042. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  42043. mode, it'll be "Save", etc.
  42044. */
  42045. virtual const String getActionVerb() const;
  42046. /** Returns true if the saveMode flag was set when this component was created.
  42047. */
  42048. bool isSaveMode() const noexcept;
  42049. /** Adds a listener to be told when the user selects and clicks on files.
  42050. @see removeListener
  42051. */
  42052. void addListener (FileBrowserListener* listener);
  42053. /** Removes a listener.
  42054. @see addListener
  42055. */
  42056. void removeListener (FileBrowserListener* listener);
  42057. /** @internal */
  42058. void resized();
  42059. /** @internal */
  42060. void buttonClicked (Button* b);
  42061. /** @internal */
  42062. void comboBoxChanged (ComboBox*);
  42063. /** @internal */
  42064. void textEditorTextChanged (TextEditor& editor);
  42065. /** @internal */
  42066. void textEditorReturnKeyPressed (TextEditor& editor);
  42067. /** @internal */
  42068. void textEditorEscapeKeyPressed (TextEditor& editor);
  42069. /** @internal */
  42070. void textEditorFocusLost (TextEditor& editor);
  42071. /** @internal */
  42072. bool keyPressed (const KeyPress& key);
  42073. /** @internal */
  42074. void selectionChanged();
  42075. /** @internal */
  42076. void fileClicked (const File& f, const MouseEvent& e);
  42077. /** @internal */
  42078. void fileDoubleClicked (const File& f);
  42079. /** @internal */
  42080. bool isFileSuitable (const File& file) const;
  42081. /** @internal */
  42082. bool isDirectorySuitable (const File&) const;
  42083. /** @internal */
  42084. FilePreviewComponent* getPreviewComponent() const noexcept;
  42085. protected:
  42086. /** Returns a list of names and paths for the default places the user might want to look.
  42087. Use an empty string to indicate a section break.
  42088. */
  42089. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  42090. private:
  42091. ScopedPointer <DirectoryContentsList> fileList;
  42092. const FileFilter* fileFilter;
  42093. int flags;
  42094. File currentRoot;
  42095. Array<File> chosenFiles;
  42096. ListenerList <FileBrowserListener> listeners;
  42097. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  42098. FilePreviewComponent* previewComp;
  42099. ComboBox currentPathBox;
  42100. TextEditor filenameBox;
  42101. Label fileLabel;
  42102. ScopedPointer<Button> goUpButton;
  42103. TimeSliceThread thread;
  42104. void sendListenerChangeMessage();
  42105. bool isFileOrDirSuitable (const File& f) const;
  42106. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  42107. };
  42108. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42109. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  42110. #endif
  42111. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42112. #endif
  42113. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42114. /*** Start of inlined file: juce_FileChooser.h ***/
  42115. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42116. #define __JUCE_FILECHOOSER_JUCEHEADER__
  42117. /**
  42118. Creates a dialog box to choose a file or directory to load or save.
  42119. To use a FileChooser:
  42120. - create one (as a local stack variable is the neatest way)
  42121. - call one of its browseFor.. methods
  42122. - if this returns true, the user has selected a file, so you can retrieve it
  42123. with the getResult() method.
  42124. e.g. @code
  42125. void loadMooseFile()
  42126. {
  42127. FileChooser myChooser ("Please select the moose you want to load...",
  42128. File::getSpecialLocation (File::userHomeDirectory),
  42129. "*.moose");
  42130. if (myChooser.browseForFileToOpen())
  42131. {
  42132. File mooseFile (myChooser.getResult());
  42133. loadMoose (mooseFile);
  42134. }
  42135. }
  42136. @endcode
  42137. */
  42138. class JUCE_API FileChooser
  42139. {
  42140. public:
  42141. /** Creates a FileChooser.
  42142. After creating one of these, use one of the browseFor... methods to display it.
  42143. @param dialogBoxTitle a text string to display in the dialog box to
  42144. tell the user what's going on
  42145. @param initialFileOrDirectory the file or directory that should be selected when
  42146. the dialog box opens. If this parameter is set to
  42147. File::nonexistent, a sensible default directory
  42148. will be used instead.
  42149. @param filePatternsAllowed a set of file patterns to specify which files can be
  42150. selected - each pattern should be separated by a
  42151. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  42152. empty string means that all files are allowed
  42153. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  42154. possible; if false, then a Juce-based browser dialog
  42155. box will always be used
  42156. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  42157. */
  42158. FileChooser (const String& dialogBoxTitle,
  42159. const File& initialFileOrDirectory = File::nonexistent,
  42160. const String& filePatternsAllowed = String::empty,
  42161. bool useOSNativeDialogBox = true);
  42162. /** Destructor. */
  42163. ~FileChooser();
  42164. /** Shows a dialog box to choose a file to open.
  42165. This will display the dialog box modally, using an "open file" mode, so that
  42166. it won't allow non-existent files or directories to be chosen.
  42167. @param previewComponent an optional component to display inside the dialog
  42168. box to show special info about the files that the user
  42169. is browsing. The component will not be deleted by this
  42170. object, so the caller must take care of it.
  42171. @returns true if the user selected a file, in which case, use the getResult()
  42172. method to find out what it was. Returns false if they cancelled instead.
  42173. @see browseForFileToSave, browseForDirectory
  42174. */
  42175. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  42176. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  42177. The files that are returned can be obtained by calling getResults(). See
  42178. browseForFileToOpen() for more info about the behaviour of this method.
  42179. */
  42180. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  42181. /** Shows a dialog box to choose a file to save.
  42182. This will display the dialog box modally, using an "save file" mode, so it
  42183. will allow non-existent files to be chosen, but not directories.
  42184. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  42185. the user if they're sure they want to overwrite a file that already
  42186. exists
  42187. @returns true if the user chose a file and pressed 'ok', in which case, use
  42188. the getResult() method to find out what the file was. Returns false
  42189. if they cancelled instead.
  42190. @see browseForFileToOpen, browseForDirectory
  42191. */
  42192. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  42193. /** Shows a dialog box to choose a directory.
  42194. This will display the dialog box modally, using an "open directory" mode, so it
  42195. will only allow directories to be returned, not files.
  42196. @returns true if the user chose a directory and pressed 'ok', in which case, use
  42197. the getResult() method to find out what they chose. Returns false
  42198. if they cancelled instead.
  42199. @see browseForFileToOpen, browseForFileToSave
  42200. */
  42201. bool browseForDirectory();
  42202. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  42203. The files that are returned can be obtained by calling getResults(). See
  42204. browseForFileToOpen() for more info about the behaviour of this method.
  42205. */
  42206. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  42207. /** Returns the last file that was chosen by one of the browseFor methods.
  42208. After calling the appropriate browseFor... method, this method lets you
  42209. find out what file or directory they chose.
  42210. Note that the file returned is only valid if the browse method returned true (i.e.
  42211. if the user pressed 'ok' rather than cancelling).
  42212. If you're using a multiple-file select, then use the getResults() method instead,
  42213. to obtain the list of all files chosen.
  42214. @see getResults
  42215. */
  42216. const File getResult() const;
  42217. /** Returns a list of all the files that were chosen during the last call to a
  42218. browse method.
  42219. This array may be empty if no files were chosen, or can contain multiple entries
  42220. if multiple files were chosen.
  42221. @see getResult
  42222. */
  42223. const Array<File>& getResults() const;
  42224. private:
  42225. String title, filters;
  42226. File startingFile;
  42227. Array<File> results;
  42228. bool useNativeDialogBox;
  42229. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  42230. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42231. FilePreviewComponent* previewComponent);
  42232. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  42233. const String& filters, bool selectsDirectories, bool selectsFiles,
  42234. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42235. FilePreviewComponent* previewComponent);
  42236. JUCE_LEAK_DETECTOR (FileChooser);
  42237. };
  42238. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  42239. /*** End of inlined file: juce_FileChooser.h ***/
  42240. #endif
  42241. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42242. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  42243. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42244. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42245. /*** Start of inlined file: juce_ResizableWindow.h ***/
  42246. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42247. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42248. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  42249. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42250. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42251. /*** Start of inlined file: juce_DropShadower.h ***/
  42252. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42253. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  42254. /**
  42255. Adds a drop-shadow to a component.
  42256. This object creates and manages a set of components which sit around a
  42257. component, creating a gaussian shadow around it. The components will track
  42258. the position of the component and if it's brought to the front they'll also
  42259. follow this.
  42260. For desktop windows you don't need to use this class directly - just
  42261. set the Component::windowHasDropShadow flag when calling
  42262. Component::addToDesktop(), and the system will create one of these if it's
  42263. needed (which it obviously isn't on the Mac, for example).
  42264. */
  42265. class JUCE_API DropShadower : public ComponentListener
  42266. {
  42267. public:
  42268. /** Creates a DropShadower.
  42269. @param alpha the opacity of the shadows, from 0 to 1.0
  42270. @param xOffset the horizontal displacement of the shadow, in pixels
  42271. @param yOffset the vertical displacement of the shadow, in pixels
  42272. @param blurRadius the radius of the blur to use for creating the shadow
  42273. */
  42274. DropShadower (float alpha = 0.5f,
  42275. int xOffset = 1,
  42276. int yOffset = 5,
  42277. float blurRadius = 10.0f);
  42278. /** Destructor. */
  42279. virtual ~DropShadower();
  42280. /** Attaches the DropShadower to the component you want to shadow. */
  42281. void setOwner (Component* componentToFollow);
  42282. /** @internal */
  42283. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42284. /** @internal */
  42285. void componentBroughtToFront (Component& component);
  42286. /** @internal */
  42287. void componentParentHierarchyChanged (Component& component);
  42288. /** @internal */
  42289. void componentVisibilityChanged (Component& component);
  42290. private:
  42291. Component* owner;
  42292. OwnedArray<Component> shadowWindows;
  42293. Image shadowImageSections[12];
  42294. const int xOffset, yOffset;
  42295. const float alpha, blurRadius;
  42296. bool reentrant;
  42297. void updateShadows();
  42298. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  42299. void bringShadowWindowsToFront();
  42300. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  42301. };
  42302. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  42303. /*** End of inlined file: juce_DropShadower.h ***/
  42304. /**
  42305. A base class for top-level windows.
  42306. This class is used for components that are considered a major part of your
  42307. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  42308. etc. Things like menus that pop up briefly aren't derived from it.
  42309. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  42310. could itself be the child of another component.
  42311. The class manages a list of all instances of top-level windows that are in use,
  42312. and each one is also given the concept of being "active". The active window is
  42313. one that is actively being used by the user. This isn't quite the same as the
  42314. component with the keyboard focus, because there may be a popup menu or other
  42315. temporary window which gets keyboard focus while the active top level window is
  42316. unchanged.
  42317. A top-level window also has an optional drop-shadow.
  42318. @see ResizableWindow, DocumentWindow, DialogWindow
  42319. */
  42320. class JUCE_API TopLevelWindow : public Component
  42321. {
  42322. public:
  42323. /** Creates a TopLevelWindow.
  42324. @param name the name to give the component
  42325. @param addToDesktop if true, the window will be automatically added to the
  42326. desktop; if false, you can use it as a child component
  42327. */
  42328. TopLevelWindow (const String& name, bool addToDesktop);
  42329. /** Destructor. */
  42330. ~TopLevelWindow();
  42331. /** True if this is currently the TopLevelWindow that is actively being used.
  42332. This isn't quite the same as having keyboard focus, because the focus may be
  42333. on a child component or a temporary pop-up menu, etc, while this window is
  42334. still considered to be active.
  42335. @see activeWindowStatusChanged
  42336. */
  42337. bool isActiveWindow() const noexcept { return windowIsActive_; }
  42338. /** This will set the bounds of the window so that it's centred in front of another
  42339. window.
  42340. If your app has a few windows open and want to pop up a dialog box for one of
  42341. them, you can use this to show it in front of the relevent parent window, which
  42342. is a bit neater than just having it appear in the middle of the screen.
  42343. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  42344. be used instead. If no window is focused, it'll just default to the middle of the
  42345. screen.
  42346. */
  42347. void centreAroundComponent (Component* componentToCentreAround,
  42348. int width, int height);
  42349. /** Turns the drop-shadow on and off. */
  42350. void setDropShadowEnabled (bool useShadow);
  42351. /** Sets whether an OS-native title bar will be used, or a Juce one.
  42352. @see isUsingNativeTitleBar
  42353. */
  42354. void setUsingNativeTitleBar (bool useNativeTitleBar);
  42355. /** Returns true if the window is currently using an OS-native title bar.
  42356. @see setUsingNativeTitleBar
  42357. */
  42358. bool isUsingNativeTitleBar() const noexcept { return useNativeTitleBar && isOnDesktop(); }
  42359. /** Returns the number of TopLevelWindow objects currently in use.
  42360. @see getTopLevelWindow
  42361. */
  42362. static int getNumTopLevelWindows() noexcept;
  42363. /** Returns one of the TopLevelWindow objects currently in use.
  42364. The index is 0 to (getNumTopLevelWindows() - 1).
  42365. */
  42366. static TopLevelWindow* getTopLevelWindow (int index) noexcept;
  42367. /** Returns the currently-active top level window.
  42368. There might not be one, of course, so this can return 0.
  42369. */
  42370. static TopLevelWindow* getActiveTopLevelWindow() noexcept;
  42371. /** @internal */
  42372. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = nullptr);
  42373. protected:
  42374. /** This callback happens when this window becomes active or inactive.
  42375. @see isActiveWindow
  42376. */
  42377. virtual void activeWindowStatusChanged();
  42378. /** @internal */
  42379. void focusOfChildComponentChanged (FocusChangeType cause);
  42380. /** @internal */
  42381. void parentHierarchyChanged();
  42382. /** @internal */
  42383. virtual int getDesktopWindowStyleFlags() const;
  42384. /** @internal */
  42385. void recreateDesktopWindow();
  42386. /** @internal */
  42387. void visibilityChanged();
  42388. private:
  42389. friend class TopLevelWindowManager;
  42390. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  42391. ScopedPointer <DropShadower> shadower;
  42392. void setWindowActive (bool isNowActive);
  42393. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  42394. };
  42395. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42396. /*** End of inlined file: juce_TopLevelWindow.h ***/
  42397. /*** Start of inlined file: juce_ComponentDragger.h ***/
  42398. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42399. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42400. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42401. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42402. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42403. /**
  42404. A class that imposes restrictions on a Component's size or position.
  42405. This is used by classes such as ResizableCornerComponent,
  42406. ResizableBorderComponent and ResizableWindow.
  42407. The base class can impose some basic size and position limits, but you can
  42408. also subclass this for custom uses.
  42409. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  42410. */
  42411. class JUCE_API ComponentBoundsConstrainer
  42412. {
  42413. public:
  42414. /** When first created, the object will not impose any restrictions on the components. */
  42415. ComponentBoundsConstrainer() noexcept;
  42416. /** Destructor. */
  42417. virtual ~ComponentBoundsConstrainer();
  42418. /** Imposes a minimum width limit. */
  42419. void setMinimumWidth (int minimumWidth) noexcept;
  42420. /** Returns the current minimum width. */
  42421. int getMinimumWidth() const noexcept { return minW; }
  42422. /** Imposes a maximum width limit. */
  42423. void setMaximumWidth (int maximumWidth) noexcept;
  42424. /** Returns the current maximum width. */
  42425. int getMaximumWidth() const noexcept { return maxW; }
  42426. /** Imposes a minimum height limit. */
  42427. void setMinimumHeight (int minimumHeight) noexcept;
  42428. /** Returns the current minimum height. */
  42429. int getMinimumHeight() const noexcept { return minH; }
  42430. /** Imposes a maximum height limit. */
  42431. void setMaximumHeight (int maximumHeight) noexcept;
  42432. /** Returns the current maximum height. */
  42433. int getMaximumHeight() const noexcept { return maxH; }
  42434. /** Imposes a minimum width and height limit. */
  42435. void setMinimumSize (int minimumWidth,
  42436. int minimumHeight) noexcept;
  42437. /** Imposes a maximum width and height limit. */
  42438. void setMaximumSize (int maximumWidth,
  42439. int maximumHeight) noexcept;
  42440. /** Set all the maximum and minimum dimensions. */
  42441. void setSizeLimits (int minimumWidth,
  42442. int minimumHeight,
  42443. int maximumWidth,
  42444. int maximumHeight) noexcept;
  42445. /** Sets the amount by which the component is allowed to go off-screen.
  42446. The values indicate how many pixels must remain on-screen when dragged off
  42447. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  42448. when the component goes off the top of the screen, its y-position will be
  42449. clipped so that there are always at least 10 pixels on-screen. In other words,
  42450. the lowest y-position it can take would be (10 - the component's height).
  42451. If you pass 0 or less for one of these amounts, the component is allowed
  42452. to move beyond that edge completely, with no restrictions at all.
  42453. If you pass a very large number (i.e. larger that the dimensions of the
  42454. component itself), then the component won't be allowed to overlap that
  42455. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  42456. the component will bump into the left side of the screen and go no further.
  42457. */
  42458. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  42459. int minimumWhenOffTheLeft,
  42460. int minimumWhenOffTheBottom,
  42461. int minimumWhenOffTheRight) noexcept;
  42462. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42463. int getMinimumWhenOffTheTop() const noexcept { return minOffTop; }
  42464. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42465. int getMinimumWhenOffTheLeft() const noexcept { return minOffLeft; }
  42466. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42467. int getMinimumWhenOffTheBottom() const noexcept { return minOffBottom; }
  42468. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42469. int getMinimumWhenOffTheRight() const noexcept { return minOffRight; }
  42470. /** Specifies a width-to-height ratio that the resizer should always maintain.
  42471. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  42472. will always be maintained as this multiple of the height.
  42473. @see setResizeLimits
  42474. */
  42475. void setFixedAspectRatio (double widthOverHeight) noexcept;
  42476. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  42477. If no aspect ratio is being enforced, this will return 0.
  42478. */
  42479. double getFixedAspectRatio() const noexcept;
  42480. /** This callback changes the given co-ordinates to impose whatever the current
  42481. constraints are set to be.
  42482. @param bounds the target position that should be examined and adjusted
  42483. @param previousBounds the component's current size
  42484. @param limits the region in which the component can be positioned
  42485. @param isStretchingTop whether the top edge of the component is being resized
  42486. @param isStretchingLeft whether the left edge of the component is being resized
  42487. @param isStretchingBottom whether the bottom edge of the component is being resized
  42488. @param isStretchingRight whether the right edge of the component is being resized
  42489. */
  42490. virtual void checkBounds (Rectangle<int>& bounds,
  42491. const Rectangle<int>& previousBounds,
  42492. const Rectangle<int>& limits,
  42493. bool isStretchingTop,
  42494. bool isStretchingLeft,
  42495. bool isStretchingBottom,
  42496. bool isStretchingRight);
  42497. /** This callback happens when the resizer is about to start dragging. */
  42498. virtual void resizeStart();
  42499. /** This callback happens when the resizer has finished dragging. */
  42500. virtual void resizeEnd();
  42501. /** Checks the given bounds, and then sets the component to the corrected size. */
  42502. void setBoundsForComponent (Component* component,
  42503. const Rectangle<int>& bounds,
  42504. bool isStretchingTop,
  42505. bool isStretchingLeft,
  42506. bool isStretchingBottom,
  42507. bool isStretchingRight);
  42508. /** Performs a check on the current size of a component, and moves or resizes
  42509. it if it fails the constraints.
  42510. */
  42511. void checkComponentBounds (Component* component);
  42512. /** Called by setBoundsForComponent() to apply a new constrained size to a
  42513. component.
  42514. By default this just calls setBounds(), but it virtual in case it's needed for
  42515. extremely cunning purposes.
  42516. */
  42517. virtual void applyBoundsToComponent (Component* component,
  42518. const Rectangle<int>& bounds);
  42519. private:
  42520. int minW, maxW, minH, maxH;
  42521. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  42522. double aspectRatio;
  42523. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  42524. };
  42525. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42526. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42527. /**
  42528. An object to take care of the logic for dragging components around with the mouse.
  42529. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  42530. then in your mouseDrag() callback, call dragComponent().
  42531. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  42532. to limit the component's position and keep it on-screen.
  42533. e.g. @code
  42534. class MyDraggableComp
  42535. {
  42536. ComponentDragger myDragger;
  42537. void mouseDown (const MouseEvent& e)
  42538. {
  42539. myDragger.startDraggingComponent (this, e);
  42540. }
  42541. void mouseDrag (const MouseEvent& e)
  42542. {
  42543. myDragger.dragComponent (this, e, nullptr);
  42544. }
  42545. };
  42546. @endcode
  42547. */
  42548. class JUCE_API ComponentDragger
  42549. {
  42550. public:
  42551. /** Creates a ComponentDragger. */
  42552. ComponentDragger();
  42553. /** Destructor. */
  42554. virtual ~ComponentDragger();
  42555. /** Call this from your component's mouseDown() method, to prepare for dragging.
  42556. @param componentToDrag the component that you want to drag
  42557. @param e the mouse event that is triggering the drag
  42558. @see dragComponent
  42559. */
  42560. void startDraggingComponent (Component* componentToDrag,
  42561. const MouseEvent& e);
  42562. /** Call this from your mouseDrag() callback to move the component.
  42563. This will move the component, but will first check the validity of the
  42564. component's new position using the checkPosition() method, which you
  42565. can override if you need to enforce special positioning limits on the
  42566. component.
  42567. @param componentToDrag the component that you want to drag
  42568. @param e the current mouse-drag event
  42569. @param constrainer an optional constrainer object that should be used
  42570. to apply limits to the component's position. Pass
  42571. null if you don't want to contrain the movement.
  42572. @see startDraggingComponent
  42573. */
  42574. void dragComponent (Component* componentToDrag,
  42575. const MouseEvent& e,
  42576. ComponentBoundsConstrainer* constrainer);
  42577. private:
  42578. Point<int> mouseDownWithinTarget;
  42579. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  42580. };
  42581. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42582. /*** End of inlined file: juce_ComponentDragger.h ***/
  42583. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  42584. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42585. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42586. /**
  42587. A component that resizes its parent component when dragged.
  42588. This component forms a frame around the edge of a component, allowing it to
  42589. be dragged by the edges or corners to resize it - like the way windows are
  42590. resized in MSWindows or Linux.
  42591. To use it, just add it to your component, making it fill the entire parent component
  42592. (there's a mouse hit-test that only traps mouse-events which land around the
  42593. edge of the component, so it's even ok to put it on top of any other components
  42594. you're using). Make sure you rescale the resizer component to fill the parent
  42595. each time the parent's size changes.
  42596. @see ResizableCornerComponent
  42597. */
  42598. class JUCE_API ResizableBorderComponent : public Component
  42599. {
  42600. public:
  42601. /** Creates a resizer.
  42602. Pass in the target component which you want to be resized when this one is
  42603. dragged.
  42604. The target component will usually be a parent of the resizer component, but this
  42605. isn't mandatory.
  42606. Remember that when the target component is resized, it'll need to move and
  42607. resize this component to keep it in place, as this won't happen automatically.
  42608. If the constrainer parameter is non-zero, then this object will be used to enforce
  42609. limits on the size and position that the component can be stretched to. Make sure
  42610. that the constrainer isn't deleted while still in use by this object.
  42611. @see ComponentBoundsConstrainer
  42612. */
  42613. ResizableBorderComponent (Component* componentToResize,
  42614. ComponentBoundsConstrainer* constrainer);
  42615. /** Destructor. */
  42616. ~ResizableBorderComponent();
  42617. /** Specifies how many pixels wide the draggable edges of this component are.
  42618. @see getBorderThickness
  42619. */
  42620. void setBorderThickness (const BorderSize<int>& newBorderSize);
  42621. /** Returns the number of pixels wide that the draggable edges of this component are.
  42622. @see setBorderThickness
  42623. */
  42624. const BorderSize<int> getBorderThickness() const;
  42625. /** Represents the different sections of a resizable border, which allow it to
  42626. resized in different ways.
  42627. */
  42628. class Zone
  42629. {
  42630. public:
  42631. enum Zones
  42632. {
  42633. centre = 0,
  42634. left = 1,
  42635. top = 2,
  42636. right = 4,
  42637. bottom = 8
  42638. };
  42639. /** Creates a Zone from a combination of the flags in \enum Zones. */
  42640. explicit Zone (int zoneFlags = 0) noexcept;
  42641. Zone (const Zone& other) noexcept;
  42642. Zone& operator= (const Zone& other) noexcept;
  42643. bool operator== (const Zone& other) const noexcept;
  42644. bool operator!= (const Zone& other) const noexcept;
  42645. /** Given a point within a rectangle with a resizable border, this returns the
  42646. zone that the point lies within.
  42647. */
  42648. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  42649. const BorderSize<int>& border,
  42650. const Point<int>& position);
  42651. /** Returns an appropriate mouse-cursor for this resize zone. */
  42652. const MouseCursor getMouseCursor() const noexcept;
  42653. /** Returns true if dragging this zone will move the enire object without resizing it. */
  42654. bool isDraggingWholeObject() const noexcept { return zone == centre; }
  42655. /** Returns true if dragging this zone will move the object's left edge. */
  42656. bool isDraggingLeftEdge() const noexcept { return (zone & left) != 0; }
  42657. /** Returns true if dragging this zone will move the object's right edge. */
  42658. bool isDraggingRightEdge() const noexcept { return (zone & right) != 0; }
  42659. /** Returns true if dragging this zone will move the object's top edge. */
  42660. bool isDraggingTopEdge() const noexcept { return (zone & top) != 0; }
  42661. /** Returns true if dragging this zone will move the object's bottom edge. */
  42662. bool isDraggingBottomEdge() const noexcept { return (zone & bottom) != 0; }
  42663. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  42664. applies to.
  42665. */
  42666. template <typename ValueType>
  42667. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  42668. const Point<ValueType>& distance) const noexcept
  42669. {
  42670. if (isDraggingWholeObject())
  42671. return original + distance;
  42672. if (isDraggingLeftEdge())
  42673. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  42674. if (isDraggingRightEdge())
  42675. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  42676. if (isDraggingTopEdge())
  42677. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  42678. if (isDraggingBottomEdge())
  42679. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  42680. return original;
  42681. }
  42682. /** Returns the raw flags for this zone. */
  42683. int getZoneFlags() const noexcept { return zone; }
  42684. private:
  42685. int zone;
  42686. };
  42687. protected:
  42688. /** @internal */
  42689. void paint (Graphics& g);
  42690. /** @internal */
  42691. void mouseEnter (const MouseEvent& e);
  42692. /** @internal */
  42693. void mouseMove (const MouseEvent& e);
  42694. /** @internal */
  42695. void mouseDown (const MouseEvent& e);
  42696. /** @internal */
  42697. void mouseDrag (const MouseEvent& e);
  42698. /** @internal */
  42699. void mouseUp (const MouseEvent& e);
  42700. /** @internal */
  42701. bool hitTest (int x, int y);
  42702. private:
  42703. WeakReference<Component> component;
  42704. ComponentBoundsConstrainer* constrainer;
  42705. BorderSize<int> borderSize;
  42706. Rectangle<int> originalBounds;
  42707. Zone mouseZone;
  42708. void updateMouseZone (const MouseEvent& e);
  42709. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  42710. };
  42711. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42712. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  42713. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  42714. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42715. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42716. /** A component that resizes a parent component when dragged.
  42717. This is the small triangular stripey resizer component you get in the bottom-right
  42718. of windows (more commonly on the Mac than Windows). Put one in the corner of
  42719. a larger component and it will automatically resize its parent when it gets dragged
  42720. around.
  42721. @see ResizableFrameComponent
  42722. */
  42723. class JUCE_API ResizableCornerComponent : public Component
  42724. {
  42725. public:
  42726. /** Creates a resizer.
  42727. Pass in the target component which you want to be resized when this one is
  42728. dragged.
  42729. The target component will usually be a parent of the resizer component, but this
  42730. isn't mandatory.
  42731. Remember that when the target component is resized, it'll need to move and
  42732. resize this component to keep it in place, as this won't happen automatically.
  42733. If the constrainer parameter is non-zero, then this object will be used to enforce
  42734. limits on the size and position that the component can be stretched to. Make sure
  42735. that the constrainer isn't deleted while still in use by this object. If you
  42736. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  42737. @see ComponentBoundsConstrainer
  42738. */
  42739. ResizableCornerComponent (Component* componentToResize,
  42740. ComponentBoundsConstrainer* constrainer);
  42741. /** Destructor. */
  42742. ~ResizableCornerComponent();
  42743. protected:
  42744. /** @internal */
  42745. void paint (Graphics& g);
  42746. /** @internal */
  42747. void mouseDown (const MouseEvent& e);
  42748. /** @internal */
  42749. void mouseDrag (const MouseEvent& e);
  42750. /** @internal */
  42751. void mouseUp (const MouseEvent& e);
  42752. /** @internal */
  42753. bool hitTest (int x, int y);
  42754. private:
  42755. WeakReference<Component> component;
  42756. ComponentBoundsConstrainer* constrainer;
  42757. Rectangle<int> originalBounds;
  42758. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  42759. };
  42760. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42761. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  42762. /**
  42763. A base class for top-level windows that can be dragged around and resized.
  42764. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  42765. to give it a component that will remain positioned inside it (leaving a gap around
  42766. the edges for a border).
  42767. It's not advisable to add child components directly to a ResizableWindow: put them
  42768. inside your content component instead. And overriding methods like resized(), moved(), etc
  42769. is also not recommended - instead override these methods for your content component.
  42770. (If for some obscure reason you do need to override these methods, always remember to
  42771. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  42772. decorations correctly).
  42773. By default resizing isn't enabled - use the setResizable() method to enable it and
  42774. to choose the style of resizing to use.
  42775. @see TopLevelWindow
  42776. */
  42777. class JUCE_API ResizableWindow : public TopLevelWindow
  42778. {
  42779. public:
  42780. /** Creates a ResizableWindow.
  42781. This constructor doesn't specify a background colour, so the LookAndFeel's default
  42782. background colour will be used.
  42783. @param name the name to give the component
  42784. @param addToDesktop if true, the window will be automatically added to the
  42785. desktop; if false, you can use it as a child component
  42786. */
  42787. ResizableWindow (const String& name,
  42788. bool addToDesktop);
  42789. /** Creates a ResizableWindow.
  42790. @param name the name to give the component
  42791. @param backgroundColour the colour to use for filling the window's background.
  42792. @param addToDesktop if true, the window will be automatically added to the
  42793. desktop; if false, you can use it as a child component
  42794. */
  42795. ResizableWindow (const String& name,
  42796. const Colour& backgroundColour,
  42797. bool addToDesktop);
  42798. /** Destructor.
  42799. If a content component has been set with setContentOwned(), it will be deleted.
  42800. */
  42801. ~ResizableWindow();
  42802. /** Returns the colour currently being used for the window's background.
  42803. As a convenience the window will fill itself with this colour, but you
  42804. can override the paint() method if you need more customised behaviour.
  42805. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  42806. @see setBackgroundColour
  42807. */
  42808. const Colour getBackgroundColour() const noexcept;
  42809. /** Changes the colour currently being used for the window's background.
  42810. As a convenience the window will fill itself with this colour, but you
  42811. can override the paint() method if you need more customised behaviour.
  42812. Note that the opaque state of this window is altered by this call to reflect
  42813. the opacity of the colour passed-in. On window systems which can't support
  42814. semi-transparent windows this might cause problems, (though it's unlikely you'll
  42815. be using this class as a base for a semi-transparent component anyway).
  42816. You can also use the ResizableWindow::backgroundColourId colour id to set
  42817. this colour.
  42818. @see getBackgroundColour
  42819. */
  42820. void setBackgroundColour (const Colour& newColour);
  42821. /** Make the window resizable or fixed.
  42822. @param shouldBeResizable whether it's resizable at all
  42823. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  42824. bottom-right; if false, it'll use a ResizableBorderComponent
  42825. around the edge
  42826. @see setResizeLimits, isResizable
  42827. */
  42828. void setResizable (bool shouldBeResizable,
  42829. bool useBottomRightCornerResizer);
  42830. /** True if resizing is enabled.
  42831. @see setResizable
  42832. */
  42833. bool isResizable() const noexcept;
  42834. /** This sets the maximum and minimum sizes for the window.
  42835. If the window's current size is outside these limits, it will be resized to
  42836. make sure it's within them.
  42837. Calling setBounds() on the component will bypass any size checking - it's only when
  42838. the window is being resized by the user that these values are enforced.
  42839. @see setResizable, setFixedAspectRatio
  42840. */
  42841. void setResizeLimits (int newMinimumWidth,
  42842. int newMinimumHeight,
  42843. int newMaximumWidth,
  42844. int newMaximumHeight) noexcept;
  42845. /** Returns the bounds constrainer object that this window is using.
  42846. You can access this to change its properties.
  42847. */
  42848. ComponentBoundsConstrainer* getConstrainer() noexcept { return constrainer; }
  42849. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  42850. A pointer to the object you pass in will be kept, but it won't be deleted
  42851. by this object, so it's the caller's responsiblity to manage it.
  42852. If you pass 0, then no contraints will be placed on the positioning of the window.
  42853. */
  42854. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  42855. /** Calls the window's setBounds method, after first checking these bounds
  42856. with the current constrainer.
  42857. @see setConstrainer
  42858. */
  42859. void setBoundsConstrained (const Rectangle<int>& bounds);
  42860. /** Returns true if the window is currently in full-screen mode.
  42861. @see setFullScreen
  42862. */
  42863. bool isFullScreen() const;
  42864. /** Puts the window into full-screen mode, or restores it to its normal size.
  42865. If true, the window will become full-screen; if false, it will return to the
  42866. last size it was before being made full-screen.
  42867. @see isFullScreen
  42868. */
  42869. void setFullScreen (bool shouldBeFullScreen);
  42870. /** Returns true if the window is currently minimised.
  42871. @see setMinimised
  42872. */
  42873. bool isMinimised() const;
  42874. /** Minimises the window, or restores it to its previous position and size.
  42875. When being un-minimised, it'll return to the last position and size it
  42876. was in before being minimised.
  42877. @see isMinimised
  42878. */
  42879. void setMinimised (bool shouldMinimise);
  42880. /** Returns a string which encodes the window's current size and position.
  42881. This string will encapsulate the window's size, position, and whether it's
  42882. in full-screen mode. It's intended for letting your application save and
  42883. restore a window's position.
  42884. Use the restoreWindowStateFromString() to restore from a saved state.
  42885. @see restoreWindowStateFromString
  42886. */
  42887. const String getWindowStateAsString();
  42888. /** Restores the window to a previously-saved size and position.
  42889. This restores the window's size, positon and full-screen status from an
  42890. string that was previously created with the getWindowStateAsString()
  42891. method.
  42892. @returns false if the string wasn't a valid window state
  42893. @see getWindowStateAsString
  42894. */
  42895. bool restoreWindowStateFromString (const String& previousState);
  42896. /** Returns the current content component.
  42897. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  42898. has yet been specified.
  42899. @see setContentOwned, setContentNonOwned
  42900. */
  42901. Component* getContentComponent() const noexcept { return contentComponent; }
  42902. /** Changes the current content component.
  42903. This sets a component that will be placed in the centre of the ResizableWindow,
  42904. (leaving a space around the edge for the border).
  42905. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42906. with addChildComponent(). Instead, add them to the content component.
  42907. @param newContentComponent the new component to use - this component will be deleted when it's
  42908. no longer needed (i.e. when the window is deleted or a new content
  42909. component is set for it). To set a component that this window will not
  42910. delete, call setContentNonOwned() instead.
  42911. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42912. such that it always fits around the size of the content component. If false,
  42913. the new content will be resized to fit the current space available.
  42914. */
  42915. void setContentOwned (Component* newContentComponent,
  42916. bool resizeToFitWhenContentChangesSize);
  42917. /** Changes the current content component.
  42918. This sets a component that will be placed in the centre of the ResizableWindow,
  42919. (leaving a space around the edge for the border).
  42920. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42921. with addChildComponent(). Instead, add them to the content component.
  42922. @param newContentComponent the new component to use - this component will NOT be deleted by this
  42923. component, so it's the caller's responsibility to manage its lifetime (it's
  42924. ok to delete it while this window is still using it). To set a content
  42925. component that the window will delete, call setContentOwned() instead.
  42926. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42927. such that it always fits around the size of the content component. If false,
  42928. the new content will be resized to fit the current space available.
  42929. */
  42930. void setContentNonOwned (Component* newContentComponent,
  42931. bool resizeToFitWhenContentChangesSize);
  42932. /** Removes the current content component.
  42933. If the previous content component was added with setContentOwned(), it will also be deleted. If
  42934. it was added with setContentNonOwned(), it will simply be removed from this component.
  42935. */
  42936. void clearContentComponent();
  42937. /** Changes the window so that the content component ends up with the specified size.
  42938. This is basically a setSize call on the window, but which adds on the borders,
  42939. so you can specify the content component's target size.
  42940. */
  42941. void setContentComponentSize (int width, int height);
  42942. /** Returns the width of the frame to use around the window.
  42943. @see getContentComponentBorder
  42944. */
  42945. virtual const BorderSize<int> getBorderThickness();
  42946. /** Returns the insets to use when positioning the content component.
  42947. @see getBorderThickness
  42948. */
  42949. virtual const BorderSize<int> getContentComponentBorder();
  42950. /** A set of colour IDs to use to change the colour of various aspects of the window.
  42951. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42952. methods.
  42953. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42954. */
  42955. enum ColourIds
  42956. {
  42957. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  42958. };
  42959. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  42960. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  42961. bool deleteOldOne = true,
  42962. bool resizeToFit = false));
  42963. protected:
  42964. /** @internal */
  42965. void paint (Graphics& g);
  42966. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42967. void moved();
  42968. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42969. void resized();
  42970. /** @internal */
  42971. void mouseDown (const MouseEvent& e);
  42972. /** @internal */
  42973. void mouseDrag (const MouseEvent& e);
  42974. /** @internal */
  42975. void lookAndFeelChanged();
  42976. /** @internal */
  42977. void childBoundsChanged (Component* child);
  42978. /** @internal */
  42979. void parentSizeChanged();
  42980. /** @internal */
  42981. void visibilityChanged();
  42982. /** @internal */
  42983. void activeWindowStatusChanged();
  42984. /** @internal */
  42985. int getDesktopWindowStyleFlags() const;
  42986. #if JUCE_DEBUG
  42987. /** Overridden to warn people about adding components directly to this component
  42988. instead of using setContentOwned().
  42989. If you know what you're doing and are sure you really want to add a component, specify
  42990. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42991. */
  42992. void addChildComponent (Component* child, int zOrder = -1);
  42993. /** Overridden to warn people about adding components directly to this component
  42994. instead of using setContentOwned().
  42995. If you know what you're doing and are sure you really want to add a component, specify
  42996. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42997. */
  42998. void addAndMakeVisible (Component* child, int zOrder = -1);
  42999. #endif
  43000. ScopedPointer <ResizableCornerComponent> resizableCorner;
  43001. ScopedPointer <ResizableBorderComponent> resizableBorder;
  43002. private:
  43003. Component::SafePointer <Component> contentComponent;
  43004. bool ownsContentComponent, resizeToFitContent, fullscreen;
  43005. ComponentDragger dragger;
  43006. Rectangle<int> lastNonFullScreenPos;
  43007. ComponentBoundsConstrainer defaultConstrainer;
  43008. ComponentBoundsConstrainer* constrainer;
  43009. #if JUCE_DEBUG
  43010. bool hasBeenResized;
  43011. #endif
  43012. void updateLastPos();
  43013. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  43014. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  43015. // The parameters for these methods have changed - please update your code!
  43016. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  43017. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  43018. #endif
  43019. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  43020. };
  43021. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43022. /*** End of inlined file: juce_ResizableWindow.h ***/
  43023. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  43024. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43025. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43026. /**
  43027. A glyph from a particular font, with a particular size, style,
  43028. typeface and position.
  43029. @see GlyphArrangement, Font
  43030. */
  43031. class JUCE_API PositionedGlyph
  43032. {
  43033. public:
  43034. PositionedGlyph (const PositionedGlyph& other);
  43035. /** Returns the character the glyph represents. */
  43036. juce_wchar getCharacter() const { return character; }
  43037. /** Checks whether the glyph is actually empty. */
  43038. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  43039. /** Returns the position of the glyph's left-hand edge. */
  43040. float getLeft() const { return x; }
  43041. /** Returns the position of the glyph's right-hand edge. */
  43042. float getRight() const { return x + w; }
  43043. /** Returns the y position of the glyph's baseline. */
  43044. float getBaselineY() const { return y; }
  43045. /** Returns the y position of the top of the glyph. */
  43046. float getTop() const { return y - font.getAscent(); }
  43047. /** Returns the y position of the bottom of the glyph. */
  43048. float getBottom() const { return y + font.getDescent(); }
  43049. /** Returns the bounds of the glyph. */
  43050. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  43051. /** Shifts the glyph's position by a relative amount. */
  43052. void moveBy (float deltaX, float deltaY);
  43053. /** Draws the glyph into a graphics context. */
  43054. void draw (const Graphics& g) const;
  43055. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  43056. void draw (const Graphics& g, const AffineTransform& transform) const;
  43057. /** Returns the path for this glyph.
  43058. @param path the glyph's outline will be appended to this path
  43059. */
  43060. void createPath (Path& path) const;
  43061. /** Checks to see if a point lies within this glyph. */
  43062. bool hitTest (float x, float y) const;
  43063. private:
  43064. friend class GlyphArrangement;
  43065. float x, y, w;
  43066. Font font;
  43067. juce_wchar character;
  43068. int glyph;
  43069. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  43070. JUCE_LEAK_DETECTOR (PositionedGlyph);
  43071. };
  43072. /**
  43073. A set of glyphs, each with a position.
  43074. You can create a GlyphArrangement, text to it and then draw it onto a
  43075. graphics context. It's used internally by the text methods in the
  43076. Graphics class, but can be used directly if more control is needed.
  43077. @see Font, PositionedGlyph
  43078. */
  43079. class JUCE_API GlyphArrangement
  43080. {
  43081. public:
  43082. /** Creates an empty arrangement. */
  43083. GlyphArrangement();
  43084. /** Takes a copy of another arrangement. */
  43085. GlyphArrangement (const GlyphArrangement& other);
  43086. /** Copies another arrangement onto this one.
  43087. To add another arrangement without clearing this one, use addGlyphArrangement().
  43088. */
  43089. GlyphArrangement& operator= (const GlyphArrangement& other);
  43090. /** Destructor. */
  43091. ~GlyphArrangement();
  43092. /** Returns the total number of glyphs in the arrangement. */
  43093. int getNumGlyphs() const noexcept { return glyphs.size(); }
  43094. /** Returns one of the glyphs from the arrangement.
  43095. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  43096. careful not to pass an out-of-range index here, as it
  43097. doesn't do any bounds-checking.
  43098. */
  43099. PositionedGlyph& getGlyph (int index) const;
  43100. /** Clears all text from the arrangement and resets it.
  43101. */
  43102. void clear();
  43103. /** Appends a line of text to the arrangement.
  43104. This will add the text as a single line, where x is the left-hand edge of the
  43105. first character, and y is the position for the text's baseline.
  43106. If the text contains new-lines or carriage-returns, this will ignore them - use
  43107. addJustifiedText() to add multi-line arrangements.
  43108. */
  43109. void addLineOfText (const Font& font,
  43110. const String& text,
  43111. float x, float y);
  43112. /** Adds a line of text, truncating it if it's wider than a specified size.
  43113. This is the same as addLineOfText(), but if the line's width exceeds the value
  43114. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  43115. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  43116. */
  43117. void addCurtailedLineOfText (const Font& font,
  43118. const String& text,
  43119. float x, float y,
  43120. float maxWidthPixels,
  43121. bool useEllipsis);
  43122. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  43123. This will add text to the arrangement, breaking it into new lines either where there
  43124. is a new-line or carriage-return character in the text, or where a line's width
  43125. exceeds the value set in maxLineWidth.
  43126. Each line that is added will be laid out using the flags set in horizontalLayout, so
  43127. the lines can be left- or right-justified, or centred horizontally in the space
  43128. between x and (x + maxLineWidth).
  43129. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  43130. lines will be placed below it, separated by a distance of font.getHeight().
  43131. */
  43132. void addJustifiedText (const Font& font,
  43133. const String& text,
  43134. float x, float y,
  43135. float maxLineWidth,
  43136. const Justification& horizontalLayout);
  43137. /** Tries to fit some text withing a given space.
  43138. This does its best to make the given text readable within the specified rectangle,
  43139. so it useful for labelling things.
  43140. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  43141. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  43142. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  43143. it's been truncated.
  43144. A Justification parameter lets you specify how the text is laid out within the rectangle,
  43145. both horizontally and vertically.
  43146. @see Graphics::drawFittedText
  43147. */
  43148. void addFittedText (const Font& font,
  43149. const String& text,
  43150. float x, float y, float width, float height,
  43151. const Justification& layout,
  43152. int maximumLinesToUse,
  43153. float minimumHorizontalScale = 0.7f);
  43154. /** Appends another glyph arrangement to this one. */
  43155. void addGlyphArrangement (const GlyphArrangement& other);
  43156. /** Draws this glyph arrangement to a graphics context.
  43157. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  43158. method, which renders the glyphs as filled vectors.
  43159. */
  43160. void draw (const Graphics& g) const;
  43161. /** Draws this glyph arrangement to a graphics context.
  43162. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  43163. method for non-transformed arrangements.
  43164. */
  43165. void draw (const Graphics& g, const AffineTransform& transform) const;
  43166. /** Converts the set of glyphs into a path.
  43167. @param path the glyphs' outlines will be appended to this path
  43168. */
  43169. void createPath (Path& path) const;
  43170. /** Looks for a glyph that contains the given co-ordinate.
  43171. @returns the index of the glyph, or -1 if none were found.
  43172. */
  43173. int findGlyphIndexAt (float x, float y) const;
  43174. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  43175. @param startIndex the first glyph to test
  43176. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  43177. startIndex will be included
  43178. @param includeWhitespace if true, the extent of any whitespace characters will also
  43179. be taken into account
  43180. */
  43181. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  43182. /** Shifts a set of glyphs by a given amount.
  43183. @param startIndex the first glyph to transform
  43184. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  43185. startIndex will be used
  43186. @param deltaX the amount to add to their x-positions
  43187. @param deltaY the amount to add to their y-positions
  43188. */
  43189. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  43190. float deltaX, float deltaY);
  43191. /** Removes a set of glyphs from the arrangement.
  43192. @param startIndex the first glyph to remove
  43193. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  43194. startIndex will be deleted
  43195. */
  43196. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  43197. /** Expands or compresses a set of glyphs horizontally.
  43198. @param startIndex the first glyph to transform
  43199. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  43200. startIndex will be used
  43201. @param horizontalScaleFactor how much to scale their horizontal width by
  43202. */
  43203. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  43204. float horizontalScaleFactor);
  43205. /** Justifies a set of glyphs within a given space.
  43206. This moves the glyphs as a block so that the whole thing is located within the
  43207. given rectangle with the specified layout.
  43208. If the Justification::horizontallyJustified flag is specified, each line will
  43209. be stretched out to fill the specified width.
  43210. */
  43211. void justifyGlyphs (int startIndex, int numGlyphs,
  43212. float x, float y, float width, float height,
  43213. const Justification& justification);
  43214. private:
  43215. OwnedArray <PositionedGlyph> glyphs;
  43216. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  43217. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  43218. const Justification& justification, float minimumHorizontalScale);
  43219. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  43220. JUCE_LEAK_DETECTOR (GlyphArrangement);
  43221. };
  43222. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43223. /*** End of inlined file: juce_GlyphArrangement.h ***/
  43224. /*** Start of inlined file: juce_AlertWindow.h ***/
  43225. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43226. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  43227. /*** Start of inlined file: juce_TextLayout.h ***/
  43228. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  43229. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  43230. class Graphics;
  43231. /**
  43232. A laid-out arrangement of text.
  43233. You can add text in different fonts to a TextLayout object, then call its
  43234. layout() method to word-wrap it into lines. The layout can then be drawn
  43235. using a graphics context.
  43236. It's handy if you've got a message to display, because you can format it,
  43237. measure the extent of the layout, and then create a suitably-sized window
  43238. to show it in.
  43239. @see Font, Graphics::drawFittedText, GlyphArrangement
  43240. */
  43241. class JUCE_API TextLayout
  43242. {
  43243. public:
  43244. /** Creates an empty text layout.
  43245. Text can then be appended using the appendText() method.
  43246. */
  43247. TextLayout();
  43248. /** Creates a copy of another layout object. */
  43249. TextLayout (const TextLayout& other);
  43250. /** Creates a text layout from an initial string and font. */
  43251. TextLayout (const String& text, const Font& font);
  43252. /** Destructor. */
  43253. ~TextLayout();
  43254. /** Copies another layout onto this one. */
  43255. TextLayout& operator= (const TextLayout& layoutToCopy);
  43256. /** Clears the layout, removing all its text. */
  43257. void clear();
  43258. /** Adds a string to the end of the arrangement.
  43259. The string will be broken onto new lines wherever it contains
  43260. carriage-returns or linefeeds. After adding it, you can call layout()
  43261. to wrap long lines into a paragraph and justify it.
  43262. */
  43263. void appendText (const String& textToAppend,
  43264. const Font& fontToUse);
  43265. /** Replaces all the text with a new string.
  43266. This is equivalent to calling clear() followed by appendText().
  43267. */
  43268. void setText (const String& newText,
  43269. const Font& fontToUse);
  43270. /** Returns true if the layout has not had any text added yet. */
  43271. bool isEmpty() const;
  43272. /** Breaks the text up to form a paragraph with the given width.
  43273. @param maximumWidth any text wider than this will be split
  43274. across multiple lines
  43275. @param justification how the lines are to be laid-out horizontally
  43276. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  43277. width that keeps all the lines of text at a
  43278. similar length - this is good when you're displaying
  43279. a short message and don't want it to get split
  43280. onto two lines with only a couple of words on
  43281. the second line, which looks untidy.
  43282. */
  43283. void layout (int maximumWidth,
  43284. const Justification& justification,
  43285. bool attemptToBalanceLineLengths);
  43286. /** Returns the overall width of the entire text layout. */
  43287. int getWidth() const;
  43288. /** Returns the overall height of the entire text layout. */
  43289. int getHeight() const;
  43290. /** Returns the total number of lines of text. */
  43291. int getNumLines() const { return totalLines; }
  43292. /** Returns the width of a particular line of text.
  43293. @param lineNumber the line, from 0 to (getNumLines() - 1)
  43294. */
  43295. int getLineWidth (int lineNumber) const;
  43296. /** Renders the text at a specified position using a graphics context.
  43297. */
  43298. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  43299. /** Renders the text within a specified rectangle using a graphics context.
  43300. The justification flags dictate how the block of text should be positioned
  43301. within the rectangle.
  43302. */
  43303. void drawWithin (Graphics& g,
  43304. int x, int y, int w, int h,
  43305. const Justification& layoutFlags) const;
  43306. private:
  43307. class Token;
  43308. friend class OwnedArray <Token>;
  43309. OwnedArray <Token> tokens;
  43310. int totalLines;
  43311. JUCE_LEAK_DETECTOR (TextLayout);
  43312. };
  43313. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  43314. /*** End of inlined file: juce_TextLayout.h ***/
  43315. /** A window that displays a message and has buttons for the user to react to it.
  43316. For simple dialog boxes with just a couple of buttons on them, there are
  43317. some static methods for running these.
  43318. For more complex dialogs, an AlertWindow can be created, then it can have some
  43319. buttons and components added to it, and its runModalLoop() method is then used to
  43320. show it. The value returned by runModalLoop() shows which button the
  43321. user pressed to dismiss the box.
  43322. @see ThreadWithProgressWindow
  43323. */
  43324. class JUCE_API AlertWindow : public TopLevelWindow,
  43325. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43326. {
  43327. public:
  43328. /** The type of icon to show in the dialog box. */
  43329. enum AlertIconType
  43330. {
  43331. NoIcon, /**< No icon will be shown on the dialog box. */
  43332. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  43333. user to answer a question. */
  43334. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  43335. warning about something and shouldn't be ignored. */
  43336. InfoIcon /**< An icon that indicates that the dialog box is just
  43337. giving the user some information, which doesn't require
  43338. a response from them. */
  43339. };
  43340. /** Creates an AlertWindow.
  43341. @param title the headline to show at the top of the dialog box
  43342. @param message a longer, more descriptive message to show underneath the
  43343. headline
  43344. @param iconType the type of icon to display
  43345. @param associatedComponent if this is non-null, it specifies the component that the
  43346. alert window should be associated with. Depending on the look
  43347. and feel, this might be used for positioning of the alert window.
  43348. */
  43349. AlertWindow (const String& title,
  43350. const String& message,
  43351. AlertIconType iconType,
  43352. Component* associatedComponent = nullptr);
  43353. /** Destroys the AlertWindow */
  43354. ~AlertWindow();
  43355. /** Returns the type of alert icon that was specified when the window
  43356. was created. */
  43357. AlertIconType getAlertType() const noexcept { return alertIconType; }
  43358. /** Changes the dialog box's message.
  43359. This will also resize the window to fit the new message if required.
  43360. */
  43361. void setMessage (const String& message);
  43362. /** Adds a button to the window.
  43363. @param name the text to show on the button
  43364. @param returnValue the value that should be returned from runModalLoop()
  43365. if this is the button that the user presses.
  43366. @param shortcutKey1 an optional key that can be pressed to trigger this button
  43367. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  43368. */
  43369. void addButton (const String& name,
  43370. int returnValue,
  43371. const KeyPress& shortcutKey1 = KeyPress(),
  43372. const KeyPress& shortcutKey2 = KeyPress());
  43373. /** Returns the number of buttons that the window currently has. */
  43374. int getNumButtons() const;
  43375. /** Invokes a click of one of the buttons. */
  43376. void triggerButtonClick (const String& buttonName);
  43377. /** Adds a textbox to the window for entering strings.
  43378. @param name an internal name for the text-box. This is the name to pass to
  43379. the getTextEditorContents() method to find out what the
  43380. user typed-in.
  43381. @param initialContents a string to show in the text box when it's first shown
  43382. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43383. text-box to label it.
  43384. @param isPasswordBox if true, the text editor will display asterisks instead of
  43385. the actual text
  43386. @see getTextEditorContents
  43387. */
  43388. void addTextEditor (const String& name,
  43389. const String& initialContents,
  43390. const String& onScreenLabel = String::empty,
  43391. bool isPasswordBox = false);
  43392. /** Returns the contents of a named textbox.
  43393. After showing an AlertWindow that contains a text editor, this can be
  43394. used to find out what the user has typed into it.
  43395. @param nameOfTextEditor the name of the text box that you're interested in
  43396. @see addTextEditor
  43397. */
  43398. const String getTextEditorContents (const String& nameOfTextEditor) const;
  43399. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  43400. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  43401. /** Adds a drop-down list of choices to the box.
  43402. After the box has been shown, the getComboBoxComponent() method can
  43403. be used to find out which item the user picked.
  43404. @param name the label to use for the drop-down list
  43405. @param items the list of items to show in it
  43406. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43407. combo-box to label it.
  43408. @see getComboBoxComponent
  43409. */
  43410. void addComboBox (const String& name,
  43411. const StringArray& items,
  43412. const String& onScreenLabel = String::empty);
  43413. /** Returns a drop-down list that was added to the AlertWindow.
  43414. @param nameOfList the name that was passed into the addComboBox() method
  43415. when creating the drop-down
  43416. @returns the ComboBox component, or 0 if none was found for the given name.
  43417. */
  43418. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  43419. /** Adds a block of text.
  43420. This is handy for adding a multi-line note next to a textbox or combo-box,
  43421. to provide more details about what's going on.
  43422. */
  43423. void addTextBlock (const String& text);
  43424. /** Adds a progress-bar to the window.
  43425. @param progressValue a variable that will be repeatedly checked while the
  43426. dialog box is visible, to see how far the process has
  43427. got. The value should be in the range 0 to 1.0
  43428. */
  43429. void addProgressBarComponent (double& progressValue);
  43430. /** Adds a user-defined component to the dialog box.
  43431. @param component the component to add - its size should be set up correctly
  43432. before it is passed in. The caller is responsible for deleting
  43433. the component later on - the AlertWindow won't delete it.
  43434. */
  43435. void addCustomComponent (Component* component);
  43436. /** Returns the number of custom components in the dialog box.
  43437. @see getCustomComponent, addCustomComponent
  43438. */
  43439. int getNumCustomComponents() const;
  43440. /** Returns one of the custom components in the dialog box.
  43441. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  43442. will return 0
  43443. @see getNumCustomComponents, addCustomComponent
  43444. */
  43445. Component* getCustomComponent (int index) const;
  43446. /** Removes one of the custom components in the dialog box.
  43447. Note that this won't delete it, it just removes the component from the window
  43448. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  43449. will return 0
  43450. @returns the component that was removed (or null)
  43451. @see getNumCustomComponents, addCustomComponent
  43452. */
  43453. Component* removeCustomComponent (int index);
  43454. /** Returns true if the window contains any components other than just buttons.*/
  43455. bool containsAnyExtraComponents() const;
  43456. // easy-to-use message box functions:
  43457. /** Shows a dialog box that just has a message and a single button to get rid of it.
  43458. If the callback parameter is null, the box is shown modally, and the method will
  43459. block until the user has clicked the button (or pressed the escape or return keys).
  43460. If the callback parameter is non-null, the box will be displayed and placed into a
  43461. modal state, but this method will return immediately, and the callback will be invoked
  43462. later when the user dismisses the box.
  43463. @param iconType the type of icon to show
  43464. @param title the headline to show at the top of the box
  43465. @param message a longer, more descriptive message to show underneath the
  43466. headline
  43467. @param buttonText the text to show in the button - if this string is empty, the
  43468. default string "ok" (or a localised version) will be used.
  43469. @param associatedComponent if this is non-null, it specifies the component that the
  43470. alert window should be associated with. Depending on the look
  43471. and feel, this might be used for positioning of the alert window.
  43472. */
  43473. #if JUCE_MODAL_LOOPS_PERMITTED
  43474. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  43475. const String& title,
  43476. const String& message,
  43477. const String& buttonText = String::empty,
  43478. Component* associatedComponent = nullptr);
  43479. #endif
  43480. /** Shows a dialog box that just has a message and a single button to get rid of it.
  43481. If the callback parameter is null, the box is shown modally, and the method will
  43482. block until the user has clicked the button (or pressed the escape or return keys).
  43483. If the callback parameter is non-null, the box will be displayed and placed into a
  43484. modal state, but this method will return immediately, and the callback will be invoked
  43485. later when the user dismisses the box.
  43486. @param iconType the type of icon to show
  43487. @param title the headline to show at the top of the box
  43488. @param message a longer, more descriptive message to show underneath the
  43489. headline
  43490. @param buttonText the text to show in the button - if this string is empty, the
  43491. default string "ok" (or a localised version) will be used.
  43492. @param associatedComponent if this is non-null, it specifies the component that the
  43493. alert window should be associated with. Depending on the look
  43494. and feel, this might be used for positioning of the alert window.
  43495. */
  43496. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  43497. const String& title,
  43498. const String& message,
  43499. const String& buttonText = String::empty,
  43500. Component* associatedComponent = nullptr);
  43501. /** Shows a dialog box with two buttons.
  43502. Ideal for ok/cancel or yes/no choices. The return key can also be used
  43503. to trigger the first button, and the escape key for the second button.
  43504. If the callback parameter is null, the box is shown modally, and the method will
  43505. block until the user has clicked the button (or pressed the escape or return keys).
  43506. If the callback parameter is non-null, the box will be displayed and placed into a
  43507. modal state, but this method will return immediately, and the callback will be invoked
  43508. later when the user dismisses the box.
  43509. @param iconType the type of icon to show
  43510. @param title the headline to show at the top of the box
  43511. @param message a longer, more descriptive message to show underneath the
  43512. headline
  43513. @param button1Text the text to show in the first button - if this string is
  43514. empty, the default string "ok" (or a localised version of it)
  43515. will be used.
  43516. @param button2Text the text to show in the second button - if this string is
  43517. empty, the default string "cancel" (or a localised version of it)
  43518. will be used.
  43519. @param associatedComponent if this is non-null, it specifies the component that the
  43520. alert window should be associated with. Depending on the look
  43521. and feel, this might be used for positioning of the alert window.
  43522. @param callback if this is non-null, the menu will be launched asynchronously,
  43523. returning immediately, and the callback will receive a call to its
  43524. modalStateFinished() when the box is dismissed, with its parameter
  43525. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  43526. will be owned and deleted by the system, so make sure that it works
  43527. safely and doesn't keep any references to objects that might be deleted
  43528. before it gets called.
  43529. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  43530. is not null, the method always returns false, and the user's choice is delivered
  43531. later by the callback.
  43532. */
  43533. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  43534. const String& title,
  43535. const String& message,
  43536. #if JUCE_MODAL_LOOPS_PERMITTED
  43537. const String& button1Text = String::empty,
  43538. const String& button2Text = String::empty,
  43539. Component* associatedComponent = nullptr,
  43540. ModalComponentManager::Callback* callback = nullptr);
  43541. #else
  43542. const String& button1Text,
  43543. const String& button2Text,
  43544. Component* associatedComponent,
  43545. ModalComponentManager::Callback* callback);
  43546. #endif
  43547. /** Shows a dialog box with three buttons.
  43548. Ideal for yes/no/cancel boxes.
  43549. The escape key can be used to trigger the third button.
  43550. If the callback parameter is null, the box is shown modally, and the method will
  43551. block until the user has clicked the button (or pressed the escape or return keys).
  43552. If the callback parameter is non-null, the box will be displayed and placed into a
  43553. modal state, but this method will return immediately, and the callback will be invoked
  43554. later when the user dismisses the box.
  43555. @param iconType the type of icon to show
  43556. @param title the headline to show at the top of the box
  43557. @param message a longer, more descriptive message to show underneath the
  43558. headline
  43559. @param button1Text the text to show in the first button - if an empty string, then
  43560. "yes" will be used (or a localised version of it)
  43561. @param button2Text the text to show in the first button - if an empty string, then
  43562. "no" will be used (or a localised version of it)
  43563. @param button3Text the text to show in the first button - if an empty string, then
  43564. "cancel" will be used (or a localised version of it)
  43565. @param associatedComponent if this is non-null, it specifies the component that the
  43566. alert window should be associated with. Depending on the look
  43567. and feel, this might be used for positioning of the alert window.
  43568. @param callback if this is non-null, the menu will be launched asynchronously,
  43569. returning immediately, and the callback will receive a call to its
  43570. modalStateFinished() when the box is dismissed, with its parameter
  43571. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  43572. if it was cancelled, The callback object will be owned and deleted by the
  43573. system, so make sure that it works safely and doesn't keep any references
  43574. to objects that might be deleted before it gets called.
  43575. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  43576. returns one of the following values:
  43577. - 0 if the third button was pressed (normally used for 'cancel')
  43578. - 1 if the first button was pressed (normally used for 'yes')
  43579. - 2 if the middle button was pressed (normally used for 'no')
  43580. */
  43581. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  43582. const String& title,
  43583. const String& message,
  43584. #if JUCE_MODAL_LOOPS_PERMITTED
  43585. const String& button1Text = String::empty,
  43586. const String& button2Text = String::empty,
  43587. const String& button3Text = String::empty,
  43588. Component* associatedComponent = nullptr,
  43589. ModalComponentManager::Callback* callback = nullptr);
  43590. #else
  43591. const String& button1Text,
  43592. const String& button2Text,
  43593. const String& button3Text,
  43594. Component* associatedComponent,
  43595. ModalComponentManager::Callback* callback);
  43596. #endif
  43597. /** Shows an operating-system native dialog box.
  43598. @param title the title to use at the top
  43599. @param bodyText the longer message to show
  43600. @param isOkCancel if true, this will show an ok/cancel box, if false,
  43601. it'll show a box with just an ok button
  43602. @returns true if the ok button was pressed, false if they pressed cancel.
  43603. */
  43604. #if JUCE_MODAL_LOOPS_PERMITTED
  43605. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  43606. const String& bodyText,
  43607. bool isOkCancel);
  43608. #endif
  43609. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  43610. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43611. methods.
  43612. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43613. */
  43614. enum ColourIds
  43615. {
  43616. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  43617. textColourId = 0x1001810, /**< The colour for the text. */
  43618. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  43619. };
  43620. protected:
  43621. /** @internal */
  43622. void paint (Graphics& g);
  43623. /** @internal */
  43624. void mouseDown (const MouseEvent& e);
  43625. /** @internal */
  43626. void mouseDrag (const MouseEvent& e);
  43627. /** @internal */
  43628. bool keyPressed (const KeyPress& key);
  43629. /** @internal */
  43630. void buttonClicked (Button* button);
  43631. /** @internal */
  43632. void lookAndFeelChanged();
  43633. /** @internal */
  43634. void userTriedToCloseWindow();
  43635. /** @internal */
  43636. int getDesktopWindowStyleFlags() const;
  43637. private:
  43638. String text;
  43639. TextLayout textLayout;
  43640. AlertIconType alertIconType;
  43641. ComponentBoundsConstrainer constrainer;
  43642. ComponentDragger dragger;
  43643. Rectangle<int> textArea;
  43644. OwnedArray<TextButton> buttons;
  43645. OwnedArray<TextEditor> textBoxes;
  43646. OwnedArray<ComboBox> comboBoxes;
  43647. OwnedArray<ProgressBar> progressBars;
  43648. Array<Component*> customComps;
  43649. OwnedArray<Component> textBlocks;
  43650. Array<Component*> allComps;
  43651. StringArray textboxNames, comboBoxNames;
  43652. Font font;
  43653. Component* associatedComponent;
  43654. void updateLayout (bool onlyIncreaseSize);
  43655. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  43656. };
  43657. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  43658. /*** End of inlined file: juce_AlertWindow.h ***/
  43659. /**
  43660. A file open/save dialog box.
  43661. This is a Juce-based file dialog box; to use a native file chooser, see the
  43662. FileChooser class.
  43663. To use one of these, create it and call its show() method. e.g.
  43664. @code
  43665. {
  43666. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  43667. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  43668. File::nonexistent,
  43669. &wildcardFilter,
  43670. 0);
  43671. FileChooserDialogBox dialogBox ("Open some kind of file",
  43672. "Please choose some kind of file that you want to open...",
  43673. browser,
  43674. getLookAndFeel().alertWindowBackground);
  43675. if (dialogBox.show())
  43676. {
  43677. File selectedFile = browser.getCurrentFile();
  43678. ...
  43679. }
  43680. }
  43681. @endcode
  43682. @see FileChooser
  43683. */
  43684. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  43685. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43686. public FileBrowserListener
  43687. {
  43688. public:
  43689. /** Creates a file chooser box.
  43690. @param title the main title to show at the top of the box
  43691. @param instructions an optional longer piece of text to show below the title in
  43692. a smaller font, describing in more detail what's required.
  43693. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  43694. box. Make sure you delete this after (but not before!) the
  43695. dialog box has been deleted.
  43696. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  43697. if they try to select a file that already exists. (This
  43698. flag is only used when saving files)
  43699. @param backgroundColour the background colour for the top level window
  43700. @see FileBrowserComponent, FilePreviewComponent
  43701. */
  43702. FileChooserDialogBox (const String& title,
  43703. const String& instructions,
  43704. FileBrowserComponent& browserComponent,
  43705. bool warnAboutOverwritingExistingFiles,
  43706. const Colour& backgroundColour);
  43707. /** Destructor. */
  43708. ~FileChooserDialogBox();
  43709. #if JUCE_MODAL_LOOPS_PERMITTED
  43710. /** Displays and runs the dialog box modally.
  43711. This will show the box with the specified size, returning true if the user
  43712. pressed 'ok', or false if they cancelled.
  43713. Leave the width or height as 0 to use the default size
  43714. */
  43715. bool show (int width = 0, int height = 0);
  43716. /** Displays and runs the dialog box modally.
  43717. This will show the box with the specified size at the specified location,
  43718. returning true if the user pressed 'ok', or false if they cancelled.
  43719. Leave the width or height as 0 to use the default size.
  43720. */
  43721. bool showAt (int x, int y, int width, int height);
  43722. #endif
  43723. /** Sets the size of this dialog box to its default and positions it either in the
  43724. centre of the screen, or centred around a component that is provided.
  43725. */
  43726. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  43727. /** A set of colour IDs to use to change the colour of various aspects of the box.
  43728. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43729. methods.
  43730. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43731. */
  43732. enum ColourIds
  43733. {
  43734. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  43735. };
  43736. /** @internal */
  43737. void buttonClicked (Button* button);
  43738. /** @internal */
  43739. void closeButtonPressed();
  43740. /** @internal */
  43741. void selectionChanged();
  43742. /** @internal */
  43743. void fileClicked (const File& file, const MouseEvent& e);
  43744. /** @internal */
  43745. void fileDoubleClicked (const File& file);
  43746. private:
  43747. class ContentComponent;
  43748. ContentComponent* content;
  43749. const bool warnAboutOverwritingExistingFiles;
  43750. void okButtonPressed();
  43751. void createNewFolder();
  43752. void createNewFolderConfirmed (const String& name);
  43753. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  43754. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  43755. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  43756. };
  43757. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  43758. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  43759. #endif
  43760. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  43761. #endif
  43762. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43763. /*** Start of inlined file: juce_FileListComponent.h ***/
  43764. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43765. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43766. /**
  43767. A component that displays the files in a directory as a listbox.
  43768. This implements the DirectoryContentsDisplayComponent base class so that
  43769. it can be used in a FileBrowserComponent.
  43770. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43771. class and the FileBrowserListener class.
  43772. @see DirectoryContentsList, FileTreeComponent
  43773. */
  43774. class JUCE_API FileListComponent : public ListBox,
  43775. public DirectoryContentsDisplayComponent,
  43776. private ListBoxModel,
  43777. private ChangeListener
  43778. {
  43779. public:
  43780. /** Creates a listbox to show the contents of a specified directory.
  43781. */
  43782. FileListComponent (DirectoryContentsList& listToShow);
  43783. /** Destructor. */
  43784. ~FileListComponent();
  43785. /** Returns the number of files the user has got selected.
  43786. @see getSelectedFile
  43787. */
  43788. int getNumSelectedFiles() const;
  43789. /** Returns one of the files that the user has currently selected.
  43790. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43791. @see getNumSelectedFiles
  43792. */
  43793. const File getSelectedFile (int index = 0) const;
  43794. /** Deselects any files that are currently selected. */
  43795. void deselectAllFiles();
  43796. /** Scrolls to the top of the list. */
  43797. void scrollToTop();
  43798. /** @internal */
  43799. void changeListenerCallback (ChangeBroadcaster*);
  43800. /** @internal */
  43801. int getNumRows();
  43802. /** @internal */
  43803. void paintListBoxItem (int, Graphics&, int, int, bool);
  43804. /** @internal */
  43805. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  43806. /** @internal */
  43807. void selectedRowsChanged (int lastRowSelected);
  43808. /** @internal */
  43809. void deleteKeyPressed (int currentSelectedRow);
  43810. /** @internal */
  43811. void returnKeyPressed (int currentSelectedRow);
  43812. private:
  43813. File lastDirectory;
  43814. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  43815. };
  43816. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43817. /*** End of inlined file: juce_FileListComponent.h ***/
  43818. #endif
  43819. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43820. /*** Start of inlined file: juce_FilenameComponent.h ***/
  43821. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43822. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43823. class FilenameComponent;
  43824. /**
  43825. Listens for events happening to a FilenameComponent.
  43826. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  43827. register one of these objects for event callbacks when the filename is changed.
  43828. @see FilenameComponent
  43829. */
  43830. class JUCE_API FilenameComponentListener
  43831. {
  43832. public:
  43833. /** Destructor. */
  43834. virtual ~FilenameComponentListener() {}
  43835. /** This method is called after the FilenameComponent's file has been changed. */
  43836. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  43837. };
  43838. /**
  43839. Shows a filename as an editable text box, with a 'browse' button and a
  43840. drop-down list for recently selected files.
  43841. A handy component for dialogue boxes where you want the user to be able to
  43842. select a file or directory.
  43843. Attach an FilenameComponentListener using the addListener() method, and it will
  43844. get called each time the user changes the filename, either by browsing for a file
  43845. and clicking 'ok', or by typing a new filename into the box and pressing return.
  43846. @see FileChooser, ComboBox
  43847. */
  43848. class JUCE_API FilenameComponent : public Component,
  43849. public SettableTooltipClient,
  43850. public FileDragAndDropTarget,
  43851. private AsyncUpdater,
  43852. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43853. private ComboBoxListener
  43854. {
  43855. public:
  43856. /** Creates a FilenameComponent.
  43857. @param name the name for this component.
  43858. @param currentFile the file to initially show in the box
  43859. @param canEditFilename if true, the user can manually edit the filename; if false,
  43860. they can only change it by browsing for a new file
  43861. @param isDirectory if true, the file will be treated as a directory, and
  43862. an appropriate directory browser used
  43863. @param isForSaving if true, the file browser will allow non-existent files to
  43864. be picked, as the file is assumed to be used for saving rather
  43865. than loading
  43866. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  43867. If an empty string is passed in, then the pattern is assumed to be "*"
  43868. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  43869. to any filenames that are entered or chosen
  43870. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  43871. will only appear if the initial file isn't valid)
  43872. */
  43873. FilenameComponent (const String& name,
  43874. const File& currentFile,
  43875. bool canEditFilename,
  43876. bool isDirectory,
  43877. bool isForSaving,
  43878. const String& fileBrowserWildcard,
  43879. const String& enforcedSuffix,
  43880. const String& textWhenNothingSelected);
  43881. /** Destructor. */
  43882. ~FilenameComponent();
  43883. /** Returns the currently displayed filename. */
  43884. const File getCurrentFile() const;
  43885. /** Changes the current filename.
  43886. If addToRecentlyUsedList is true, the filename will also be added to the
  43887. drop-down list of recent files.
  43888. If sendChangeNotification is false, then the listeners won't be told of the
  43889. change.
  43890. */
  43891. void setCurrentFile (File newFile,
  43892. bool addToRecentlyUsedList,
  43893. bool sendChangeNotification = true);
  43894. /** Changes whether the use can type into the filename box.
  43895. */
  43896. void setFilenameIsEditable (bool shouldBeEditable);
  43897. /** Sets a file or directory to be the default starting point for the browser to show.
  43898. This is only used if the current file hasn't been set.
  43899. */
  43900. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43901. /** Returns all the entries on the recent files list.
  43902. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  43903. state of this list.
  43904. @see setRecentlyUsedFilenames
  43905. */
  43906. const StringArray getRecentlyUsedFilenames() const;
  43907. /** Sets all the entries on the recent files list.
  43908. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  43909. state of this list.
  43910. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  43911. */
  43912. void setRecentlyUsedFilenames (const StringArray& filenames);
  43913. /** Adds an entry to the recently-used files dropdown list.
  43914. If the file is already in the list, it will be moved to the top. A limit
  43915. is also placed on the number of items that are kept in the list.
  43916. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  43917. */
  43918. void addRecentlyUsedFile (const File& file);
  43919. /** Changes the limit for the number of files that will be stored in the recent-file list.
  43920. */
  43921. void setMaxNumberOfRecentFiles (int newMaximum);
  43922. /** Changes the text shown on the 'browse' button.
  43923. By default this button just says "..." but you can change it. The button itself
  43924. can be changed using the look-and-feel classes, so it might not actually have any
  43925. text on it.
  43926. */
  43927. void setBrowseButtonText (const String& browseButtonText);
  43928. /** Adds a listener that will be called when the selected file is changed. */
  43929. void addListener (FilenameComponentListener* listener);
  43930. /** Removes a previously-registered listener. */
  43931. void removeListener (FilenameComponentListener* listener);
  43932. /** Gives the component a tooltip. */
  43933. void setTooltip (const String& newTooltip);
  43934. /** @internal */
  43935. void paintOverChildren (Graphics& g);
  43936. /** @internal */
  43937. void resized();
  43938. /** @internal */
  43939. void lookAndFeelChanged();
  43940. /** @internal */
  43941. bool isInterestedInFileDrag (const StringArray& files);
  43942. /** @internal */
  43943. void filesDropped (const StringArray& files, int, int);
  43944. /** @internal */
  43945. void fileDragEnter (const StringArray& files, int, int);
  43946. /** @internal */
  43947. void fileDragExit (const StringArray& files);
  43948. private:
  43949. ComboBox filenameBox;
  43950. String lastFilename;
  43951. ScopedPointer<Button> browseButton;
  43952. int maxRecentFiles;
  43953. bool isDir, isSaving, isFileDragOver;
  43954. String wildcard, enforcedSuffix, browseButtonText;
  43955. ListenerList <FilenameComponentListener> listeners;
  43956. File defaultBrowseFile;
  43957. void comboBoxChanged (ComboBox*);
  43958. void buttonClicked (Button* button);
  43959. void handleAsyncUpdate();
  43960. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  43961. };
  43962. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43963. /*** End of inlined file: juce_FilenameComponent.h ***/
  43964. #endif
  43965. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  43966. #endif
  43967. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43968. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  43969. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43970. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43971. /**
  43972. Shows a set of file paths in a list, allowing them to be added, removed or
  43973. re-ordered.
  43974. @see FileSearchPath
  43975. */
  43976. class JUCE_API FileSearchPathListComponent : public Component,
  43977. public SettableTooltipClient,
  43978. public FileDragAndDropTarget,
  43979. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43980. private ListBoxModel
  43981. {
  43982. public:
  43983. /** Creates an empty FileSearchPathListComponent. */
  43984. FileSearchPathListComponent();
  43985. /** Destructor. */
  43986. ~FileSearchPathListComponent();
  43987. /** Returns the path as it is currently shown. */
  43988. const FileSearchPath& getPath() const noexcept { return path; }
  43989. /** Changes the current path. */
  43990. void setPath (const FileSearchPath& newPath);
  43991. /** Sets a file or directory to be the default starting point for the browser to show.
  43992. This is only used if the current file hasn't been set.
  43993. */
  43994. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43995. /** A set of colour IDs to use to change the colour of various aspects of the label.
  43996. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43997. methods.
  43998. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43999. */
  44000. enum ColourIds
  44001. {
  44002. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  44003. Make this transparent if you don't want the background to be filled. */
  44004. };
  44005. /** @internal */
  44006. int getNumRows();
  44007. /** @internal */
  44008. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  44009. /** @internal */
  44010. void deleteKeyPressed (int lastRowSelected);
  44011. /** @internal */
  44012. void returnKeyPressed (int lastRowSelected);
  44013. /** @internal */
  44014. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  44015. /** @internal */
  44016. void selectedRowsChanged (int lastRowSelected);
  44017. /** @internal */
  44018. void resized();
  44019. /** @internal */
  44020. void paint (Graphics& g);
  44021. /** @internal */
  44022. bool isInterestedInFileDrag (const StringArray& files);
  44023. /** @internal */
  44024. void filesDropped (const StringArray& files, int, int);
  44025. /** @internal */
  44026. void buttonClicked (Button* button);
  44027. private:
  44028. FileSearchPath path;
  44029. File defaultBrowseTarget;
  44030. ListBox listBox;
  44031. TextButton addButton, removeButton, changeButton;
  44032. DrawableButton upButton, downButton;
  44033. void changed();
  44034. void updateButtons();
  44035. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  44036. };
  44037. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44038. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  44039. #endif
  44040. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44041. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  44042. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44043. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44044. /**
  44045. A component that displays the files in a directory as a treeview.
  44046. This implements the DirectoryContentsDisplayComponent base class so that
  44047. it can be used in a FileBrowserComponent.
  44048. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44049. class and the FileBrowserListener class.
  44050. @see DirectoryContentsList, FileListComponent
  44051. */
  44052. class JUCE_API FileTreeComponent : public TreeView,
  44053. public DirectoryContentsDisplayComponent
  44054. {
  44055. public:
  44056. /** Creates a listbox to show the contents of a specified directory.
  44057. */
  44058. FileTreeComponent (DirectoryContentsList& listToShow);
  44059. /** Destructor. */
  44060. ~FileTreeComponent();
  44061. /** Returns the number of files the user has got selected.
  44062. @see getSelectedFile
  44063. */
  44064. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  44065. /** Returns one of the files that the user has currently selected.
  44066. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44067. @see getNumSelectedFiles
  44068. */
  44069. const File getSelectedFile (int index = 0) const;
  44070. /** Deselects any files that are currently selected. */
  44071. void deselectAllFiles();
  44072. /** Scrolls the list to the top. */
  44073. void scrollToTop();
  44074. /** Setting a name for this allows tree items to be dragged.
  44075. The string that you pass in here will be returned by the getDragSourceDescription()
  44076. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  44077. */
  44078. void setDragAndDropDescription (const String& description);
  44079. /** Returns the last value that was set by setDragAndDropDescription().
  44080. */
  44081. const String& getDragAndDropDescription() const noexcept { return dragAndDropDescription; }
  44082. private:
  44083. String dragAndDropDescription;
  44084. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  44085. };
  44086. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44087. /*** End of inlined file: juce_FileTreeComponent.h ***/
  44088. #endif
  44089. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44090. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  44091. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44092. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44093. /**
  44094. A simple preview component that shows thumbnails of image files.
  44095. @see FileChooserDialogBox, FilePreviewComponent
  44096. */
  44097. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  44098. private Timer
  44099. {
  44100. public:
  44101. /** Creates an ImagePreviewComponent. */
  44102. ImagePreviewComponent();
  44103. /** Destructor. */
  44104. ~ImagePreviewComponent();
  44105. /** @internal */
  44106. void selectedFileChanged (const File& newSelectedFile);
  44107. /** @internal */
  44108. void paint (Graphics& g);
  44109. /** @internal */
  44110. void timerCallback();
  44111. private:
  44112. File fileToLoad;
  44113. Image currentThumbnail;
  44114. String currentDetails;
  44115. void getThumbSize (int& w, int& h) const;
  44116. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  44117. };
  44118. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44119. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  44120. #endif
  44121. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44122. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  44123. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44124. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44125. /**
  44126. A type of FileFilter that works by wildcard pattern matching.
  44127. This filter only allows files that match one of the specified patterns, but
  44128. allows all directories through.
  44129. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  44130. */
  44131. class JUCE_API WildcardFileFilter : public FileFilter
  44132. {
  44133. public:
  44134. /**
  44135. Creates a wildcard filter for one or more patterns.
  44136. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  44137. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  44138. or .aiff.
  44139. The description is a name to show the user in a list of possible patterns, so
  44140. for the wav/aiff example, your description might be "audio files".
  44141. */
  44142. WildcardFileFilter (const String& fileWildcardPatterns,
  44143. const String& directoryWildcardPatterns,
  44144. const String& description);
  44145. /** Destructor. */
  44146. ~WildcardFileFilter();
  44147. /** Returns true if the filename matches one of the patterns specified. */
  44148. bool isFileSuitable (const File& file) const;
  44149. /** This always returns true. */
  44150. bool isDirectorySuitable (const File& file) const;
  44151. private:
  44152. StringArray fileWildcards, directoryWildcards;
  44153. static void parse (const String& pattern, StringArray& result);
  44154. static bool match (const File& file, const StringArray& wildcards);
  44155. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  44156. };
  44157. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44158. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  44159. #endif
  44160. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  44161. #endif
  44162. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  44163. #endif
  44164. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  44165. #endif
  44166. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  44167. #endif
  44168. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  44169. #endif
  44170. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  44171. #endif
  44172. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  44173. #endif
  44174. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44175. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  44176. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44177. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44178. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  44179. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44180. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44181. /**
  44182. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  44183. command in a ApplicationCommandManager.
  44184. Normally, you won't actually create a KeyPressMappingSet directly, because
  44185. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  44186. you'd create yourself an ApplicationCommandManager, and call its
  44187. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  44188. KeyPressMappingSet.
  44189. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  44190. to the top-level component for which you want to handle keystrokes. So for example:
  44191. @code
  44192. class MyMainWindow : public Component
  44193. {
  44194. ApplicationCommandManager* myCommandManager;
  44195. public:
  44196. MyMainWindow()
  44197. {
  44198. myCommandManager = new ApplicationCommandManager();
  44199. // first, make sure the command manager has registered all the commands that its
  44200. // targets can perform..
  44201. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  44202. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  44203. // this will use the command manager to initialise the KeyPressMappingSet with
  44204. // the default keypresses that were specified when the targets added their commands
  44205. // to the manager.
  44206. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  44207. // having set up the default key-mappings, you might now want to load the last set
  44208. // of mappings that the user configured.
  44209. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  44210. // Now tell our top-level window to send any keypresses that arrive to the
  44211. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  44212. addKeyListener (myCommandManager->getKeyMappings());
  44213. }
  44214. ...
  44215. }
  44216. @endcode
  44217. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  44218. register to be told when a command or mapping is added, removed, etc.
  44219. There's also a UI component called KeyMappingEditorComponent that can be used
  44220. to easily edit the key mappings.
  44221. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  44222. */
  44223. class JUCE_API KeyPressMappingSet : public KeyListener,
  44224. public ChangeBroadcaster,
  44225. public FocusChangeListener
  44226. {
  44227. public:
  44228. /** Creates a KeyPressMappingSet for a given command manager.
  44229. Normally, you won't actually create a KeyPressMappingSet directly, because
  44230. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  44231. best thing to do is to create your ApplicationCommandManager, and use the
  44232. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  44233. When a suitable keypress happens, the manager's invoke() method will be
  44234. used to invoke the appropriate command.
  44235. @see ApplicationCommandManager
  44236. */
  44237. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  44238. /** Creates an copy of a KeyPressMappingSet. */
  44239. KeyPressMappingSet (const KeyPressMappingSet& other);
  44240. /** Destructor. */
  44241. ~KeyPressMappingSet();
  44242. ApplicationCommandManager* getCommandManager() const noexcept { return commandManager; }
  44243. /** Returns a list of keypresses that are assigned to a particular command.
  44244. @param commandID the command's ID
  44245. */
  44246. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  44247. /** Assigns a keypress to a command.
  44248. If the keypress is already assigned to a different command, it will first be
  44249. removed from that command, to avoid it triggering multiple functions.
  44250. @param commandID the ID of the command that you want to add a keypress to. If
  44251. this is 0, the keypress will be removed from anything that it
  44252. was previously assigned to, but not re-assigned
  44253. @param newKeyPress the new key-press
  44254. @param insertIndex if this is less than zero, the key will be appended to the
  44255. end of the list of keypresses; otherwise the new keypress will
  44256. be inserted into the existing list at this index
  44257. */
  44258. void addKeyPress (CommandID commandID,
  44259. const KeyPress& newKeyPress,
  44260. int insertIndex = -1);
  44261. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  44262. @see resetToDefaultMapping
  44263. */
  44264. void resetToDefaultMappings();
  44265. /** Resets all key-mappings to the defaults for a particular command.
  44266. @see resetToDefaultMappings
  44267. */
  44268. void resetToDefaultMapping (CommandID commandID);
  44269. /** Removes all keypresses that are assigned to any commands. */
  44270. void clearAllKeyPresses();
  44271. /** Removes all keypresses that are assigned to a particular command. */
  44272. void clearAllKeyPresses (CommandID commandID);
  44273. /** Removes one of the keypresses that are assigned to a command.
  44274. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  44275. which the keyPressIndex refers.
  44276. */
  44277. void removeKeyPress (CommandID commandID, int keyPressIndex);
  44278. /** Removes a keypress from any command that it may be assigned to.
  44279. */
  44280. void removeKeyPress (const KeyPress& keypress);
  44281. /** Returns true if the given command is linked to this key. */
  44282. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const noexcept;
  44283. /** Looks for a command that corresponds to a keypress.
  44284. @returns the UID of the command or 0 if none was found
  44285. */
  44286. CommandID findCommandForKeyPress (const KeyPress& keyPress) const noexcept;
  44287. /** Tries to recreate the mappings from a previously stored state.
  44288. The XML passed in must have been created by the createXml() method.
  44289. If the stored state makes any reference to commands that aren't
  44290. currently available, these will be ignored.
  44291. If the set of mappings being loaded was a set of differences (using createXml (true)),
  44292. then this will call resetToDefaultMappings() and then merge the saved mappings
  44293. on top. If the saved set was created with createXml (false), then this method
  44294. will first clear all existing mappings and load the saved ones as a complete set.
  44295. @returns true if it manages to load the XML correctly
  44296. @see createXml
  44297. */
  44298. bool restoreFromXml (const XmlElement& xmlVersion);
  44299. /** Creates an XML representation of the current mappings.
  44300. This will produce a lump of XML that can be later reloaded using
  44301. restoreFromXml() to recreate the current mapping state.
  44302. The object that is returned must be deleted by the caller.
  44303. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  44304. will be saved into the XML. If it's true, then the XML will
  44305. only store the differences between the current mappings and
  44306. the default mappings you'd get from calling resetToDefaultMappings().
  44307. The advantage of saving a set of differences from the default is that
  44308. if you change the default mappings (in a new version of your app, for
  44309. example), then these will be merged into a user's saved preferences.
  44310. @see restoreFromXml
  44311. */
  44312. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  44313. /** @internal */
  44314. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  44315. /** @internal */
  44316. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  44317. /** @internal */
  44318. void globalFocusChanged (Component* focusedComponent);
  44319. private:
  44320. ApplicationCommandManager* commandManager;
  44321. struct CommandMapping
  44322. {
  44323. CommandID commandID;
  44324. Array <KeyPress> keypresses;
  44325. bool wantsKeyUpDownCallbacks;
  44326. };
  44327. OwnedArray <CommandMapping> mappings;
  44328. struct KeyPressTime
  44329. {
  44330. KeyPress key;
  44331. uint32 timeWhenPressed;
  44332. };
  44333. OwnedArray <KeyPressTime> keysDown;
  44334. void handleMessage (const Message& message);
  44335. void invokeCommand (const CommandID commandID,
  44336. const KeyPress& keyPress,
  44337. const bool isKeyDown,
  44338. const int millisecsSinceKeyPressed,
  44339. Component* const originatingComponent) const;
  44340. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  44341. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  44342. };
  44343. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44344. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  44345. /**
  44346. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  44347. object.
  44348. @see KeyPressMappingSet
  44349. */
  44350. class JUCE_API KeyMappingEditorComponent : public Component
  44351. {
  44352. public:
  44353. /** Creates a KeyMappingEditorComponent.
  44354. @param mappingSet this is the set of mappings to display and edit. Make sure the
  44355. mappings object is not deleted before this component!
  44356. @param showResetToDefaultButton if true, then at the bottom of the list, the
  44357. component will include a 'reset to defaults' button.
  44358. */
  44359. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  44360. bool showResetToDefaultButton);
  44361. /** Destructor. */
  44362. virtual ~KeyMappingEditorComponent();
  44363. /** Sets up the colours to use for parts of the component.
  44364. @param mainBackground colour to use for most of the background
  44365. @param textColour colour to use for the text
  44366. */
  44367. void setColours (const Colour& mainBackground,
  44368. const Colour& textColour);
  44369. /** Returns the KeyPressMappingSet that this component is acting upon. */
  44370. KeyPressMappingSet& getMappings() const noexcept { return mappings; }
  44371. /** Can be overridden if some commands need to be excluded from the list.
  44372. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  44373. method to decide what to return, but you can override it to handle special cases.
  44374. */
  44375. virtual bool shouldCommandBeIncluded (CommandID commandID);
  44376. /** Can be overridden to indicate that some commands are shown as read-only.
  44377. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  44378. method to decide what to return, but you can override it to handle special cases.
  44379. */
  44380. virtual bool isCommandReadOnly (CommandID commandID);
  44381. /** This can be overridden to let you change the format of the string used
  44382. to describe a keypress.
  44383. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  44384. keys that are triggered by something else externally. If you override the
  44385. method, be sure to let the base class's method handle keys you're not
  44386. interested in.
  44387. */
  44388. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  44389. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  44390. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44391. methods.
  44392. To change the colours of the menu that pops up
  44393. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44394. */
  44395. enum ColourIds
  44396. {
  44397. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  44398. textColourId = 0x100ad01, /**< The colour for the text. */
  44399. };
  44400. /** @internal */
  44401. void parentHierarchyChanged();
  44402. /** @internal */
  44403. void resized();
  44404. private:
  44405. KeyPressMappingSet& mappings;
  44406. TreeView tree;
  44407. TextButton resetButton;
  44408. class TopLevelItem;
  44409. class ChangeKeyButton;
  44410. class MappingItem;
  44411. class CategoryItem;
  44412. class ItemComponent;
  44413. friend class TopLevelItem;
  44414. friend class OwnedArray <ChangeKeyButton>;
  44415. friend class ScopedPointer<TopLevelItem>;
  44416. ScopedPointer<TopLevelItem> treeItem;
  44417. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  44418. };
  44419. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44420. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  44421. #endif
  44422. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  44423. #endif
  44424. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44425. #endif
  44426. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  44427. #endif
  44428. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  44429. #endif
  44430. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  44431. #endif
  44432. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  44433. #endif
  44434. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  44435. #endif
  44436. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44437. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  44438. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44439. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44440. /** An object that watches for any movement of a component or any of its parent components.
  44441. This makes it easy to check when a component is moved relative to its top-level
  44442. peer window. The normal Component::moved() method is only called when a component
  44443. moves relative to its immediate parent, and sometimes you want to know if any of
  44444. components higher up the tree have moved (which of course will affect the overall
  44445. position of all their sub-components).
  44446. It also includes a callback that lets you know when the top-level peer is changed.
  44447. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  44448. because they need to keep their custom windows in the right place and respond to
  44449. changes in the peer.
  44450. */
  44451. class JUCE_API ComponentMovementWatcher : public ComponentListener
  44452. {
  44453. public:
  44454. /** Creates a ComponentMovementWatcher to watch a given target component. */
  44455. ComponentMovementWatcher (Component* component);
  44456. /** Destructor. */
  44457. ~ComponentMovementWatcher();
  44458. /** This callback happens when the component that is being watched is moved
  44459. relative to its top-level peer window, or when it is resized. */
  44460. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  44461. /** This callback happens when the component's top-level peer is changed. */
  44462. virtual void componentPeerChanged() = 0;
  44463. /** This callback happens when the component's visibility state changes, possibly due to
  44464. one of its parents being made visible or invisible.
  44465. */
  44466. virtual void componentVisibilityChanged() = 0;
  44467. /** @internal */
  44468. void componentParentHierarchyChanged (Component& component);
  44469. /** @internal */
  44470. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  44471. /** @internal */
  44472. void componentBeingDeleted (Component& component);
  44473. /** @internal */
  44474. void componentVisibilityChanged (Component& component);
  44475. private:
  44476. WeakReference<Component> component;
  44477. ComponentPeer* lastPeer;
  44478. Array <Component*> registeredParentComps;
  44479. bool reentrant, wasShowing;
  44480. Rectangle<int> lastBounds;
  44481. void unregister();
  44482. void registerWithParentComps();
  44483. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  44484. };
  44485. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44486. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  44487. #endif
  44488. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44489. /*** Start of inlined file: juce_GroupComponent.h ***/
  44490. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44491. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44492. /**
  44493. A component that draws an outline around itself and has an optional title at
  44494. the top, for drawing an outline around a group of controls.
  44495. */
  44496. class JUCE_API GroupComponent : public Component
  44497. {
  44498. public:
  44499. /** Creates a GroupComponent.
  44500. @param componentName the name to give the component
  44501. @param labelText the text to show at the top of the outline
  44502. */
  44503. GroupComponent (const String& componentName = String::empty,
  44504. const String& labelText = String::empty);
  44505. /** Destructor. */
  44506. ~GroupComponent();
  44507. /** Changes the text that's shown at the top of the component. */
  44508. void setText (const String& newText);
  44509. /** Returns the currently displayed text label. */
  44510. const String getText() const;
  44511. /** Sets the positioning of the text label.
  44512. (The default is Justification::left)
  44513. @see getTextLabelPosition
  44514. */
  44515. void setTextLabelPosition (const Justification& justification);
  44516. /** Returns the current text label position.
  44517. @see setTextLabelPosition
  44518. */
  44519. const Justification getTextLabelPosition() const noexcept { return justification; }
  44520. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44521. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44522. methods.
  44523. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44524. */
  44525. enum ColourIds
  44526. {
  44527. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  44528. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  44529. };
  44530. /** @internal */
  44531. void paint (Graphics& g);
  44532. /** @internal */
  44533. void enablementChanged();
  44534. /** @internal */
  44535. void colourChanged();
  44536. private:
  44537. String text;
  44538. Justification justification;
  44539. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  44540. };
  44541. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44542. /*** End of inlined file: juce_GroupComponent.h ***/
  44543. #endif
  44544. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44545. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  44546. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44547. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44548. /*** Start of inlined file: juce_TabbedComponent.h ***/
  44549. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44550. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44551. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  44552. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44553. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44554. class TabbedButtonBar;
  44555. /** In a TabbedButtonBar, this component is used for each of the buttons.
  44556. If you want to create a TabbedButtonBar with custom tab components, derive
  44557. your component from this class, and override the TabbedButtonBar::createTabButton()
  44558. method to create it instead of the default one.
  44559. @see TabbedButtonBar
  44560. */
  44561. class JUCE_API TabBarButton : public Button
  44562. {
  44563. public:
  44564. /** Creates the tab button. */
  44565. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  44566. /** Destructor. */
  44567. ~TabBarButton();
  44568. /** Chooses the best length for the tab, given the specified depth.
  44569. If the tab is horizontal, this should return its width, and the depth
  44570. specifies its height. If it's vertical, it should return the height, and
  44571. the depth is actually its width.
  44572. */
  44573. virtual int getBestTabLength (int depth);
  44574. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  44575. void clicked (const ModifierKeys& mods);
  44576. bool hitTest (int x, int y);
  44577. protected:
  44578. friend class TabbedButtonBar;
  44579. TabbedButtonBar& owner;
  44580. int overlapPixels;
  44581. DropShadowEffect shadow;
  44582. /** Returns an area of the component that's safe to draw in.
  44583. This deals with the orientation of the tabs, which affects which side is
  44584. touching the tabbed box's content component.
  44585. */
  44586. const Rectangle<int> getActiveArea();
  44587. /** Returns this tab's index in its tab bar. */
  44588. int getIndex() const;
  44589. private:
  44590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  44591. };
  44592. /**
  44593. A vertical or horizontal bar containing tabs that you can select.
  44594. You can use one of these to generate things like a dialog box that has
  44595. tabbed pages you can flip between. Attach a ChangeListener to the
  44596. button bar to be told when the user changes the page.
  44597. An easier method than doing this is to use a TabbedComponent, which
  44598. contains its own TabbedButtonBar and which takes care of the layout
  44599. and other housekeeping.
  44600. @see TabbedComponent
  44601. */
  44602. class JUCE_API TabbedButtonBar : public Component,
  44603. public ChangeBroadcaster
  44604. {
  44605. public:
  44606. /** The placement of the tab-bar
  44607. @see setOrientation, getOrientation
  44608. */
  44609. enum Orientation
  44610. {
  44611. TabsAtTop,
  44612. TabsAtBottom,
  44613. TabsAtLeft,
  44614. TabsAtRight
  44615. };
  44616. /** Creates a TabbedButtonBar with a given placement.
  44617. You can change the orientation later if you need to.
  44618. */
  44619. TabbedButtonBar (Orientation orientation);
  44620. /** Destructor. */
  44621. ~TabbedButtonBar();
  44622. /** Changes the bar's orientation.
  44623. This won't change the bar's actual size - you'll need to do that yourself,
  44624. but this determines which direction the tabs go in, and which side they're
  44625. stuck to.
  44626. */
  44627. void setOrientation (Orientation orientation);
  44628. /** Returns the current orientation.
  44629. @see setOrientation
  44630. */
  44631. Orientation getOrientation() const noexcept { return orientation; }
  44632. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  44633. fit a lot of tabs on-screen.
  44634. */
  44635. void setMinimumTabScaleFactor (double newMinimumScale);
  44636. /** Deletes all the tabs from the bar.
  44637. @see addTab
  44638. */
  44639. void clearTabs();
  44640. /** Adds a tab to the bar.
  44641. Tabs are added in left-to-right reading order.
  44642. If this is the first tab added, it'll also be automatically selected.
  44643. */
  44644. void addTab (const String& tabName,
  44645. const Colour& tabBackgroundColour,
  44646. int insertIndex = -1);
  44647. /** Changes the name of one of the tabs. */
  44648. void setTabName (int tabIndex,
  44649. const String& newName);
  44650. /** Gets rid of one of the tabs. */
  44651. void removeTab (int tabIndex);
  44652. /** Moves a tab to a new index in the list.
  44653. Pass -1 as the index to move it to the end of the list.
  44654. */
  44655. void moveTab (int currentIndex, int newIndex);
  44656. /** Returns the number of tabs in the bar. */
  44657. int getNumTabs() const;
  44658. /** Returns a list of all the tab names in the bar. */
  44659. const StringArray getTabNames() const;
  44660. /** Changes the currently selected tab.
  44661. This will send a change message and cause a synchronous callback to
  44662. the currentTabChanged() method. (But if the given tab is already selected,
  44663. nothing will be done).
  44664. To deselect all the tabs, use an index of -1.
  44665. */
  44666. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44667. /** Returns the name of the currently selected tab.
  44668. This could be an empty string if none are selected.
  44669. */
  44670. const String getCurrentTabName() const;
  44671. /** Returns the index of the currently selected tab.
  44672. This could return -1 if none are selected.
  44673. */
  44674. int getCurrentTabIndex() const noexcept { return currentTabIndex; }
  44675. /** Returns the button for a specific tab.
  44676. The button that is returned may be deleted later by this component, so don't hang
  44677. on to the pointer that is returned. A null pointer may be returned if the index is
  44678. out of range.
  44679. */
  44680. TabBarButton* getTabButton (int index) const;
  44681. /** Returns the index of a TabBarButton if it belongs to this bar. */
  44682. int indexOfTabButton (const TabBarButton* button) const;
  44683. /** Callback method to indicate the selected tab has been changed.
  44684. @see setCurrentTabIndex
  44685. */
  44686. virtual void currentTabChanged (int newCurrentTabIndex,
  44687. const String& newCurrentTabName);
  44688. /** Callback method to indicate that the user has right-clicked on a tab.
  44689. (Or ctrl-clicked on the Mac)
  44690. */
  44691. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  44692. /** Returns the colour of a tab.
  44693. This is the colour that was specified in addTab().
  44694. */
  44695. const Colour getTabBackgroundColour (int tabIndex);
  44696. /** Changes the background colour of a tab.
  44697. @see addTab, getTabBackgroundColour
  44698. */
  44699. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44700. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44701. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44702. methods.
  44703. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44704. */
  44705. enum ColourIds
  44706. {
  44707. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  44708. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  44709. the look and feel will choose an appropriate colour. */
  44710. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  44711. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  44712. this isn't specified, the look and feel will choose an appropriate
  44713. colour. */
  44714. };
  44715. /** @internal */
  44716. void resized();
  44717. /** @internal */
  44718. void lookAndFeelChanged();
  44719. protected:
  44720. /** This creates one of the tabs.
  44721. If you need to use custom tab components, you can override this method and
  44722. return your own class instead of the default.
  44723. */
  44724. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44725. private:
  44726. Orientation orientation;
  44727. struct TabInfo
  44728. {
  44729. ScopedPointer<TabBarButton> component;
  44730. String name;
  44731. Colour colour;
  44732. };
  44733. OwnedArray <TabInfo> tabs;
  44734. double minimumScale;
  44735. int currentTabIndex;
  44736. class BehindFrontTabComp;
  44737. friend class BehindFrontTabComp;
  44738. friend class ScopedPointer<BehindFrontTabComp>;
  44739. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  44740. ScopedPointer<Button> extraTabsButton;
  44741. void showExtraItemsMenu();
  44742. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  44743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  44744. };
  44745. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44746. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  44747. /**
  44748. A component with a TabbedButtonBar along one of its sides.
  44749. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  44750. with addTab(), and this will take care of showing the pages for you when the
  44751. user clicks on a different tab.
  44752. @see TabbedButtonBar
  44753. */
  44754. class JUCE_API TabbedComponent : public Component
  44755. {
  44756. public:
  44757. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  44758. Once created, add some tabs with the addTab() method.
  44759. */
  44760. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  44761. /** Destructor. */
  44762. ~TabbedComponent();
  44763. /** Changes the placement of the tabs.
  44764. This will rearrange the layout to place the tabs along the appropriate
  44765. side of this component, and will shift the content component accordingly.
  44766. @see TabbedButtonBar::setOrientation
  44767. */
  44768. void setOrientation (TabbedButtonBar::Orientation orientation);
  44769. /** Returns the current tab placement.
  44770. @see setOrientation, TabbedButtonBar::getOrientation
  44771. */
  44772. TabbedButtonBar::Orientation getOrientation() const noexcept;
  44773. /** Specifies how many pixels wide or high the tab-bar should be.
  44774. If the tabs are placed along the top or bottom, this specified the height
  44775. of the bar; if they're along the left or right edges, it'll be the width
  44776. of the bar.
  44777. */
  44778. void setTabBarDepth (int newDepth);
  44779. /** Returns the current thickness of the tab bar.
  44780. @see setTabBarDepth
  44781. */
  44782. int getTabBarDepth() const noexcept { return tabDepth; }
  44783. /** Specifies the thickness of an outline that should be drawn around the content component.
  44784. If this thickness is > 0, a line will be drawn around the three sides of the content
  44785. component which don't touch the tab-bar, and the content component will be inset by this amount.
  44786. To set the colour of the line, use setColour (outlineColourId, ...).
  44787. */
  44788. void setOutline (int newThickness);
  44789. /** Specifies a gap to leave around the edge of the content component.
  44790. Each edge of the content component will be indented by the given number of pixels.
  44791. */
  44792. void setIndent (int indentThickness);
  44793. /** Removes all the tabs from the bar.
  44794. @see TabbedButtonBar::clearTabs
  44795. */
  44796. void clearTabs();
  44797. /** Adds a tab to the tab-bar.
  44798. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  44799. is true, it will be deleted when the tab is removed or when this object is
  44800. deleted.
  44801. @see TabbedButtonBar::addTab
  44802. */
  44803. void addTab (const String& tabName,
  44804. const Colour& tabBackgroundColour,
  44805. Component* contentComponent,
  44806. bool deleteComponentWhenNotNeeded,
  44807. int insertIndex = -1);
  44808. /** Changes the name of one of the tabs. */
  44809. void setTabName (int tabIndex, const String& newName);
  44810. /** Gets rid of one of the tabs. */
  44811. void removeTab (int tabIndex);
  44812. /** Returns the number of tabs in the bar. */
  44813. int getNumTabs() const;
  44814. /** Returns a list of all the tab names in the bar. */
  44815. const StringArray getTabNames() const;
  44816. /** Returns the content component that was added for the given index.
  44817. Be sure not to use or delete the components that are returned, as this may interfere
  44818. with the TabbedComponent's use of them.
  44819. */
  44820. Component* getTabContentComponent (int tabIndex) const noexcept;
  44821. /** Returns the colour of one of the tabs. */
  44822. const Colour getTabBackgroundColour (int tabIndex) const noexcept;
  44823. /** Changes the background colour of one of the tabs. */
  44824. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44825. /** Changes the currently-selected tab.
  44826. To deselect all the tabs, pass -1 as the index.
  44827. @see TabbedButtonBar::setCurrentTabIndex
  44828. */
  44829. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44830. /** Returns the index of the currently selected tab.
  44831. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  44832. */
  44833. int getCurrentTabIndex() const;
  44834. /** Returns the name of the currently selected tab.
  44835. @see addTab, TabbedButtonBar::getCurrentTabName()
  44836. */
  44837. const String getCurrentTabName() const;
  44838. /** Returns the current component that's filling the panel.
  44839. This will return 0 if there isn't one.
  44840. */
  44841. Component* getCurrentContentComponent() const noexcept { return panelComponent; }
  44842. /** Callback method to indicate the selected tab has been changed.
  44843. @see setCurrentTabIndex
  44844. */
  44845. virtual void currentTabChanged (int newCurrentTabIndex,
  44846. const String& newCurrentTabName);
  44847. /** Callback method to indicate that the user has right-clicked on a tab.
  44848. (Or ctrl-clicked on the Mac)
  44849. */
  44850. virtual void popupMenuClickOnTab (int tabIndex,
  44851. const String& tabName);
  44852. /** Returns the tab button bar component that is being used.
  44853. */
  44854. TabbedButtonBar& getTabbedButtonBar() const noexcept { return *tabs; }
  44855. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44856. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44857. methods.
  44858. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44859. */
  44860. enum ColourIds
  44861. {
  44862. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  44863. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  44864. (See setOutline) */
  44865. };
  44866. /** @internal */
  44867. void paint (Graphics& g);
  44868. /** @internal */
  44869. void resized();
  44870. /** @internal */
  44871. void lookAndFeelChanged();
  44872. protected:
  44873. /** This creates one of the tab buttons.
  44874. If you need to use custom tab components, you can override this method and
  44875. return your own class instead of the default.
  44876. */
  44877. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44878. /** @internal */
  44879. ScopedPointer<TabbedButtonBar> tabs;
  44880. private:
  44881. Array <WeakReference<Component> > contentComponents;
  44882. WeakReference<Component> panelComponent;
  44883. int tabDepth;
  44884. int outlineThickness, edgeIndent;
  44885. class ButtonBar;
  44886. friend class ButtonBar;
  44887. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  44888. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  44889. };
  44890. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44891. /*** End of inlined file: juce_TabbedComponent.h ***/
  44892. /*** Start of inlined file: juce_DocumentWindow.h ***/
  44893. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44894. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44895. /*** Start of inlined file: juce_MenuBarModel.h ***/
  44896. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  44897. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  44898. /**
  44899. A class for controlling MenuBar components.
  44900. This class is used to tell a MenuBar what menus to show, and to respond
  44901. to a menu being selected.
  44902. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  44903. */
  44904. class JUCE_API MenuBarModel : private AsyncUpdater,
  44905. private ApplicationCommandManagerListener
  44906. {
  44907. public:
  44908. MenuBarModel() noexcept;
  44909. /** Destructor. */
  44910. virtual ~MenuBarModel();
  44911. /** Call this when some of your menu items have changed.
  44912. This method will cause a callback to any MenuBarListener objects that
  44913. are registered with this model.
  44914. If this model is displaying items from an ApplicationCommandManager, you
  44915. can use the setApplicationCommandManagerToWatch() method to cause
  44916. change messages to be sent automatically when the ApplicationCommandManager
  44917. is changed.
  44918. @see addListener, removeListener, MenuBarListener
  44919. */
  44920. void menuItemsChanged();
  44921. /** Tells the menu bar to listen to the specified command manager, and to update
  44922. itself when the commands change.
  44923. This will also allow it to flash a menu name when a command from that menu
  44924. is invoked using a keystroke.
  44925. */
  44926. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) noexcept;
  44927. /** A class to receive callbacks when a MenuBarModel changes.
  44928. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  44929. */
  44930. class JUCE_API Listener
  44931. {
  44932. public:
  44933. /** Destructor. */
  44934. virtual ~Listener() {}
  44935. /** This callback is made when items are changed in the menu bar model.
  44936. */
  44937. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  44938. /** This callback is made when an application command is invoked that
  44939. is represented by one of the items in the menu bar model.
  44940. */
  44941. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  44942. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  44943. };
  44944. /** Registers a listener for callbacks when the menu items in this model change.
  44945. The listener object will get callbacks when this object's menuItemsChanged()
  44946. method is called.
  44947. @see removeListener
  44948. */
  44949. void addListener (Listener* listenerToAdd) noexcept;
  44950. /** Removes a listener.
  44951. @see addListener
  44952. */
  44953. void removeListener (Listener* listenerToRemove) noexcept;
  44954. /** This method must return a list of the names of the menus. */
  44955. virtual const StringArray getMenuBarNames() = 0;
  44956. /** This should return the popup menu to display for a given top-level menu.
  44957. @param topLevelMenuIndex the index of the top-level menu to show
  44958. @param menuName the name of the top-level menu item to show
  44959. */
  44960. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  44961. const String& menuName) = 0;
  44962. /** This is called when a menu item has been clicked on.
  44963. @param menuItemID the item ID of the PopupMenu item that was selected
  44964. @param topLevelMenuIndex the index of the top-level menu from which the item was
  44965. chosen (just in case you've used duplicate ID numbers
  44966. on more than one of the popup menus)
  44967. */
  44968. virtual void menuItemSelected (int menuItemID,
  44969. int topLevelMenuIndex) = 0;
  44970. #if JUCE_MAC || DOXYGEN
  44971. /** MAC ONLY - Sets the model that is currently being shown as the main
  44972. menu bar at the top of the screen on the Mac.
  44973. You can pass 0 to stop the current model being displayed. Be careful
  44974. not to delete a model while it is being used.
  44975. An optional extra menu can be specified, containing items to add to the top of
  44976. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  44977. an apple, it's the one next to it, with your application's name at the top
  44978. and the services menu etc on it). When one of these items is selected, the
  44979. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  44980. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  44981. object then newMenuBarModel must be non-null.
  44982. */
  44983. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  44984. const PopupMenu* extraAppleMenuItems = nullptr);
  44985. /** MAC ONLY - Returns the menu model that is currently being shown as
  44986. the main menu bar.
  44987. */
  44988. static MenuBarModel* getMacMainMenu();
  44989. #endif
  44990. /** @internal */
  44991. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  44992. /** @internal */
  44993. void applicationCommandListChanged();
  44994. /** @internal */
  44995. void handleAsyncUpdate();
  44996. private:
  44997. ApplicationCommandManager* manager;
  44998. ListenerList <Listener> listeners;
  44999. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  45000. };
  45001. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  45002. typedef MenuBarModel::Listener MenuBarModelListener;
  45003. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  45004. /*** End of inlined file: juce_MenuBarModel.h ***/
  45005. /**
  45006. A resizable window with a title bar and maximise, minimise and close buttons.
  45007. This subclass of ResizableWindow creates a fairly standard type of window with
  45008. a title bar and various buttons. The name of the component is shown in the
  45009. title bar, and an icon can optionally be specified with setIcon().
  45010. All the methods available to a ResizableWindow are also available to this,
  45011. so it can easily be made resizable, minimised, maximised, etc.
  45012. It's not advisable to add child components directly to a DocumentWindow: put them
  45013. inside your content component instead. And overriding methods like resized(), moved(), etc
  45014. is also not recommended - instead override these methods for your content component.
  45015. (If for some obscure reason you do need to override these methods, always remember to
  45016. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  45017. decorations correctly).
  45018. You can also automatically add a menu bar to the window, using the setMenuBar()
  45019. method.
  45020. @see ResizableWindow, DialogWindow
  45021. */
  45022. class JUCE_API DocumentWindow : public ResizableWindow
  45023. {
  45024. public:
  45025. /** The set of available button-types that can be put on the title bar.
  45026. @see setTitleBarButtonsRequired
  45027. */
  45028. enum TitleBarButtons
  45029. {
  45030. minimiseButton = 1,
  45031. maximiseButton = 2,
  45032. closeButton = 4,
  45033. /** A combination of all the buttons above. */
  45034. allButtons = 7
  45035. };
  45036. /** Creates a DocumentWindow.
  45037. @param name the name to give the component - this is also
  45038. the title shown at the top of the window. To change
  45039. this later, use setName()
  45040. @param backgroundColour the colour to use for filling the window's background.
  45041. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45042. should be shown on the title bar. This value is a bitwise
  45043. combination of values from the TitleBarButtons enum. Note
  45044. that it can be "allButtons" to get them all. You
  45045. can change this later with the setTitleBarButtonsRequired()
  45046. method, which can also specify where they are positioned.
  45047. @param addToDesktop if true, the window will be automatically added to the
  45048. desktop; if false, you can use it as a child component
  45049. @see TitleBarButtons
  45050. */
  45051. DocumentWindow (const String& name,
  45052. const Colour& backgroundColour,
  45053. int requiredButtons,
  45054. bool addToDesktop = true);
  45055. /** Destructor.
  45056. If a content component has been set with setContentOwned(), it will be deleted.
  45057. */
  45058. ~DocumentWindow();
  45059. /** Changes the component's name.
  45060. (This is overridden from Component::setName() to cause a repaint, as
  45061. the name is what gets drawn across the window's title bar).
  45062. */
  45063. void setName (const String& newName);
  45064. /** Sets an icon to show in the title bar, next to the title.
  45065. A copy is made internally of the image, so the caller can delete the
  45066. image after calling this. If 0 is passed-in, any existing icon will be
  45067. removed.
  45068. */
  45069. void setIcon (const Image& imageToUse);
  45070. /** Changes the height of the title-bar. */
  45071. void setTitleBarHeight (int newHeight);
  45072. /** Returns the current title bar height. */
  45073. int getTitleBarHeight() const;
  45074. /** Changes the set of title-bar buttons being shown.
  45075. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45076. should be shown on the title bar. This value is a bitwise
  45077. combination of values from the TitleBarButtons enum. Note
  45078. that it can be "allButtons" to get them all.
  45079. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  45080. left side of the bar; if false, they'll be placed at the right
  45081. */
  45082. void setTitleBarButtonsRequired (int requiredButtons,
  45083. bool positionTitleBarButtonsOnLeft);
  45084. /** Sets whether the title should be centred within the window.
  45085. If true, the title text is shown in the middle of the title-bar; if false,
  45086. it'll be shown at the left of the bar.
  45087. */
  45088. void setTitleBarTextCentred (bool textShouldBeCentred);
  45089. /** Creates a menu inside this window.
  45090. @param menuBarModel this specifies a MenuBarModel that should be used to
  45091. generate the contents of a menu bar that will be placed
  45092. just below the title bar, and just above any content
  45093. component. If this value is zero, any existing menu bar
  45094. will be removed from the component; if non-zero, one will
  45095. be added if it's required.
  45096. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  45097. or less to use the look-and-feel's default size.
  45098. */
  45099. void setMenuBar (MenuBarModel* menuBarModel,
  45100. int menuBarHeight = 0);
  45101. /** Returns the current menu bar component, or null if there isn't one.
  45102. This is probably a MenuBarComponent, unless a custom one has been set using
  45103. setMenuBarComponent().
  45104. */
  45105. Component* getMenuBarComponent() const noexcept;
  45106. /** Replaces the current menu bar with a custom component.
  45107. The component will be owned and deleted by the document window.
  45108. */
  45109. void setMenuBarComponent (Component* newMenuBarComponent);
  45110. /** This method is called when the user tries to close the window.
  45111. This is triggered by the user clicking the close button, or using some other
  45112. OS-specific key shortcut or OS menu for getting rid of a window.
  45113. If the window is just a pop-up, you should override this closeButtonPressed()
  45114. method and make it delete the window in whatever way is appropriate for your
  45115. app. E.g. you might just want to call "delete this".
  45116. If your app is centred around this window such that the whole app should quit when
  45117. the window is closed, then you will probably want to use this method as an opportunity
  45118. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  45119. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  45120. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  45121. or closing it via the taskbar icon on Windows).
  45122. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  45123. redirects it to call this method, so any methods of closing the window that are
  45124. caught by userTriedToCloseWindow() will also end up here).
  45125. */
  45126. virtual void closeButtonPressed();
  45127. /** Callback that is triggered when the minimise button is pressed.
  45128. The default implementation of this calls ResizableWindow::setMinimised(), but
  45129. you can override it to do more customised behaviour.
  45130. */
  45131. virtual void minimiseButtonPressed();
  45132. /** Callback that is triggered when the maximise button is pressed, or when the
  45133. title-bar is double-clicked.
  45134. The default implementation of this calls ResizableWindow::setFullScreen(), but
  45135. you can override it to do more customised behaviour.
  45136. */
  45137. virtual void maximiseButtonPressed();
  45138. /** Returns the close button, (or 0 if there isn't one). */
  45139. Button* getCloseButton() const noexcept;
  45140. /** Returns the minimise button, (or 0 if there isn't one). */
  45141. Button* getMinimiseButton() const noexcept;
  45142. /** Returns the maximise button, (or 0 if there isn't one). */
  45143. Button* getMaximiseButton() const noexcept;
  45144. /** A set of colour IDs to use to change the colour of various aspects of the window.
  45145. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45146. methods.
  45147. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45148. */
  45149. enum ColourIds
  45150. {
  45151. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  45152. and feel class how this is used. */
  45153. };
  45154. /** @internal */
  45155. void paint (Graphics& g);
  45156. /** @internal */
  45157. void resized();
  45158. /** @internal */
  45159. void lookAndFeelChanged();
  45160. /** @internal */
  45161. const BorderSize<int> getBorderThickness();
  45162. /** @internal */
  45163. const BorderSize<int> getContentComponentBorder();
  45164. /** @internal */
  45165. void mouseDoubleClick (const MouseEvent& e);
  45166. /** @internal */
  45167. void userTriedToCloseWindow();
  45168. /** @internal */
  45169. void activeWindowStatusChanged();
  45170. /** @internal */
  45171. int getDesktopWindowStyleFlags() const;
  45172. /** @internal */
  45173. void parentHierarchyChanged();
  45174. /** @internal */
  45175. const Rectangle<int> getTitleBarArea();
  45176. private:
  45177. int titleBarHeight, menuBarHeight, requiredButtons;
  45178. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  45179. ScopedPointer <Button> titleBarButtons [3];
  45180. Image titleBarIcon;
  45181. ScopedPointer <Component> menuBar;
  45182. MenuBarModel* menuBarModel;
  45183. class ButtonListenerProxy;
  45184. friend class ScopedPointer <ButtonListenerProxy>;
  45185. ScopedPointer <ButtonListenerProxy> buttonListener;
  45186. void repaintTitleBar();
  45187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  45188. };
  45189. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45190. /*** End of inlined file: juce_DocumentWindow.h ***/
  45191. class MultiDocumentPanel;
  45192. class MDITabbedComponentInternal;
  45193. /**
  45194. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  45195. component.
  45196. It's like a normal DocumentWindow but has some extra functionality to make sure
  45197. everything works nicely inside a MultiDocumentPanel.
  45198. @see MultiDocumentPanel
  45199. */
  45200. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  45201. {
  45202. public:
  45203. /**
  45204. */
  45205. MultiDocumentPanelWindow (const Colour& backgroundColour);
  45206. /** Destructor. */
  45207. ~MultiDocumentPanelWindow();
  45208. /** @internal */
  45209. void maximiseButtonPressed();
  45210. /** @internal */
  45211. void closeButtonPressed();
  45212. /** @internal */
  45213. void activeWindowStatusChanged();
  45214. /** @internal */
  45215. void broughtToFront();
  45216. private:
  45217. void updateOrder();
  45218. MultiDocumentPanel* getOwner() const noexcept;
  45219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  45220. };
  45221. /**
  45222. A component that contains a set of other components either in floating windows
  45223. or tabs.
  45224. This acts as a panel that can be used to hold a set of open document windows, with
  45225. different layout modes.
  45226. Use addDocument() and closeDocument() to add or remove components from the
  45227. panel - never use any of the Component methods to access the panel's child
  45228. components directly, as these are managed internally.
  45229. */
  45230. class JUCE_API MultiDocumentPanel : public Component,
  45231. private ComponentListener
  45232. {
  45233. public:
  45234. /** Creates an empty panel.
  45235. Use addDocument() and closeDocument() to add or remove components from the
  45236. panel - never use any of the Component methods to access the panel's child
  45237. components directly, as these are managed internally.
  45238. */
  45239. MultiDocumentPanel();
  45240. /** Destructor.
  45241. When deleted, this will call closeAllDocuments (false) to make sure all its
  45242. components are deleted. If you need to make sure all documents are saved
  45243. before closing, then you should call closeAllDocuments (true) and check that
  45244. it returns true before deleting the panel.
  45245. */
  45246. ~MultiDocumentPanel();
  45247. /** Tries to close all the documents.
  45248. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45249. be called for each open document, and any of these calls fails, this method
  45250. will stop and return false, leaving some documents still open.
  45251. If checkItsOkToCloseFirst is false, then all documents will be closed
  45252. unconditionally.
  45253. @see closeDocument
  45254. */
  45255. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  45256. /** Adds a document component to the panel.
  45257. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  45258. this will fail and return false. (If it does fail, the component passed-in will not be
  45259. deleted, even if deleteWhenRemoved was set to true).
  45260. The MultiDocumentPanel will deal with creating a window border to go around your component,
  45261. so just pass in the bare content component here, no need to give it a ResizableWindow
  45262. or DocumentWindow.
  45263. @param component the component to add
  45264. @param backgroundColour the background colour to use to fill the component's
  45265. window or tab
  45266. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  45267. or closeAllDocuments(), then it will be deleted. If false, then
  45268. the caller must handle the component's deletion
  45269. */
  45270. bool addDocument (Component* component,
  45271. const Colour& backgroundColour,
  45272. bool deleteWhenRemoved);
  45273. /** Closes one of the documents.
  45274. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45275. be called, and if it fails, this method will return false without closing the
  45276. document.
  45277. If checkItsOkToCloseFirst is false, then the documents will be closed
  45278. unconditionally.
  45279. The component will be deleted if the deleteWhenRemoved parameter was set to
  45280. true when it was added with addDocument.
  45281. @see addDocument, closeAllDocuments
  45282. */
  45283. bool closeDocument (Component* component,
  45284. bool checkItsOkToCloseFirst);
  45285. /** Returns the number of open document windows.
  45286. @see getDocument
  45287. */
  45288. int getNumDocuments() const noexcept;
  45289. /** Returns one of the open documents.
  45290. The order of the documents in this array may change when they are added, removed
  45291. or moved around.
  45292. @see getNumDocuments
  45293. */
  45294. Component* getDocument (int index) const noexcept;
  45295. /** Returns the document component that is currently focused or on top.
  45296. If currently using floating windows, then this will be the component in the currently
  45297. active window, or the top component if none are active.
  45298. If it's currently in tabbed mode, then it'll return the component in the active tab.
  45299. @see setActiveDocument
  45300. */
  45301. Component* getActiveDocument() const noexcept;
  45302. /** Makes one of the components active and brings it to the top.
  45303. @see getActiveDocument
  45304. */
  45305. void setActiveDocument (Component* component);
  45306. /** Callback which gets invoked when the currently-active document changes. */
  45307. virtual void activeDocumentChanged();
  45308. /** Sets a limit on how many windows can be open at once.
  45309. If this is zero or less there's no limit (the default). addDocument() will fail
  45310. if this number is exceeded.
  45311. */
  45312. void setMaximumNumDocuments (int maximumNumDocuments);
  45313. /** Sets an option to make the document fullscreen if there's only one document open.
  45314. If set to true, then if there's only one document, it'll fill the whole of this
  45315. component without tabs or a window border. If false, then tabs or a window
  45316. will always be shown, even if there's only one document. If there's more than
  45317. one document open, then this option makes no difference.
  45318. */
  45319. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  45320. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  45321. */
  45322. bool isFullscreenWhenOneDocument() const noexcept;
  45323. /** The different layout modes available. */
  45324. enum LayoutMode
  45325. {
  45326. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  45327. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  45328. };
  45329. /** Changes the panel's mode.
  45330. @see LayoutMode, getLayoutMode
  45331. */
  45332. void setLayoutMode (LayoutMode newLayoutMode);
  45333. /** Returns the current layout mode. */
  45334. LayoutMode getLayoutMode() const noexcept { return mode; }
  45335. /** Sets the background colour for the whole panel.
  45336. Each document has its own background colour, but this is the one used to fill the areas
  45337. behind them.
  45338. */
  45339. void setBackgroundColour (const Colour& newBackgroundColour);
  45340. /** Returns the current background colour.
  45341. @see setBackgroundColour
  45342. */
  45343. const Colour& getBackgroundColour() const noexcept { return backgroundColour; }
  45344. /** A subclass must override this to say whether its currently ok for a document
  45345. to be closed.
  45346. This method is called by closeDocument() and closeAllDocuments() to indicate that
  45347. a document should be saved if possible, ready for it to be closed.
  45348. If this method returns true, then it means the document is ok and can be closed.
  45349. If it returns false, then it means that the closeDocument() method should stop
  45350. and not close.
  45351. Normally, you'd use this method to ask the user if they want to save any changes,
  45352. then return true if the save operation went ok. If the user cancelled the save
  45353. operation you could return false here to abort the close operation.
  45354. If your component is based on the FileBasedDocument class, then you'd probably want
  45355. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  45356. FileBasedDocument::savedOk
  45357. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  45358. */
  45359. virtual bool tryToCloseDocument (Component* component) = 0;
  45360. /** Creates a new window to be used for a document.
  45361. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  45362. but you might want to override it to return a custom component.
  45363. */
  45364. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  45365. /** @internal */
  45366. void paint (Graphics& g);
  45367. /** @internal */
  45368. void resized();
  45369. /** @internal */
  45370. void componentNameChanged (Component&);
  45371. private:
  45372. LayoutMode mode;
  45373. Array <Component*> components;
  45374. ScopedPointer<TabbedComponent> tabComponent;
  45375. Colour backgroundColour;
  45376. int maximumNumDocuments, numDocsBeforeTabsUsed;
  45377. friend class MultiDocumentPanelWindow;
  45378. friend class MDITabbedComponentInternal;
  45379. Component* getContainerComp (Component* c) const;
  45380. void updateOrder();
  45381. void addWindow (Component* component);
  45382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  45383. };
  45384. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45385. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  45386. #endif
  45387. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  45388. #endif
  45389. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  45390. #endif
  45391. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45392. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  45393. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45394. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45395. /**
  45396. A component that resizes its parent component when dragged.
  45397. This component forms a bar along one edge of a component, allowing it to
  45398. be dragged by that edges to resize it.
  45399. To use it, just add it to your component, positioning it along the appropriate
  45400. edge. Make sure you reposition the resizer component each time the parent's size
  45401. changes, to keep it in the correct position.
  45402. @see ResizbleBorderComponent, ResizableCornerComponent
  45403. */
  45404. class JUCE_API ResizableEdgeComponent : public Component
  45405. {
  45406. public:
  45407. enum Edge
  45408. {
  45409. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  45410. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  45411. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  45412. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  45413. };
  45414. /** Creates a resizer bar.
  45415. Pass in the target component which you want to be resized when this one is
  45416. dragged. The target component will usually be this component's parent, but this
  45417. isn't mandatory.
  45418. Remember that when the target component is resized, it'll need to move and
  45419. resize this component to keep it in place, as this won't happen automatically.
  45420. If the constrainer parameter is non-zero, then this object will be used to enforce
  45421. limits on the size and position that the component can be stretched to. Make sure
  45422. that the constrainer isn't deleted while still in use by this object.
  45423. @see ComponentBoundsConstrainer
  45424. */
  45425. ResizableEdgeComponent (Component* componentToResize,
  45426. ComponentBoundsConstrainer* constrainer,
  45427. Edge edgeToResize);
  45428. /** Destructor. */
  45429. ~ResizableEdgeComponent();
  45430. bool isVertical() const noexcept;
  45431. protected:
  45432. /** @internal */
  45433. void paint (Graphics& g);
  45434. /** @internal */
  45435. void mouseDown (const MouseEvent& e);
  45436. /** @internal */
  45437. void mouseDrag (const MouseEvent& e);
  45438. /** @internal */
  45439. void mouseUp (const MouseEvent& e);
  45440. private:
  45441. WeakReference<Component> component;
  45442. ComponentBoundsConstrainer* constrainer;
  45443. Rectangle<int> originalBounds;
  45444. const Edge edge;
  45445. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  45446. };
  45447. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45448. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  45449. #endif
  45450. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  45451. #endif
  45452. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45453. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  45454. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45455. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45456. /**
  45457. For laying out a set of components, where the components have preferred sizes
  45458. and size limits, but where they are allowed to stretch to fill the available
  45459. space.
  45460. For example, if you have a component containing several other components, and
  45461. each one should be given a share of the total size, you could use one of these
  45462. to resize the child components when the parent component is resized. Then
  45463. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  45464. A StretchableLayoutManager operates only in one dimension, so if you have a set
  45465. of components stacked vertically on top of each other, you'd use one to manage their
  45466. heights. To build up complex arrangements of components, e.g. for applications
  45467. with multiple nested panels, you would use more than one StretchableLayoutManager.
  45468. E.g. by using two (one vertical, one horizontal), you could create a resizable
  45469. spreadsheet-style table.
  45470. E.g.
  45471. @code
  45472. class MyComp : public Component
  45473. {
  45474. StretchableLayoutManager myLayout;
  45475. MyComp()
  45476. {
  45477. myLayout.setItemLayout (0, // for item 0
  45478. 50, 100, // must be between 50 and 100 pixels in size
  45479. -0.6); // and its preferred size is 60% of the total available space
  45480. myLayout.setItemLayout (1, // for item 1
  45481. -0.2, -0.6, // size must be between 20% and 60% of the available space
  45482. 50); // and its preferred size is 50 pixels
  45483. }
  45484. void resized()
  45485. {
  45486. // make a list of two of our child components that we want to reposition
  45487. Component* comps[] = { myComp1, myComp2 };
  45488. // this will position the 2 components, one above the other, to fit
  45489. // vertically into the rectangle provided.
  45490. myLayout.layOutComponents (comps, 2,
  45491. 0, 0, getWidth(), getHeight(),
  45492. true);
  45493. }
  45494. };
  45495. @endcode
  45496. @see StretchableLayoutResizerBar
  45497. */
  45498. class JUCE_API StretchableLayoutManager
  45499. {
  45500. public:
  45501. /** Creates an empty layout.
  45502. You'll need to add some item properties to the layout before it can be used
  45503. to resize things - see setItemLayout().
  45504. */
  45505. StretchableLayoutManager();
  45506. /** Destructor. */
  45507. ~StretchableLayoutManager();
  45508. /** For a numbered item, this sets its size limits and preferred size.
  45509. @param itemIndex the index of the item to change.
  45510. @param minimumSize the minimum size that this item is allowed to be - a positive number
  45511. indicates an absolute size in pixels. A negative number indicates a
  45512. proportion of the available space (e.g -0.5 is 50%)
  45513. @param maximumSize the maximum size that this item is allowed to be - a positive number
  45514. indicates an absolute size in pixels. A negative number indicates a
  45515. proportion of the available space
  45516. @param preferredSize the size that this item would like to be, if there's enough room. A
  45517. positive number indicates an absolute size in pixels. A negative number
  45518. indicates a proportion of the available space
  45519. @see getItemLayout
  45520. */
  45521. void setItemLayout (int itemIndex,
  45522. double minimumSize,
  45523. double maximumSize,
  45524. double preferredSize);
  45525. /** For a numbered item, this returns its size limits and preferred size.
  45526. @param itemIndex the index of the item.
  45527. @param minimumSize the minimum size that this item is allowed to be - a positive number
  45528. indicates an absolute size in pixels. A negative number indicates a
  45529. proportion of the available space (e.g -0.5 is 50%)
  45530. @param maximumSize the maximum size that this item is allowed to be - a positive number
  45531. indicates an absolute size in pixels. A negative number indicates a
  45532. proportion of the available space
  45533. @param preferredSize the size that this item would like to be, if there's enough room. A
  45534. positive number indicates an absolute size in pixels. A negative number
  45535. indicates a proportion of the available space
  45536. @returns false if the item's properties hadn't been set
  45537. @see setItemLayout
  45538. */
  45539. bool getItemLayout (int itemIndex,
  45540. double& minimumSize,
  45541. double& maximumSize,
  45542. double& preferredSize) const;
  45543. /** Clears all the properties that have been set with setItemLayout() and resets
  45544. this object to its initial state.
  45545. */
  45546. void clearAllItems();
  45547. /** Takes a set of components that correspond to the layout's items, and positions
  45548. them to fill a space.
  45549. This will try to give each item its preferred size, whether that's a relative size
  45550. or an absolute one.
  45551. @param components an array of components that correspond to each of the
  45552. numbered items that the StretchableLayoutManager object
  45553. has been told about with setItemLayout()
  45554. @param numComponents the number of components in the array that is passed-in. This
  45555. should be the same as the number of items this object has been
  45556. told about.
  45557. @param x the left of the rectangle in which the components should
  45558. be laid out
  45559. @param y the top of the rectangle in which the components should
  45560. be laid out
  45561. @param width the width of the rectangle in which the components should
  45562. be laid out
  45563. @param height the height of the rectangle in which the components should
  45564. be laid out
  45565. @param vertically if true, the components will be positioned in a vertical stack,
  45566. so that they fill the height of the rectangle. If false, they
  45567. will be placed side-by-side in a horizontal line, filling the
  45568. available width
  45569. @param resizeOtherDimension if true, this means that the components will have their
  45570. other dimension resized to fit the space - i.e. if the 'vertically'
  45571. parameter is true, their x-positions and widths are adjusted to fit
  45572. the x and width parameters; if 'vertically' is false, their y-positions
  45573. and heights are adjusted to fit the y and height parameters.
  45574. */
  45575. void layOutComponents (Component** components,
  45576. int numComponents,
  45577. int x, int y, int width, int height,
  45578. bool vertically,
  45579. bool resizeOtherDimension);
  45580. /** Returns the current position of one of the items.
  45581. This is only a valid call after layOutComponents() has been called, as it
  45582. returns the last position that this item was placed at. If the layout was
  45583. vertical, the value returned will be the y position of the top of the item,
  45584. relative to the top of the rectangle in which the items were placed (so for
  45585. example, item 0 will always have position of 0, even in the rectangle passed
  45586. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  45587. the position returned is the item's left-hand position, again relative to the
  45588. x position of the rectangle used.
  45589. @see getItemCurrentSize, setItemPosition
  45590. */
  45591. int getItemCurrentPosition (int itemIndex) const;
  45592. /** Returns the current size of one of the items.
  45593. This is only meaningful after layOutComponents() has been called, as it
  45594. returns the last size that this item was given. If the layout was done
  45595. vertically, it'll return the item's height in pixels; if it was horizontal,
  45596. it'll return its width.
  45597. @see getItemCurrentRelativeSize
  45598. */
  45599. int getItemCurrentAbsoluteSize (int itemIndex) const;
  45600. /** Returns the current size of one of the items.
  45601. This is only meaningful after layOutComponents() has been called, as it
  45602. returns the last size that this item was given. If the layout was done
  45603. vertically, it'll return a negative value representing the item's height relative
  45604. to the last size used for laying the components out; if the layout was done
  45605. horizontally it'll be the proportion of its width.
  45606. @see getItemCurrentAbsoluteSize
  45607. */
  45608. double getItemCurrentRelativeSize (int itemIndex) const;
  45609. /** Moves one of the items, shifting along any other items as necessary in
  45610. order to get it to the desired position.
  45611. Calling this method will also update the preferred sizes of the items it
  45612. shuffles along, so that they reflect their new positions.
  45613. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  45614. about when it's dragged).
  45615. @param itemIndex the item to move
  45616. @param newPosition the absolute position that you'd like this item to move
  45617. to. The item might not be able to always reach exactly this position,
  45618. because other items may have minimum sizes that constrain how
  45619. far it can go
  45620. */
  45621. void setItemPosition (int itemIndex,
  45622. int newPosition);
  45623. private:
  45624. struct ItemLayoutProperties
  45625. {
  45626. int itemIndex;
  45627. int currentSize;
  45628. double minSize, maxSize, preferredSize;
  45629. };
  45630. OwnedArray <ItemLayoutProperties> items;
  45631. int totalSize;
  45632. static int sizeToRealSize (double size, int totalSpace);
  45633. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  45634. void setTotalSize (int newTotalSize);
  45635. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  45636. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  45637. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  45638. void updatePrefSizesToMatchCurrentPositions();
  45639. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  45640. };
  45641. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45642. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  45643. #endif
  45644. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45645. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45646. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45647. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45648. /**
  45649. A component that acts as one of the vertical or horizontal bars you see being
  45650. used to resize panels in a window.
  45651. One of these acts with a StretchableLayoutManager to resize the other components.
  45652. @see StretchableLayoutManager
  45653. */
  45654. class JUCE_API StretchableLayoutResizerBar : public Component
  45655. {
  45656. public:
  45657. /** Creates a resizer bar for use on a specified layout.
  45658. @param layoutToUse the layout that will be affected when this bar
  45659. is dragged
  45660. @param itemIndexInLayout the item index in the layout that corresponds to
  45661. this bar component. You'll need to set up the item
  45662. properties in a suitable way for a divider bar, e.g.
  45663. for an 8-pixel wide bar which, you could call
  45664. myLayout->setItemLayout (barIndex, 8, 8, 8)
  45665. @param isBarVertical true if it's an upright bar that you drag left and
  45666. right; false for a horizontal one that you drag up and
  45667. down
  45668. */
  45669. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  45670. int itemIndexInLayout,
  45671. bool isBarVertical);
  45672. /** Destructor. */
  45673. ~StretchableLayoutResizerBar();
  45674. /** This is called when the bar is dragged.
  45675. This method must update the positions of any components whose position is
  45676. determined by the StretchableLayoutManager, because they might have just
  45677. moved.
  45678. The default implementation calls the resized() method of this component's
  45679. parent component, because that's often where you're likely to apply the
  45680. layout, but it can be overridden for more specific needs.
  45681. */
  45682. virtual void hasBeenMoved();
  45683. /** @internal */
  45684. void paint (Graphics& g);
  45685. /** @internal */
  45686. void mouseDown (const MouseEvent& e);
  45687. /** @internal */
  45688. void mouseDrag (const MouseEvent& e);
  45689. private:
  45690. StretchableLayoutManager* layout;
  45691. int itemIndex, mouseDownPos;
  45692. bool isVertical;
  45693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  45694. };
  45695. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45696. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45697. #endif
  45698. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45699. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  45700. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45701. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45702. /**
  45703. A utility class for fitting a set of objects whose sizes can vary between
  45704. a minimum and maximum size, into a space.
  45705. This is a trickier algorithm than it would first seem, so I've put it in this
  45706. class to allow it to be shared by various bits of code.
  45707. To use it, create one of these objects, call addItem() to add the list of items
  45708. you need, then call resizeToFit(), which will change all their sizes. You can
  45709. then retrieve the new sizes with getItemSize() and getNumItems().
  45710. It's currently used by the TableHeaderComponent for stretching out the table
  45711. headings to fill the table's width.
  45712. */
  45713. class StretchableObjectResizer
  45714. {
  45715. public:
  45716. /** Creates an empty object resizer. */
  45717. StretchableObjectResizer();
  45718. /** Destructor. */
  45719. ~StretchableObjectResizer();
  45720. /** Adds an item to the list.
  45721. The order parameter lets you specify groups of items that are resized first when some
  45722. space needs to be found. Those items with an order of 0 will be the first ones to be
  45723. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  45724. will then try resizing the items with an order of 1, then 2, and so on.
  45725. */
  45726. void addItem (double currentSize,
  45727. double minSize,
  45728. double maxSize,
  45729. int order = 0);
  45730. /** Resizes all the items to fit this amount of space.
  45731. This will attempt to fit them in without exceeding each item's miniumum and
  45732. maximum sizes. In cases where none of the items can be expanded or enlarged any
  45733. further, the final size may be greater or less than the size passed in.
  45734. After calling this method, you can retrieve the new sizes with the getItemSize()
  45735. method.
  45736. */
  45737. void resizeToFit (double targetSize);
  45738. /** Returns the number of items that have been added. */
  45739. int getNumItems() const noexcept { return items.size(); }
  45740. /** Returns the size of one of the items. */
  45741. double getItemSize (int index) const noexcept;
  45742. private:
  45743. struct Item
  45744. {
  45745. double size;
  45746. double minSize;
  45747. double maxSize;
  45748. int order;
  45749. };
  45750. OwnedArray <Item> items;
  45751. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  45752. };
  45753. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45754. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  45755. #endif
  45756. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45757. #endif
  45758. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45759. #endif
  45760. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  45761. #endif
  45762. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45763. /*** Start of inlined file: juce_LookAndFeel.h ***/
  45764. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45765. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  45766. class ToggleButton;
  45767. class TextButton;
  45768. class AlertWindow;
  45769. class TextLayout;
  45770. class ScrollBar;
  45771. class BubbleComponent;
  45772. class ComboBox;
  45773. class Button;
  45774. class FilenameComponent;
  45775. class DocumentWindow;
  45776. class ResizableWindow;
  45777. class GroupComponent;
  45778. class MenuBarComponent;
  45779. class DropShadower;
  45780. class GlyphArrangement;
  45781. class PropertyComponent;
  45782. class TableHeaderComponent;
  45783. class Toolbar;
  45784. class ToolbarItemComponent;
  45785. class PopupMenu;
  45786. class ProgressBar;
  45787. class FileBrowserComponent;
  45788. class DirectoryContentsDisplayComponent;
  45789. class FilePreviewComponent;
  45790. class ImageButton;
  45791. class CallOutBox;
  45792. class Drawable;
  45793. class CaretComponent;
  45794. /**
  45795. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  45796. can be used to apply different 'skins' to the application.
  45797. */
  45798. class JUCE_API LookAndFeel
  45799. {
  45800. public:
  45801. /** Creates the default JUCE look and feel. */
  45802. LookAndFeel();
  45803. /** Destructor. */
  45804. virtual ~LookAndFeel();
  45805. /** Returns the current default look-and-feel for a component to use when it
  45806. hasn't got one explicitly set.
  45807. @see setDefaultLookAndFeel
  45808. */
  45809. static LookAndFeel& getDefaultLookAndFeel() noexcept;
  45810. /** Changes the default look-and-feel.
  45811. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  45812. set to null, it will revert to using the default one. The
  45813. object passed-in must be deleted by the caller when
  45814. it's no longer needed.
  45815. @see getDefaultLookAndFeel
  45816. */
  45817. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) noexcept;
  45818. /** Looks for a colour that has been registered with the given colour ID number.
  45819. If a colour has been set for this ID number using setColour(), then it is
  45820. returned. If none has been set, it will just return Colours::black.
  45821. The colour IDs for various purposes are stored as enums in the components that
  45822. they are relevent to - for an example, see Slider::ColourIds,
  45823. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  45824. If you're looking up a colour for use in drawing a component, it's usually
  45825. best not to call this directly, but to use the Component::findColour() method
  45826. instead. That will first check whether a suitable colour has been registered
  45827. directly with the component, and will fall-back on calling the component's
  45828. LookAndFeel's findColour() method if none is found.
  45829. @see setColour, Component::findColour, Component::setColour
  45830. */
  45831. const Colour findColour (int colourId) const noexcept;
  45832. /** Registers a colour to be used for a particular purpose.
  45833. For more details, see the comments for findColour().
  45834. @see findColour, Component::findColour, Component::setColour
  45835. */
  45836. void setColour (int colourId, const Colour& colour) noexcept;
  45837. /** Returns true if the specified colour ID has been explicitly set using the
  45838. setColour() method.
  45839. */
  45840. bool isColourSpecified (int colourId) const noexcept;
  45841. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  45842. /** Allows you to change the default sans-serif font.
  45843. If you need to supply your own Typeface object for any of the default fonts, rather
  45844. than just supplying the name (e.g. if you want to use an embedded font), then
  45845. you should instead override getTypefaceForFont() to create and return the typeface.
  45846. */
  45847. void setDefaultSansSerifTypefaceName (const String& newName);
  45848. /** Override this to get the chance to swap a component's mouse cursor for a
  45849. customised one.
  45850. */
  45851. virtual const MouseCursor getMouseCursorFor (Component& component);
  45852. /** Draws the lozenge-shaped background for a standard button. */
  45853. virtual void drawButtonBackground (Graphics& g,
  45854. Button& button,
  45855. const Colour& backgroundColour,
  45856. bool isMouseOverButton,
  45857. bool isButtonDown);
  45858. virtual const Font getFontForTextButton (TextButton& button);
  45859. /** Draws the text for a TextButton. */
  45860. virtual void drawButtonText (Graphics& g,
  45861. TextButton& button,
  45862. bool isMouseOverButton,
  45863. bool isButtonDown);
  45864. /** Draws the contents of a standard ToggleButton. */
  45865. virtual void drawToggleButton (Graphics& g,
  45866. ToggleButton& button,
  45867. bool isMouseOverButton,
  45868. bool isButtonDown);
  45869. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  45870. virtual void drawTickBox (Graphics& g,
  45871. Component& component,
  45872. float x, float y, float w, float h,
  45873. bool ticked,
  45874. bool isEnabled,
  45875. bool isMouseOverButton,
  45876. bool isButtonDown);
  45877. /* AlertWindow handling..
  45878. */
  45879. virtual AlertWindow* createAlertWindow (const String& title,
  45880. const String& message,
  45881. const String& button1,
  45882. const String& button2,
  45883. const String& button3,
  45884. AlertWindow::AlertIconType iconType,
  45885. int numButtons,
  45886. Component* associatedComponent);
  45887. virtual void drawAlertBox (Graphics& g,
  45888. AlertWindow& alert,
  45889. const Rectangle<int>& textArea,
  45890. TextLayout& textLayout);
  45891. virtual int getAlertBoxWindowFlags();
  45892. virtual int getAlertWindowButtonHeight();
  45893. virtual const Font getAlertWindowMessageFont();
  45894. virtual const Font getAlertWindowFont();
  45895. void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
  45896. bool isUsingNativeAlertWindows();
  45897. /** Draws a progress bar.
  45898. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  45899. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  45900. isn't known). It can use the current time as a basis for playing an animation.
  45901. (Used by progress bars in AlertWindow).
  45902. */
  45903. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  45904. int width, int height,
  45905. double progress, const String& textToShow);
  45906. // Draws a small image that spins to indicate that something's happening..
  45907. // This method should use the current time to animate itself, so just keep
  45908. // repainting it every so often.
  45909. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  45910. int x, int y, int w, int h);
  45911. /** Draws one of the buttons on a scrollbar.
  45912. @param g the context to draw into
  45913. @param scrollbar the bar itself
  45914. @param width the width of the button
  45915. @param height the height of the button
  45916. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  45917. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45918. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  45919. @param isButtonDown whether the mouse button's held down
  45920. */
  45921. virtual void drawScrollbarButton (Graphics& g,
  45922. ScrollBar& scrollbar,
  45923. int width, int height,
  45924. int buttonDirection,
  45925. bool isScrollbarVertical,
  45926. bool isMouseOverButton,
  45927. bool isButtonDown);
  45928. /** Draws the thumb area of a scrollbar.
  45929. @param g the context to draw into
  45930. @param scrollbar the bar itself
  45931. @param x the x position of the left edge of the thumb area to draw in
  45932. @param y the y position of the top edge of the thumb area to draw in
  45933. @param width the width of the thumb area to draw in
  45934. @param height the height of the thumb area to draw in
  45935. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45936. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  45937. thumb, or its x position for horizontal bars
  45938. @param thumbSize for vertical bars, the height of the thumb, or its width for
  45939. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  45940. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  45941. currently dragging the thumb
  45942. @param isMouseDown whether the mouse is currently dragging the scrollbar
  45943. */
  45944. virtual void drawScrollbar (Graphics& g,
  45945. ScrollBar& scrollbar,
  45946. int x, int y,
  45947. int width, int height,
  45948. bool isScrollbarVertical,
  45949. int thumbStartPosition,
  45950. int thumbSize,
  45951. bool isMouseOver,
  45952. bool isMouseDown);
  45953. /** Returns the component effect to use for a scrollbar */
  45954. virtual ImageEffectFilter* getScrollbarEffect();
  45955. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  45956. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  45957. /** Returns the default thickness to use for a scrollbar. */
  45958. virtual int getDefaultScrollbarWidth();
  45959. /** Returns the length in pixels to use for a scrollbar button. */
  45960. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  45961. /** Returns a tick shape for use in yes/no boxes, etc. */
  45962. virtual const Path getTickShape (float height);
  45963. /** Returns a cross shape for use in yes/no boxes, etc. */
  45964. virtual const Path getCrossShape (float height);
  45965. /** Draws the + or - box in a treeview. */
  45966. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  45967. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  45968. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  45969. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
  45970. // These return a pointer to an internally cached drawable - make sure you don't keep
  45971. // a copy of this pointer anywhere, as it may become invalid in the future.
  45972. virtual const Drawable* getDefaultFolderImage();
  45973. virtual const Drawable* getDefaultDocumentFileImage();
  45974. virtual void createFileChooserHeaderText (const String& title,
  45975. const String& instructions,
  45976. GlyphArrangement& destArrangement,
  45977. int width);
  45978. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  45979. const String& filename, Image* icon,
  45980. const String& fileSizeDescription,
  45981. const String& fileTimeDescription,
  45982. bool isDirectory,
  45983. bool isItemSelected,
  45984. int itemIndex,
  45985. DirectoryContentsDisplayComponent& component);
  45986. virtual Button* createFileBrowserGoUpButton();
  45987. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  45988. DirectoryContentsDisplayComponent* fileListComponent,
  45989. FilePreviewComponent* previewComp,
  45990. ComboBox* currentPathBox,
  45991. TextEditor* filenameBox,
  45992. Button* goUpButton);
  45993. virtual void drawBubble (Graphics& g,
  45994. float tipX, float tipY,
  45995. float boxX, float boxY, float boxW, float boxH);
  45996. /** Fills the background of a popup menu component. */
  45997. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  45998. /** Draws one of the items in a popup menu. */
  45999. virtual void drawPopupMenuItem (Graphics& g,
  46000. int width, int height,
  46001. bool isSeparator,
  46002. bool isActive,
  46003. bool isHighlighted,
  46004. bool isTicked,
  46005. bool hasSubMenu,
  46006. const String& text,
  46007. const String& shortcutKeyText,
  46008. Image* image,
  46009. const Colour* const textColour);
  46010. /** Returns the size and style of font to use in popup menus. */
  46011. virtual const Font getPopupMenuFont();
  46012. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  46013. int width, int height,
  46014. bool isScrollUpArrow);
  46015. /** Finds the best size for an item in a popup menu. */
  46016. virtual void getIdealPopupMenuItemSize (const String& text,
  46017. bool isSeparator,
  46018. int standardMenuItemHeight,
  46019. int& idealWidth,
  46020. int& idealHeight);
  46021. virtual int getMenuWindowFlags();
  46022. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46023. bool isMouseOverBar,
  46024. MenuBarComponent& menuBar);
  46025. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46026. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46027. virtual void drawMenuBarItem (Graphics& g,
  46028. int width, int height,
  46029. int itemIndex,
  46030. const String& itemText,
  46031. bool isMouseOverItem,
  46032. bool isMenuOpen,
  46033. bool isMouseOverBar,
  46034. MenuBarComponent& menuBar);
  46035. virtual void drawComboBox (Graphics& g, int width, int height,
  46036. bool isButtonDown,
  46037. int buttonX, int buttonY,
  46038. int buttonW, int buttonH,
  46039. ComboBox& box);
  46040. virtual const Font getComboBoxFont (ComboBox& box);
  46041. virtual Label* createComboBoxTextBox (ComboBox& box);
  46042. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  46043. virtual void drawLabel (Graphics& g, Label& label);
  46044. virtual void drawLinearSlider (Graphics& g,
  46045. int x, int y,
  46046. int width, int height,
  46047. float sliderPos,
  46048. float minSliderPos,
  46049. float maxSliderPos,
  46050. const Slider::SliderStyle style,
  46051. Slider& slider);
  46052. virtual void drawLinearSliderBackground (Graphics& g,
  46053. int x, int y,
  46054. int width, int height,
  46055. float sliderPos,
  46056. float minSliderPos,
  46057. float maxSliderPos,
  46058. const Slider::SliderStyle style,
  46059. Slider& slider);
  46060. virtual void drawLinearSliderThumb (Graphics& g,
  46061. int x, int y,
  46062. int width, int height,
  46063. float sliderPos,
  46064. float minSliderPos,
  46065. float maxSliderPos,
  46066. const Slider::SliderStyle style,
  46067. Slider& slider);
  46068. virtual int getSliderThumbRadius (Slider& slider);
  46069. virtual void drawRotarySlider (Graphics& g,
  46070. int x, int y,
  46071. int width, int height,
  46072. float sliderPosProportional,
  46073. float rotaryStartAngle,
  46074. float rotaryEndAngle,
  46075. Slider& slider);
  46076. virtual Button* createSliderButton (bool isIncrement);
  46077. virtual Label* createSliderTextBox (Slider& slider);
  46078. virtual ImageEffectFilter* getSliderEffect();
  46079. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  46080. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  46081. virtual Button* createFilenameComponentBrowseButton (const String& text);
  46082. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  46083. ComboBox* filenameBox, Button* browseButton);
  46084. virtual void drawCornerResizer (Graphics& g,
  46085. int w, int h,
  46086. bool isMouseOver,
  46087. bool isMouseDragging);
  46088. virtual void drawResizableFrame (Graphics& g,
  46089. int w, int h,
  46090. const BorderSize<int>& borders);
  46091. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  46092. const BorderSize<int>& border,
  46093. ResizableWindow& window);
  46094. virtual void drawResizableWindowBorder (Graphics& g,
  46095. int w, int h,
  46096. const BorderSize<int>& border,
  46097. ResizableWindow& window);
  46098. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  46099. Graphics& g, int w, int h,
  46100. int titleSpaceX, int titleSpaceW,
  46101. const Image* icon,
  46102. bool drawTitleTextOnLeft);
  46103. virtual Button* createDocumentWindowButton (int buttonType);
  46104. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46105. int titleBarX, int titleBarY,
  46106. int titleBarW, int titleBarH,
  46107. Button* minimiseButton,
  46108. Button* maximiseButton,
  46109. Button* closeButton,
  46110. bool positionTitleBarButtonsOnLeft);
  46111. virtual int getDefaultMenuBarHeight();
  46112. virtual DropShadower* createDropShadowerForComponent (Component* component);
  46113. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  46114. int w, int h,
  46115. bool isVerticalBar,
  46116. bool isMouseOver,
  46117. bool isMouseDragging);
  46118. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  46119. const String& text,
  46120. const Justification& position,
  46121. GroupComponent& group);
  46122. virtual void createTabButtonShape (Path& p,
  46123. int width, int height,
  46124. int tabIndex,
  46125. const String& text,
  46126. Button& button,
  46127. TabbedButtonBar::Orientation orientation,
  46128. bool isMouseOver,
  46129. bool isMouseDown,
  46130. bool isFrontTab);
  46131. virtual void fillTabButtonShape (Graphics& g,
  46132. const Path& path,
  46133. const Colour& preferredBackgroundColour,
  46134. int tabIndex,
  46135. const String& text,
  46136. Button& button,
  46137. TabbedButtonBar::Orientation orientation,
  46138. bool isMouseOver,
  46139. bool isMouseDown,
  46140. bool isFrontTab);
  46141. virtual void drawTabButtonText (Graphics& g,
  46142. int x, int y, int w, int h,
  46143. const Colour& preferredBackgroundColour,
  46144. int tabIndex,
  46145. const String& text,
  46146. Button& button,
  46147. TabbedButtonBar::Orientation orientation,
  46148. bool isMouseOver,
  46149. bool isMouseDown,
  46150. bool isFrontTab);
  46151. virtual int getTabButtonOverlap (int tabDepth);
  46152. virtual int getTabButtonSpaceAroundImage();
  46153. virtual int getTabButtonBestWidth (int tabIndex,
  46154. const String& text,
  46155. int tabDepth,
  46156. Button& button);
  46157. virtual void drawTabButton (Graphics& g,
  46158. int w, int h,
  46159. const Colour& preferredColour,
  46160. int tabIndex,
  46161. const String& text,
  46162. Button& button,
  46163. TabbedButtonBar::Orientation orientation,
  46164. bool isMouseOver,
  46165. bool isMouseDown,
  46166. bool isFrontTab);
  46167. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  46168. int w, int h,
  46169. TabbedButtonBar& tabBar,
  46170. TabbedButtonBar::Orientation orientation);
  46171. virtual Button* createTabBarExtrasButton();
  46172. virtual void drawImageButton (Graphics& g, Image* image,
  46173. int imageX, int imageY, int imageW, int imageH,
  46174. const Colour& overlayColour,
  46175. float imageOpacity,
  46176. ImageButton& button);
  46177. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  46178. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  46179. int width, int height,
  46180. bool isMouseOver, bool isMouseDown,
  46181. int columnFlags);
  46182. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  46183. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  46184. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  46185. bool isMouseOver, bool isMouseDown,
  46186. ToolbarItemComponent& component);
  46187. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  46188. const String& text, ToolbarItemComponent& component);
  46189. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  46190. bool isOpen, int width, int height);
  46191. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  46192. PropertyComponent& component);
  46193. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  46194. PropertyComponent& component);
  46195. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  46196. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  46197. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  46198. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  46199. /**
  46200. */
  46201. virtual void playAlertSound();
  46202. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  46203. static void drawGlassSphere (Graphics& g,
  46204. float x, float y,
  46205. float diameter,
  46206. const Colour& colour,
  46207. float outlineThickness) noexcept;
  46208. static void drawGlassPointer (Graphics& g,
  46209. float x, float y,
  46210. float diameter,
  46211. const Colour& colour, float outlineThickness,
  46212. int direction) noexcept;
  46213. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  46214. static void drawGlassLozenge (Graphics& g,
  46215. float x, float y,
  46216. float width, float height,
  46217. const Colour& colour,
  46218. float outlineThickness,
  46219. float cornerSize,
  46220. bool flatOnLeft, bool flatOnRight,
  46221. bool flatOnTop, bool flatOnBottom) noexcept;
  46222. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  46223. private:
  46224. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  46225. static void clearDefaultLookAndFeel() noexcept; // called at shutdown
  46226. Array <int> colourIds;
  46227. Array <Colour> colours;
  46228. // default typeface names
  46229. String defaultSans, defaultSerif, defaultFixed;
  46230. ScopedPointer<Drawable> folderImage, documentImage;
  46231. bool useNativeAlertWindows;
  46232. void drawShinyButtonShape (Graphics& g,
  46233. float x, float y, float w, float h, float maxCornerSize,
  46234. const Colour& baseColour,
  46235. float strokeWidth,
  46236. bool flatOnLeft,
  46237. bool flatOnRight,
  46238. bool flatOnTop,
  46239. bool flatOnBottom) noexcept;
  46240. // This has been deprecated - see the new parameter list..
  46241. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  46242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  46243. };
  46244. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  46245. /*** End of inlined file: juce_LookAndFeel.h ***/
  46246. #endif
  46247. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46248. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46249. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46250. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46251. /**
  46252. The original Juce look-and-feel.
  46253. */
  46254. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  46255. {
  46256. public:
  46257. /** Creates the default JUCE look and feel. */
  46258. OldSchoolLookAndFeel();
  46259. /** Destructor. */
  46260. virtual ~OldSchoolLookAndFeel();
  46261. /** Draws the lozenge-shaped background for a standard button. */
  46262. virtual void drawButtonBackground (Graphics& g,
  46263. Button& button,
  46264. const Colour& backgroundColour,
  46265. bool isMouseOverButton,
  46266. bool isButtonDown);
  46267. /** Draws the contents of a standard ToggleButton. */
  46268. virtual void drawToggleButton (Graphics& g,
  46269. ToggleButton& button,
  46270. bool isMouseOverButton,
  46271. bool isButtonDown);
  46272. virtual void drawTickBox (Graphics& g,
  46273. Component& component,
  46274. float x, float y, float w, float h,
  46275. bool ticked,
  46276. bool isEnabled,
  46277. bool isMouseOverButton,
  46278. bool isButtonDown);
  46279. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46280. int width, int height,
  46281. double progress, const String& textToShow);
  46282. virtual void drawScrollbarButton (Graphics& g,
  46283. ScrollBar& scrollbar,
  46284. int width, int height,
  46285. int buttonDirection,
  46286. bool isScrollbarVertical,
  46287. bool isMouseOverButton,
  46288. bool isButtonDown);
  46289. virtual void drawScrollbar (Graphics& g,
  46290. ScrollBar& scrollbar,
  46291. int x, int y,
  46292. int width, int height,
  46293. bool isScrollbarVertical,
  46294. int thumbStartPosition,
  46295. int thumbSize,
  46296. bool isMouseOver,
  46297. bool isMouseDown);
  46298. virtual ImageEffectFilter* getScrollbarEffect();
  46299. virtual void drawTextEditorOutline (Graphics& g,
  46300. int width, int height,
  46301. TextEditor& textEditor);
  46302. /** Fills the background of a popup menu component. */
  46303. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46304. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46305. bool isMouseOverBar,
  46306. MenuBarComponent& menuBar);
  46307. virtual void drawComboBox (Graphics& g, int width, int height,
  46308. bool isButtonDown,
  46309. int buttonX, int buttonY,
  46310. int buttonW, int buttonH,
  46311. ComboBox& box);
  46312. virtual const Font getComboBoxFont (ComboBox& box);
  46313. virtual void drawLinearSlider (Graphics& g,
  46314. int x, int y,
  46315. int width, int height,
  46316. float sliderPos,
  46317. float minSliderPos,
  46318. float maxSliderPos,
  46319. const Slider::SliderStyle style,
  46320. Slider& slider);
  46321. virtual int getSliderThumbRadius (Slider& slider);
  46322. virtual Button* createSliderButton (bool isIncrement);
  46323. virtual ImageEffectFilter* getSliderEffect();
  46324. virtual void drawCornerResizer (Graphics& g,
  46325. int w, int h,
  46326. bool isMouseOver,
  46327. bool isMouseDragging);
  46328. virtual Button* createDocumentWindowButton (int buttonType);
  46329. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46330. int titleBarX, int titleBarY,
  46331. int titleBarW, int titleBarH,
  46332. Button* minimiseButton,
  46333. Button* maximiseButton,
  46334. Button* closeButton,
  46335. bool positionTitleBarButtonsOnLeft);
  46336. private:
  46337. DropShadowEffect scrollbarShadow;
  46338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  46339. };
  46340. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46341. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46342. #endif
  46343. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46344. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  46345. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46346. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46347. /**
  46348. A menu bar component.
  46349. @see MenuBarModel
  46350. */
  46351. class JUCE_API MenuBarComponent : public Component,
  46352. private MenuBarModel::Listener,
  46353. private Timer
  46354. {
  46355. public:
  46356. /** Creates a menu bar.
  46357. @param model the model object to use to control this bar. You can
  46358. pass 0 into this if you like, and set the model later
  46359. using the setModel() method
  46360. */
  46361. MenuBarComponent (MenuBarModel* model);
  46362. /** Destructor. */
  46363. ~MenuBarComponent();
  46364. /** Changes the model object to use to control the bar.
  46365. This can be a null pointer, in which case the bar will be empty. Don't delete the object
  46366. that is passed-in while it's still being used by this MenuBar.
  46367. */
  46368. void setModel (MenuBarModel* newModel);
  46369. /** Returns the current menu bar model being used.
  46370. */
  46371. MenuBarModel* getModel() const noexcept;
  46372. /** Pops up one of the menu items.
  46373. This lets you manually open one of the menus - it could be triggered by a
  46374. key shortcut, for example.
  46375. */
  46376. void showMenu (int menuIndex);
  46377. /** @internal */
  46378. void paint (Graphics& g);
  46379. /** @internal */
  46380. void resized();
  46381. /** @internal */
  46382. void mouseEnter (const MouseEvent& e);
  46383. /** @internal */
  46384. void mouseExit (const MouseEvent& e);
  46385. /** @internal */
  46386. void mouseDown (const MouseEvent& e);
  46387. /** @internal */
  46388. void mouseDrag (const MouseEvent& e);
  46389. /** @internal */
  46390. void mouseUp (const MouseEvent& e);
  46391. /** @internal */
  46392. void mouseMove (const MouseEvent& e);
  46393. /** @internal */
  46394. void handleCommandMessage (int commandId);
  46395. /** @internal */
  46396. bool keyPressed (const KeyPress& key);
  46397. /** @internal */
  46398. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  46399. /** @internal */
  46400. void menuCommandInvoked (MenuBarModel* menuBarModel,
  46401. const ApplicationCommandTarget::InvocationInfo& info);
  46402. private:
  46403. MenuBarModel* model;
  46404. StringArray menuNames;
  46405. Array <int> xPositions;
  46406. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  46407. int lastMouseX, lastMouseY;
  46408. int getItemAt (int x, int y);
  46409. void setItemUnderMouse (int index);
  46410. void setOpenItem (int index);
  46411. void updateItemUnderMouse (int x, int y);
  46412. void timerCallback();
  46413. void repaintMenuItem (int index);
  46414. void menuDismissed (int topLevelIndex, int itemId);
  46415. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  46416. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  46417. };
  46418. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46419. /*** End of inlined file: juce_MenuBarComponent.h ***/
  46420. #endif
  46421. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  46422. #endif
  46423. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  46424. #endif
  46425. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  46426. #endif
  46427. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  46428. #endif
  46429. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  46430. #endif
  46431. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  46432. #endif
  46433. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46434. /*** Start of inlined file: juce_LassoComponent.h ***/
  46435. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46436. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46437. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  46438. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46439. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46440. /** Manages a list of selectable items.
  46441. Use one of these to keep a track of things that the user has highlighted, like
  46442. icons or things in a list.
  46443. The class is templated so that you can use it to hold either a set of pointers
  46444. to objects, or a set of ID numbers or handles, for cases where each item may
  46445. not always have a corresponding object.
  46446. To be informed when items are selected/deselected, register a ChangeListener with
  46447. this object.
  46448. @see SelectableObject
  46449. */
  46450. template <class SelectableItemType>
  46451. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  46452. {
  46453. public:
  46454. typedef SelectableItemType ItemType;
  46455. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  46456. /** Creates an empty set. */
  46457. SelectedItemSet()
  46458. {
  46459. }
  46460. /** Creates a set based on an array of items. */
  46461. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  46462. : selectedItems (items)
  46463. {
  46464. }
  46465. /** Creates a copy of another set. */
  46466. SelectedItemSet (const SelectedItemSet& other)
  46467. : selectedItems (other.selectedItems)
  46468. {
  46469. }
  46470. /** Creates a copy of another set. */
  46471. SelectedItemSet& operator= (const SelectedItemSet& other)
  46472. {
  46473. if (selectedItems != other.selectedItems)
  46474. {
  46475. selectedItems = other.selectedItems;
  46476. changed();
  46477. }
  46478. return *this;
  46479. }
  46480. /** Clears any other currently selected items, and selects this item.
  46481. If this item is already the only thing selected, no change notification
  46482. will be sent out.
  46483. @see addToSelection, addToSelectionBasedOnModifiers
  46484. */
  46485. void selectOnly (ParameterType item)
  46486. {
  46487. if (isSelected (item))
  46488. {
  46489. for (int i = selectedItems.size(); --i >= 0;)
  46490. {
  46491. if (selectedItems.getUnchecked(i) != item)
  46492. {
  46493. deselect (selectedItems.getUnchecked(i));
  46494. i = jmin (i, selectedItems.size());
  46495. }
  46496. }
  46497. }
  46498. else
  46499. {
  46500. deselectAll();
  46501. changed();
  46502. selectedItems.add (item);
  46503. itemSelected (item);
  46504. }
  46505. }
  46506. /** Selects an item.
  46507. If the item is already selected, no change notification will be sent out.
  46508. @see selectOnly, addToSelectionBasedOnModifiers
  46509. */
  46510. void addToSelection (ParameterType item)
  46511. {
  46512. if (! isSelected (item))
  46513. {
  46514. changed();
  46515. selectedItems.add (item);
  46516. itemSelected (item);
  46517. }
  46518. }
  46519. /** Selects or deselects an item.
  46520. This will use the modifier keys to decide whether to deselect other items
  46521. first.
  46522. So if the shift key is held down, the item will be added without deselecting
  46523. anything (same as calling addToSelection() )
  46524. If no modifiers are down, the current selection will be cleared first (same
  46525. as calling selectOnly() )
  46526. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  46527. so it'll be added to the set unless it's already there, in which case it'll be
  46528. deselected.
  46529. If the items that you're selecting can also be dragged, you may need to use the
  46530. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  46531. subtleties of this kind of usage.
  46532. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  46533. */
  46534. void addToSelectionBasedOnModifiers (ParameterType item,
  46535. const ModifierKeys& modifiers)
  46536. {
  46537. if (modifiers.isShiftDown())
  46538. {
  46539. addToSelection (item);
  46540. }
  46541. else if (modifiers.isCommandDown())
  46542. {
  46543. if (isSelected (item))
  46544. deselect (item);
  46545. else
  46546. addToSelection (item);
  46547. }
  46548. else
  46549. {
  46550. selectOnly (item);
  46551. }
  46552. }
  46553. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  46554. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  46555. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  46556. makes it easy to handle multiple-selection of sets of objects that can also
  46557. be dragged.
  46558. For example, if you have several items already selected, and you click on
  46559. one of them (without dragging), then you'd expect this to deselect the other, and
  46560. just select the item you clicked on. But if you had clicked on this item and
  46561. dragged it, you'd have expected them all to stay selected.
  46562. When you call this method, you'll need to store the boolean result, because the
  46563. addToSelectionOnMouseUp() method will need to be know this value.
  46564. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  46565. */
  46566. bool addToSelectionOnMouseDown (ParameterType item,
  46567. const ModifierKeys& modifiers)
  46568. {
  46569. if (isSelected (item))
  46570. {
  46571. return ! modifiers.isPopupMenu();
  46572. }
  46573. else
  46574. {
  46575. addToSelectionBasedOnModifiers (item, modifiers);
  46576. return false;
  46577. }
  46578. }
  46579. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  46580. Call this during a mouseUp callback, when you have previously called the
  46581. addToSelectionOnMouseDown() method during your mouseDown event.
  46582. See addToSelectionOnMouseDown() for more info
  46583. @param item the item to select (or deselect)
  46584. @param modifiers the modifiers from the mouse-up event
  46585. @param wasItemDragged true if your item was dragged during the mouse click
  46586. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  46587. back from the addToSelectionOnMouseDown() call that you
  46588. should have made during the matching mouseDown event
  46589. */
  46590. void addToSelectionOnMouseUp (ParameterType item,
  46591. const ModifierKeys& modifiers,
  46592. const bool wasItemDragged,
  46593. const bool resultOfMouseDownSelectMethod)
  46594. {
  46595. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  46596. addToSelectionBasedOnModifiers (item, modifiers);
  46597. }
  46598. /** Deselects an item. */
  46599. void deselect (ParameterType item)
  46600. {
  46601. const int i = selectedItems.indexOf (item);
  46602. if (i >= 0)
  46603. {
  46604. changed();
  46605. itemDeselected (selectedItems.remove (i));
  46606. }
  46607. }
  46608. /** Deselects all items. */
  46609. void deselectAll()
  46610. {
  46611. if (selectedItems.size() > 0)
  46612. {
  46613. changed();
  46614. for (int i = selectedItems.size(); --i >= 0;)
  46615. {
  46616. itemDeselected (selectedItems.remove (i));
  46617. i = jmin (i, selectedItems.size());
  46618. }
  46619. }
  46620. }
  46621. /** Returns the number of currently selected items.
  46622. @see getSelectedItem
  46623. */
  46624. int getNumSelected() const noexcept
  46625. {
  46626. return selectedItems.size();
  46627. }
  46628. /** Returns one of the currently selected items.
  46629. Returns 0 if the index is out-of-range.
  46630. @see getNumSelected
  46631. */
  46632. SelectableItemType getSelectedItem (const int index) const noexcept
  46633. {
  46634. return selectedItems [index];
  46635. }
  46636. /** True if this item is currently selected. */
  46637. bool isSelected (ParameterType item) const noexcept
  46638. {
  46639. return selectedItems.contains (item);
  46640. }
  46641. const Array <SelectableItemType>& getItemArray() const noexcept { return selectedItems; }
  46642. /** Can be overridden to do special handling when an item is selected.
  46643. For example, if the item is an object, you might want to call it and tell
  46644. it that it's being selected.
  46645. */
  46646. virtual void itemSelected (SelectableItemType item) { (void) item; }
  46647. /** Can be overridden to do special handling when an item is deselected.
  46648. For example, if the item is an object, you might want to call it and tell
  46649. it that it's being deselected.
  46650. */
  46651. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  46652. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  46653. */
  46654. void changed (const bool synchronous = false)
  46655. {
  46656. if (synchronous)
  46657. sendSynchronousChangeMessage();
  46658. else
  46659. sendChangeMessage();
  46660. }
  46661. private:
  46662. Array <SelectableItemType> selectedItems;
  46663. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  46664. };
  46665. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46666. /*** End of inlined file: juce_SelectedItemSet.h ***/
  46667. /**
  46668. A class used by the LassoComponent to manage the things that it selects.
  46669. This allows the LassoComponent to find out which items are within the lasso,
  46670. and to change the list of selected items.
  46671. @see LassoComponent, SelectedItemSet
  46672. */
  46673. template <class SelectableItemType>
  46674. class LassoSource
  46675. {
  46676. public:
  46677. /** Destructor. */
  46678. virtual ~LassoSource() {}
  46679. /** Returns the set of items that lie within a given lassoable region.
  46680. Your implementation of this method must find all the relevent items that lie
  46681. within the given rectangle. and add them to the itemsFound array.
  46682. The co-ordinates are relative to the top-left of the lasso component's parent
  46683. component. (i.e. they are the same as the size and position of the lasso
  46684. component itself).
  46685. */
  46686. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  46687. const Rectangle<int>& area) = 0;
  46688. /** Returns the SelectedItemSet that the lasso should update.
  46689. This set will be continuously updated by the LassoComponent as it gets
  46690. dragged around, so make sure that you've got a ChangeListener attached to
  46691. the set so that your UI objects will know when the selection changes and
  46692. be able to update themselves appropriately.
  46693. */
  46694. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  46695. };
  46696. /**
  46697. A component that acts as a rectangular selection region, which you drag with
  46698. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  46699. To use one of these:
  46700. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  46701. component, and call its beginLasso() method, giving it a
  46702. suitable LassoSource object that it can use to find out which items are in
  46703. the active area.
  46704. - Each time your parent component gets a mouseDrag event, call dragLasso()
  46705. to update the lasso's position - it will use its LassoSource to calculate and
  46706. update the current selection.
  46707. - After the drag has finished and you get a mouseUp callback, you should call
  46708. endLasso() to clean up. This will make the lasso component invisible, and you
  46709. can remove it from the parent component, or delete it.
  46710. The class takes into account the modifier keys that are being held down while
  46711. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  46712. be added to the original selection; if ctrl or command is pressed, they will be
  46713. xor'ed with any previously selected items.
  46714. @see LassoSource, SelectedItemSet
  46715. */
  46716. template <class SelectableItemType>
  46717. class LassoComponent : public Component
  46718. {
  46719. public:
  46720. /** Creates a Lasso component.
  46721. The fill colour is used to fill the lasso'ed rectangle, and the outline
  46722. colour is used to draw a line around its edge.
  46723. */
  46724. explicit LassoComponent (const int outlineThickness_ = 1)
  46725. : source (nullptr),
  46726. outlineThickness (outlineThickness_)
  46727. {
  46728. }
  46729. /** Destructor. */
  46730. ~LassoComponent()
  46731. {
  46732. }
  46733. /** Call this in your mouseDown event, to initialise a drag.
  46734. Pass in a suitable LassoSource object which the lasso will use to find
  46735. the items and change the selection.
  46736. After using this method to initialise the lasso, repeatedly call dragLasso()
  46737. in your component's mouseDrag callback.
  46738. @see dragLasso, endLasso, LassoSource
  46739. */
  46740. void beginLasso (const MouseEvent& e,
  46741. LassoSource <SelectableItemType>* const lassoSource)
  46742. {
  46743. jassert (source == nullptr); // this suggests that you didn't call endLasso() after the last drag...
  46744. jassert (lassoSource != nullptr); // the source can't be null!
  46745. jassert (getParentComponent() != nullptr); // you need to add this to a parent component for it to work!
  46746. source = lassoSource;
  46747. if (lassoSource != nullptr)
  46748. originalSelection = lassoSource->getLassoSelection().getItemArray();
  46749. setSize (0, 0);
  46750. dragStartPos = e.getMouseDownPosition();
  46751. }
  46752. /** Call this in your mouseDrag event, to update the lasso's position.
  46753. This must be repeatedly calling when the mouse is dragged, after you've
  46754. first initialised the lasso with beginLasso().
  46755. This method takes into account the modifier keys that are being held down, so
  46756. if shift is pressed, then the lassoed items will be added to any that were
  46757. previously selected; if ctrl or command is pressed, then they will be xor'ed
  46758. with previously selected items.
  46759. @see beginLasso, endLasso
  46760. */
  46761. void dragLasso (const MouseEvent& e)
  46762. {
  46763. if (source != nullptr)
  46764. {
  46765. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  46766. setVisible (true);
  46767. Array <SelectableItemType> itemsInLasso;
  46768. source->findLassoItemsInArea (itemsInLasso, getBounds());
  46769. if (e.mods.isShiftDown())
  46770. {
  46771. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  46772. itemsInLasso.addArray (originalSelection);
  46773. }
  46774. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  46775. {
  46776. Array <SelectableItemType> originalMinusNew (originalSelection);
  46777. originalMinusNew.removeValuesIn (itemsInLasso);
  46778. itemsInLasso.removeValuesIn (originalSelection);
  46779. itemsInLasso.addArray (originalMinusNew);
  46780. }
  46781. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  46782. }
  46783. }
  46784. /** Call this in your mouseUp event, after the lasso has been dragged.
  46785. @see beginLasso, dragLasso
  46786. */
  46787. void endLasso()
  46788. {
  46789. source = nullptr;
  46790. originalSelection.clear();
  46791. setVisible (false);
  46792. }
  46793. /** A set of colour IDs to use to change the colour of various aspects of the label.
  46794. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46795. methods.
  46796. Note that you can also use the constants from TextEditor::ColourIds to change the
  46797. colour of the text editor that is opened when a label is editable.
  46798. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46799. */
  46800. enum ColourIds
  46801. {
  46802. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  46803. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  46804. };
  46805. /** @internal */
  46806. void paint (Graphics& g)
  46807. {
  46808. g.fillAll (findColour (lassoFillColourId));
  46809. g.setColour (findColour (lassoOutlineColourId));
  46810. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  46811. // this suggests that you've left a lasso comp lying around after the
  46812. // mouse drag has finished.. Be careful to call endLasso() when you get a
  46813. // mouse-up event.
  46814. jassert (isMouseButtonDownAnywhere());
  46815. }
  46816. /** @internal */
  46817. bool hitTest (int, int) { return false; }
  46818. private:
  46819. Array <SelectableItemType> originalSelection;
  46820. LassoSource <SelectableItemType>* source;
  46821. int outlineThickness;
  46822. Point<int> dragStartPos;
  46823. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  46824. };
  46825. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46826. /*** End of inlined file: juce_LassoComponent.h ***/
  46827. #endif
  46828. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  46829. #endif
  46830. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  46831. #endif
  46832. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46833. /*** Start of inlined file: juce_MouseInputSource.h ***/
  46834. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46835. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46836. class MouseInputSourceInternal;
  46837. /**
  46838. Represents a linear source of mouse events from a mouse device or individual finger
  46839. in a multi-touch environment.
  46840. Each MouseEvent object contains a reference to the MouseInputSource that generated
  46841. it. In an environment with a single mouse for input, all events will come from the
  46842. same source, but in a multi-touch system, there may be multiple MouseInputSource
  46843. obects active, each representing a stream of events coming from a particular finger.
  46844. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  46845. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  46846. the only events that can happen between a mouseDown and its corresponding mouseUp are
  46847. mouseDrags, etc.
  46848. When there are multiple touches arriving from multiple MouseInputSources, their
  46849. event streams may arrive in an interleaved order, so you should use the getIndex()
  46850. method to find out which finger each event came from.
  46851. @see MouseEvent
  46852. */
  46853. class JUCE_API MouseInputSource
  46854. {
  46855. public:
  46856. /** Creates a MouseInputSource.
  46857. You should never actually create a MouseInputSource in your own code - the
  46858. library takes care of managing these objects.
  46859. */
  46860. MouseInputSource (int index, bool isMouseDevice);
  46861. /** Destructor. */
  46862. ~MouseInputSource();
  46863. /** Returns true if this object represents a normal desk-based mouse device. */
  46864. bool isMouse() const;
  46865. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  46866. bool isTouch() const;
  46867. /** Returns true if this source has an on-screen pointer that can hover over
  46868. items without clicking them.
  46869. */
  46870. bool canHover() const;
  46871. /** Returns true if this source may have a scroll wheel. */
  46872. bool hasMouseWheel() const;
  46873. /** Returns this source's index in the global list of possible sources.
  46874. If the system only has a single mouse, there will only be a single MouseInputSource
  46875. with an index of 0.
  46876. If the system supports multi-touch input, then the index will represent a finger
  46877. number, starting from 0. When the first touch event begins, it will have finger
  46878. number 0, and then if a second touch happens while the first is still down, it
  46879. will have index 1, etc.
  46880. */
  46881. int getIndex() const;
  46882. /** Returns true if this device is currently being pressed. */
  46883. bool isDragging() const;
  46884. /** Returns the last-known screen position of this source. */
  46885. const Point<int> getScreenPosition() const;
  46886. /** Returns a set of modifiers that indicate which buttons are currently
  46887. held down on this device.
  46888. */
  46889. const ModifierKeys getCurrentModifiers() const;
  46890. /** Returns the component that was last known to be under this pointer. */
  46891. Component* getComponentUnderMouse() const;
  46892. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  46893. This is asynchronous - the event will occur on the message thread.
  46894. */
  46895. void triggerFakeMove() const;
  46896. /** Returns the number of clicks that should be counted as belonging to the
  46897. current mouse event.
  46898. So the mouse is currently down and it's the second click of a double-click, this
  46899. will return 2.
  46900. */
  46901. int getNumberOfMultipleClicks() const noexcept;
  46902. /** Returns the time at which the last mouse-down occurred. */
  46903. const Time getLastMouseDownTime() const noexcept;
  46904. /** Returns the screen position at which the last mouse-down occurred. */
  46905. const Point<int> getLastMouseDownPosition() const noexcept;
  46906. /** Returns true if this mouse is currently down, and if it has been dragged more
  46907. than a couple of pixels from the place it was pressed.
  46908. */
  46909. bool hasMouseMovedSignificantlySincePressed() const noexcept;
  46910. /** Returns true if this input source uses a visible mouse cursor. */
  46911. bool hasMouseCursor() const noexcept;
  46912. /** Changes the mouse cursor, (if there is one). */
  46913. void showMouseCursor (const MouseCursor& cursor);
  46914. /** Hides the mouse cursor (if there is one). */
  46915. void hideCursor();
  46916. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  46917. void revealCursor();
  46918. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  46919. void forceMouseCursorUpdate();
  46920. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  46921. bool canDoUnboundedMovement() const noexcept;
  46922. /** Allows the mouse to move beyond the edges of the screen.
  46923. Calling this method when the mouse button is currently pressed will remove the cursor
  46924. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  46925. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  46926. can be used for things like custom slider controls or dragging objects around, where
  46927. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  46928. The unbounded mode is automatically turned off when the mouse button is released, or
  46929. it can be turned off explicitly by calling this method again.
  46930. @param isEnabled whether to turn this mode on or off
  46931. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  46932. hidden; if true, it will only be hidden when it
  46933. is moved beyond the edge of the screen
  46934. */
  46935. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  46936. /** @internal */
  46937. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  46938. /** @internal */
  46939. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  46940. private:
  46941. friend class Desktop;
  46942. friend class ComponentPeer;
  46943. friend class MouseInputSourceInternal;
  46944. ScopedPointer<MouseInputSourceInternal> pimpl;
  46945. static const Point<int> getCurrentMousePosition();
  46946. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  46947. };
  46948. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46949. /*** End of inlined file: juce_MouseInputSource.h ***/
  46950. #endif
  46951. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  46952. #endif
  46953. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  46954. #endif
  46955. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  46956. #endif
  46957. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  46958. #endif
  46959. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  46960. #endif
  46961. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46962. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  46963. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46964. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46965. /**
  46966. A parallelogram defined by three RelativePoint positions.
  46967. @see RelativePoint, RelativeCoordinate
  46968. */
  46969. class JUCE_API RelativeParallelogram
  46970. {
  46971. public:
  46972. RelativeParallelogram();
  46973. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  46974. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  46975. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  46976. ~RelativeParallelogram();
  46977. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  46978. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  46979. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  46980. void getPath (Path& path, Expression::Scope* scope) const;
  46981. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  46982. bool isDynamic() const;
  46983. bool operator== (const RelativeParallelogram& other) const noexcept;
  46984. bool operator!= (const RelativeParallelogram& other) const noexcept;
  46985. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) noexcept;
  46986. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) noexcept;
  46987. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) noexcept;
  46988. RelativePoint topLeft, topRight, bottomLeft;
  46989. };
  46990. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46991. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  46992. #endif
  46993. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  46994. #endif
  46995. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46996. /*** Start of inlined file: juce_RelativePointPath.h ***/
  46997. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46998. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46999. class DrawablePath;
  47000. /**
  47001. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  47002. One of these paths can be converted into a Path object for drawing and manipulation, but
  47003. unlike a Path, its points can be dynamic instead of just fixed.
  47004. @see RelativePoint, RelativeCoordinate
  47005. */
  47006. class JUCE_API RelativePointPath
  47007. {
  47008. public:
  47009. RelativePointPath();
  47010. RelativePointPath (const RelativePointPath& other);
  47011. explicit RelativePointPath (const Path& path);
  47012. ~RelativePointPath();
  47013. bool operator== (const RelativePointPath& other) const noexcept;
  47014. bool operator!= (const RelativePointPath& other) const noexcept;
  47015. /** Resolves this points in this path and adds them to a normal Path object. */
  47016. void createPath (Path& path, Expression::Scope* scope) const;
  47017. /** Returns true if the path contains any non-fixed points. */
  47018. bool containsAnyDynamicPoints() const;
  47019. /** Quickly swaps the contents of this path with another. */
  47020. void swapWith (RelativePointPath& other) noexcept;
  47021. /** The types of element that may be contained in this path.
  47022. @see RelativePointPath::ElementBase
  47023. */
  47024. enum ElementType
  47025. {
  47026. nullElement,
  47027. startSubPathElement,
  47028. closeSubPathElement,
  47029. lineToElement,
  47030. quadraticToElement,
  47031. cubicToElement
  47032. };
  47033. /** Base class for the elements that make up a RelativePointPath.
  47034. */
  47035. class JUCE_API ElementBase
  47036. {
  47037. public:
  47038. ElementBase (ElementType type);
  47039. virtual ~ElementBase() {}
  47040. virtual const ValueTree createTree() const = 0;
  47041. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  47042. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  47043. virtual ElementBase* clone() const = 0;
  47044. bool isDynamic();
  47045. const ElementType type;
  47046. private:
  47047. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  47048. };
  47049. class JUCE_API StartSubPath : public ElementBase
  47050. {
  47051. public:
  47052. StartSubPath (const RelativePoint& pos);
  47053. const ValueTree createTree() const;
  47054. void addToPath (Path& path, Expression::Scope*) const;
  47055. RelativePoint* getControlPoints (int& numPoints);
  47056. ElementBase* clone() const;
  47057. RelativePoint startPos;
  47058. private:
  47059. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  47060. };
  47061. class JUCE_API CloseSubPath : public ElementBase
  47062. {
  47063. public:
  47064. CloseSubPath();
  47065. const ValueTree createTree() const;
  47066. void addToPath (Path& path, Expression::Scope*) const;
  47067. RelativePoint* getControlPoints (int& numPoints);
  47068. ElementBase* clone() const;
  47069. private:
  47070. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  47071. };
  47072. class JUCE_API LineTo : public ElementBase
  47073. {
  47074. public:
  47075. LineTo (const RelativePoint& endPoint);
  47076. const ValueTree createTree() const;
  47077. void addToPath (Path& path, Expression::Scope*) const;
  47078. RelativePoint* getControlPoints (int& numPoints);
  47079. ElementBase* clone() const;
  47080. RelativePoint endPoint;
  47081. private:
  47082. JUCE_DECLARE_NON_COPYABLE (LineTo);
  47083. };
  47084. class JUCE_API QuadraticTo : public ElementBase
  47085. {
  47086. public:
  47087. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  47088. const ValueTree createTree() const;
  47089. void addToPath (Path& path, Expression::Scope*) const;
  47090. RelativePoint* getControlPoints (int& numPoints);
  47091. ElementBase* clone() const;
  47092. RelativePoint controlPoints[2];
  47093. private:
  47094. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  47095. };
  47096. class JUCE_API CubicTo : public ElementBase
  47097. {
  47098. public:
  47099. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  47100. const ValueTree createTree() const;
  47101. void addToPath (Path& path, Expression::Scope*) const;
  47102. RelativePoint* getControlPoints (int& numPoints);
  47103. ElementBase* clone() const;
  47104. RelativePoint controlPoints[3];
  47105. private:
  47106. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  47107. };
  47108. void addElement (ElementBase* newElement);
  47109. OwnedArray <ElementBase> elements;
  47110. bool usesNonZeroWinding;
  47111. private:
  47112. class Positioner;
  47113. friend class Positioner;
  47114. bool containsDynamicPoints;
  47115. void applyTo (DrawablePath& path) const;
  47116. RelativePointPath& operator= (const RelativePointPath&);
  47117. JUCE_LEAK_DETECTOR (RelativePointPath);
  47118. };
  47119. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47120. /*** End of inlined file: juce_RelativePointPath.h ***/
  47121. #endif
  47122. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47123. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  47124. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47125. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47126. class Component;
  47127. /**
  47128. An rectangle stored as a set of RelativeCoordinate values.
  47129. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  47130. @see RelativeCoordinate, RelativePoint
  47131. */
  47132. class JUCE_API RelativeRectangle
  47133. {
  47134. public:
  47135. /** Creates a zero-size rectangle at the origin. */
  47136. RelativeRectangle();
  47137. /** Creates an absolute rectangle, relative to the origin. */
  47138. explicit RelativeRectangle (const Rectangle<float>& rect);
  47139. /** Creates a rectangle from four coordinates. */
  47140. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  47141. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  47142. /** Creates a rectangle from a stringified representation.
  47143. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  47144. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  47145. RelativeCoordinate class.
  47146. @see toString
  47147. */
  47148. explicit RelativeRectangle (const String& stringVersion);
  47149. bool operator== (const RelativeRectangle& other) const noexcept;
  47150. bool operator!= (const RelativeRectangle& other) const noexcept;
  47151. /** Calculates the absolute position of this rectangle.
  47152. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  47153. be needed to calculate the result.
  47154. */
  47155. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  47156. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  47157. Calling this will leave any anchor points unchanged, but will set any absolute
  47158. or relative positions to whatever values are necessary to make the resultant position
  47159. match the position that is provided.
  47160. */
  47161. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  47162. /** Returns true if this rectangle depends on any external symbols for its position.
  47163. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  47164. */
  47165. bool isDynamic() const;
  47166. /** Returns a string which represents this point.
  47167. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  47168. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  47169. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  47170. */
  47171. const String toString() const;
  47172. /** Renames a symbol if it is used by any of the coordinates.
  47173. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  47174. */
  47175. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  47176. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  47177. keep it positioned with this rectangle.
  47178. */
  47179. void applyToComponent (Component& component) const;
  47180. // The actual rectangle coords...
  47181. RelativeCoordinate left, right, top, bottom;
  47182. };
  47183. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47184. /*** End of inlined file: juce_RelativeRectangle.h ***/
  47185. #endif
  47186. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47187. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  47188. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47189. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47190. /**
  47191. A PropertyComponent that contains an on/off toggle button.
  47192. This type of property component can be used if you have a boolean value to
  47193. toggle on/off.
  47194. @see PropertyComponent
  47195. */
  47196. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  47197. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47198. {
  47199. protected:
  47200. /** Creates a button component.
  47201. If you use this constructor, you must override the getState() and setState()
  47202. methods.
  47203. @param propertyName the property name to be passed to the PropertyComponent
  47204. @param buttonTextWhenTrue the text shown in the button when the value is true
  47205. @param buttonTextWhenFalse the text shown in the button when the value is false
  47206. */
  47207. BooleanPropertyComponent (const String& propertyName,
  47208. const String& buttonTextWhenTrue,
  47209. const String& buttonTextWhenFalse);
  47210. public:
  47211. /** Creates a button component.
  47212. @param valueToControl a Value object that this property should refer to.
  47213. @param propertyName the property name to be passed to the PropertyComponent
  47214. @param buttonText the text shown in the ToggleButton component
  47215. */
  47216. BooleanPropertyComponent (const Value& valueToControl,
  47217. const String& propertyName,
  47218. const String& buttonText);
  47219. /** Destructor. */
  47220. ~BooleanPropertyComponent();
  47221. /** Called to change the state of the boolean value. */
  47222. virtual void setState (bool newState);
  47223. /** Must return the current value of the property. */
  47224. virtual bool getState() const;
  47225. /** @internal */
  47226. void paint (Graphics& g);
  47227. /** @internal */
  47228. void refresh();
  47229. /** @internal */
  47230. void buttonClicked (Button*);
  47231. private:
  47232. ToggleButton button;
  47233. String onText, offText;
  47234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  47235. };
  47236. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47237. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  47238. #endif
  47239. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47240. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  47241. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47242. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47243. /**
  47244. A PropertyComponent that contains a button.
  47245. This type of property component can be used if you need a button to trigger some
  47246. kind of action.
  47247. @see PropertyComponent
  47248. */
  47249. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  47250. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47251. {
  47252. public:
  47253. /** Creates a button component.
  47254. @param propertyName the property name to be passed to the PropertyComponent
  47255. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  47256. */
  47257. ButtonPropertyComponent (const String& propertyName,
  47258. bool triggerOnMouseDown);
  47259. /** Destructor. */
  47260. ~ButtonPropertyComponent();
  47261. /** Called when the user clicks the button.
  47262. */
  47263. virtual void buttonClicked() = 0;
  47264. /** Returns the string that should be displayed in the button.
  47265. If you need to change this string, call refresh() to update the component.
  47266. */
  47267. virtual const String getButtonText() const = 0;
  47268. /** @internal */
  47269. void refresh();
  47270. /** @internal */
  47271. void buttonClicked (Button*);
  47272. private:
  47273. TextButton button;
  47274. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  47275. };
  47276. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47277. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  47278. #endif
  47279. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47280. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  47281. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47282. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47283. /**
  47284. A PropertyComponent that shows its value as a combo box.
  47285. This type of property component contains a list of options and has a
  47286. combo box to choose one.
  47287. Your subclass's constructor must add some strings to the choices StringArray
  47288. and these are shown in the list.
  47289. The getIndex() method will be called to find out which option is the currently
  47290. selected one. If you call refresh() it will call getIndex() to check whether
  47291. the value has changed, and will update the combo box if needed.
  47292. If the user selects a different item from the list, setIndex() will be
  47293. called to let your class process this.
  47294. @see PropertyComponent, PropertyPanel
  47295. */
  47296. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  47297. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47298. {
  47299. protected:
  47300. /** Creates the component.
  47301. Your subclass's constructor must add a list of options to the choices
  47302. member variable.
  47303. */
  47304. ChoicePropertyComponent (const String& propertyName);
  47305. public:
  47306. /** Creates the component.
  47307. @param valueToControl the value that the combo box will read and control
  47308. @param propertyName the name of the property
  47309. @param choices the list of possible values that the drop-down list will contain
  47310. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  47311. These are the values that will be read and written to the
  47312. valueToControl value. This array must contain the same number of items
  47313. as the choices array
  47314. */
  47315. ChoicePropertyComponent (const Value& valueToControl,
  47316. const String& propertyName,
  47317. const StringArray& choices,
  47318. const Array <var>& correspondingValues);
  47319. /** Destructor. */
  47320. ~ChoicePropertyComponent();
  47321. /** Called when the user selects an item from the combo box.
  47322. Your subclass must use this callback to update the value that this component
  47323. represents. The index is the index of the chosen item in the choices
  47324. StringArray.
  47325. */
  47326. virtual void setIndex (int newIndex);
  47327. /** Returns the index of the item that should currently be shown.
  47328. This is the index of the item in the choices StringArray that will be
  47329. shown.
  47330. */
  47331. virtual int getIndex() const;
  47332. /** Returns the list of options. */
  47333. const StringArray& getChoices() const;
  47334. /** @internal */
  47335. void refresh();
  47336. /** @internal */
  47337. void comboBoxChanged (ComboBox*);
  47338. protected:
  47339. /** The list of options that will be shown in the combo box.
  47340. Your subclass must populate this array in its constructor. If any empty
  47341. strings are added, these will be replaced with horizontal separators (see
  47342. ComboBox::addSeparator() for more info).
  47343. */
  47344. StringArray choices;
  47345. private:
  47346. ComboBox comboBox;
  47347. bool isCustomClass;
  47348. class RemapperValueSource;
  47349. void createComboBox();
  47350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  47351. };
  47352. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47353. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  47354. #endif
  47355. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  47356. #endif
  47357. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  47358. #endif
  47359. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47360. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  47361. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47362. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47363. /**
  47364. A PropertyComponent that shows its value as a slider.
  47365. @see PropertyComponent, Slider
  47366. */
  47367. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  47368. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  47369. {
  47370. protected:
  47371. /** Creates the property component.
  47372. The ranges, interval and skew factor are passed to the Slider component.
  47373. If you need to customise the slider in other ways, your constructor can
  47374. access the slider member variable and change it directly.
  47375. */
  47376. SliderPropertyComponent (const String& propertyName,
  47377. double rangeMin,
  47378. double rangeMax,
  47379. double interval,
  47380. double skewFactor = 1.0);
  47381. public:
  47382. /** Creates the property component.
  47383. The ranges, interval and skew factor are passed to the Slider component.
  47384. If you need to customise the slider in other ways, your constructor can
  47385. access the slider member variable and change it directly.
  47386. */
  47387. SliderPropertyComponent (const Value& valueToControl,
  47388. const String& propertyName,
  47389. double rangeMin,
  47390. double rangeMax,
  47391. double interval,
  47392. double skewFactor = 1.0);
  47393. /** Destructor. */
  47394. ~SliderPropertyComponent();
  47395. /** Called when the user moves the slider to change its value.
  47396. Your subclass must use this method to update whatever item this property
  47397. represents.
  47398. */
  47399. virtual void setValue (double newValue);
  47400. /** Returns the value that the slider should show. */
  47401. virtual double getValue() const;
  47402. /** @internal */
  47403. void refresh();
  47404. /** @internal */
  47405. void sliderValueChanged (Slider*);
  47406. protected:
  47407. /** The slider component being used in this component.
  47408. Your subclass has access to this in case it needs to customise it in some way.
  47409. */
  47410. Slider slider;
  47411. private:
  47412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  47413. };
  47414. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47415. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  47416. #endif
  47417. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47418. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  47419. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47420. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47421. /**
  47422. A PropertyComponent that shows its value as editable text.
  47423. @see PropertyComponent
  47424. */
  47425. class JUCE_API TextPropertyComponent : public PropertyComponent
  47426. {
  47427. protected:
  47428. /** Creates a text property component.
  47429. The maxNumChars is used to set the length of string allowable, and isMultiLine
  47430. sets whether the text editor allows carriage returns.
  47431. @see TextEditor
  47432. */
  47433. TextPropertyComponent (const String& propertyName,
  47434. int maxNumChars,
  47435. bool isMultiLine);
  47436. public:
  47437. /** Creates a text property component.
  47438. The maxNumChars is used to set the length of string allowable, and isMultiLine
  47439. sets whether the text editor allows carriage returns.
  47440. @see TextEditor
  47441. */
  47442. TextPropertyComponent (const Value& valueToControl,
  47443. const String& propertyName,
  47444. int maxNumChars,
  47445. bool isMultiLine);
  47446. /** Destructor. */
  47447. ~TextPropertyComponent();
  47448. /** Called when the user edits the text.
  47449. Your subclass must use this callback to change the value of whatever item
  47450. this property component represents.
  47451. */
  47452. virtual void setText (const String& newText);
  47453. /** Returns the text that should be shown in the text editor.
  47454. */
  47455. virtual const String getText() const;
  47456. /** @internal */
  47457. void refresh();
  47458. /** @internal */
  47459. void textWasEdited();
  47460. private:
  47461. ScopedPointer<Label> textEditor;
  47462. void createEditor (int maxNumChars, bool isMultiLine);
  47463. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  47464. };
  47465. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47466. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  47467. #endif
  47468. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47469. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  47470. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47471. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47472. #if JUCE_WINDOWS || DOXYGEN
  47473. /**
  47474. A Windows-specific class that can create and embed an ActiveX control inside
  47475. itself.
  47476. To use it, create one of these, put it in place and make sure it's visible in a
  47477. window, then use createControl() to instantiate an ActiveX control. The control
  47478. will then be moved and resized to follow the movements of this component.
  47479. Of course, since the control is a heavyweight window, it'll obliterate any
  47480. juce components that may overlap this component, but that's life.
  47481. */
  47482. class JUCE_API ActiveXControlComponent : public Component
  47483. {
  47484. public:
  47485. /** Create an initially-empty container. */
  47486. ActiveXControlComponent();
  47487. /** Destructor. */
  47488. ~ActiveXControlComponent();
  47489. /** Tries to create an ActiveX control and embed it in this peer.
  47490. The peer controlIID is a pointer to an IID structure - it's treated
  47491. as a void* because when including the Juce headers, you might not always
  47492. have included windows.h first, in which case IID wouldn't be defined.
  47493. e.g. @code
  47494. const IID myIID = __uuidof (QTControl);
  47495. myControlComp->createControl (&myIID);
  47496. @endcode
  47497. */
  47498. bool createControl (const void* controlIID);
  47499. /** Deletes the ActiveX control, if one has been created.
  47500. */
  47501. void deleteControl();
  47502. /** Returns true if a control is currently in use. */
  47503. bool isControlOpen() const noexcept { return control != nullptr; }
  47504. /** Does a QueryInterface call on the embedded control object.
  47505. This allows you to cast the control to whatever type of COM object you need.
  47506. The iid parameter is a pointer to an IID structure - it's treated
  47507. as a void* because when including the Juce headers, you might not always
  47508. have included windows.h first, in which case IID wouldn't be defined, but
  47509. you should just pass a pointer to an IID.
  47510. e.g. @code
  47511. const IID iid = __uuidof (IOleWindow);
  47512. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  47513. if (oleWindow != nullptr)
  47514. {
  47515. HWND hwnd;
  47516. oleWindow->GetWindow (&hwnd);
  47517. ...
  47518. oleWindow->Release();
  47519. }
  47520. @endcode
  47521. */
  47522. void* queryInterface (const void* iid) const;
  47523. /** Set this to false to stop mouse events being allowed through to the control.
  47524. */
  47525. void setMouseEventsAllowed (bool eventsCanReachControl);
  47526. /** Returns true if mouse events are allowed to get through to the control.
  47527. */
  47528. bool areMouseEventsAllowed() const noexcept { return mouseEventsAllowed; }
  47529. /** @internal */
  47530. void paint (Graphics& g);
  47531. /** @internal */
  47532. void* originalWndProc;
  47533. private:
  47534. class Pimpl;
  47535. friend class Pimpl;
  47536. friend class ScopedPointer <Pimpl>;
  47537. ScopedPointer <Pimpl> control;
  47538. bool mouseEventsAllowed;
  47539. void setControlBounds (const Rectangle<int>& bounds) const;
  47540. void setControlVisible (bool b) const;
  47541. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  47542. };
  47543. #endif
  47544. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47545. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  47546. #endif
  47547. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47548. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  47549. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47550. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47551. /**
  47552. A component containing controls to let the user change the audio settings of
  47553. an AudioDeviceManager object.
  47554. Very easy to use - just create one of these and show it to the user.
  47555. @see AudioDeviceManager
  47556. */
  47557. class JUCE_API AudioDeviceSelectorComponent : public Component,
  47558. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47559. public ButtonListener,
  47560. public ChangeListener
  47561. {
  47562. public:
  47563. /** Creates the component.
  47564. If your app needs only output channels, you might ask for a maximum of 0 input
  47565. channels, and the component won't display any options for choosing the input
  47566. channels. And likewise if you're doing an input-only app.
  47567. @param deviceManager the device manager that this component should control
  47568. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  47569. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  47570. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  47571. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  47572. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  47573. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  47574. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  47575. treated as a set of separate mono channels.
  47576. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  47577. are shown, with an "advanced" button that shows the rest of them
  47578. */
  47579. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  47580. const int minAudioInputChannels,
  47581. const int maxAudioInputChannels,
  47582. const int minAudioOutputChannels,
  47583. const int maxAudioOutputChannels,
  47584. const bool showMidiInputOptions,
  47585. const bool showMidiOutputSelector,
  47586. const bool showChannelsAsStereoPairs,
  47587. const bool hideAdvancedOptionsWithButton);
  47588. /** Destructor */
  47589. ~AudioDeviceSelectorComponent();
  47590. /** @internal */
  47591. void resized();
  47592. /** @internal */
  47593. void comboBoxChanged (ComboBox*);
  47594. /** @internal */
  47595. void buttonClicked (Button*);
  47596. /** @internal */
  47597. void changeListenerCallback (ChangeBroadcaster*);
  47598. /** @internal */
  47599. void childBoundsChanged (Component*);
  47600. private:
  47601. AudioDeviceManager& deviceManager;
  47602. ScopedPointer<ComboBox> deviceTypeDropDown;
  47603. ScopedPointer<Label> deviceTypeDropDownLabel;
  47604. ScopedPointer<Component> audioDeviceSettingsComp;
  47605. String audioDeviceSettingsCompType;
  47606. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  47607. const bool showChannelsAsStereoPairs;
  47608. const bool hideAdvancedOptionsWithButton;
  47609. class MidiInputSelectorComponentListBox;
  47610. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  47611. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  47612. ScopedPointer<ComboBox> midiOutputSelector;
  47613. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  47614. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  47615. };
  47616. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47617. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  47618. #endif
  47619. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47620. /*** Start of inlined file: juce_BubbleComponent.h ***/
  47621. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47622. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47623. /**
  47624. A component for showing a message or other graphics inside a speech-bubble-shaped
  47625. outline, pointing at a location on the screen.
  47626. This is a base class that just draws and positions the bubble shape, but leaves
  47627. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  47628. that draws a text message.
  47629. To use it, create your subclass, then either add it to a parent component or
  47630. put it on the desktop with addToDesktop (0), use setPosition() to
  47631. resize and position it, then make it visible.
  47632. @see BubbleMessageComponent
  47633. */
  47634. class JUCE_API BubbleComponent : public Component
  47635. {
  47636. protected:
  47637. /** Creates a BubbleComponent.
  47638. Your subclass will need to implement the getContentSize() and paintContent()
  47639. methods to draw the bubble's contents.
  47640. */
  47641. BubbleComponent();
  47642. public:
  47643. /** Destructor. */
  47644. ~BubbleComponent();
  47645. /** A list of permitted placements for the bubble, relative to the co-ordinates
  47646. at which it should be pointing.
  47647. @see setAllowedPlacement
  47648. */
  47649. enum BubblePlacement
  47650. {
  47651. above = 1,
  47652. below = 2,
  47653. left = 4,
  47654. right = 8
  47655. };
  47656. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  47657. point at which it's pointing.
  47658. By default when setPosition() is called, the bubble will place itself either
  47659. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  47660. the values in BubblePlacement to restrict this choice.
  47661. E.g. if you only want your bubble to appear above or below the target area,
  47662. use setAllowedPlacement (above | below);
  47663. @see BubblePlacement
  47664. */
  47665. void setAllowedPlacement (int newPlacement);
  47666. /** Moves and resizes the bubble to point at a given component.
  47667. This will resize the bubble to fit its content, then find a position for it
  47668. so that it's next to, but doesn't overlap the given component.
  47669. It'll put itself either above, below, or to the side of the component depending
  47670. on where there's the most space, honouring any restrictions that were set
  47671. with setAllowedPlacement().
  47672. */
  47673. void setPosition (Component* componentToPointTo);
  47674. /** Moves and resizes the bubble to point at a given point.
  47675. This will resize the bubble to fit its content, then position it
  47676. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  47677. are relative to either the bubble component's parent component if it has one, or
  47678. they are screen co-ordinates if not.
  47679. It'll put itself either above, below, or to the side of this point, depending
  47680. on where there's the most space, honouring any restrictions that were set
  47681. with setAllowedPlacement().
  47682. */
  47683. void setPosition (int arrowTipX,
  47684. int arrowTipY);
  47685. /** Moves and resizes the bubble to point at a given rectangle.
  47686. This will resize the bubble to fit its content, then find a position for it
  47687. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  47688. co-ordinates are relative to either the bubble component's parent component
  47689. if it has one, or they are screen co-ordinates if not.
  47690. It'll put itself either above, below, or to the side of the component depending
  47691. on where there's the most space, honouring any restrictions that were set
  47692. with setAllowedPlacement().
  47693. */
  47694. void setPosition (const Rectangle<int>& rectangleToPointTo);
  47695. protected:
  47696. /** Subclasses should override this to return the size of the content they
  47697. want to draw inside the bubble.
  47698. */
  47699. virtual void getContentSize (int& width, int& height) = 0;
  47700. /** Subclasses should override this to draw their bubble's contents.
  47701. The graphics object's clip region and the dimensions passed in here are
  47702. set up to paint just the rectangle inside the bubble.
  47703. */
  47704. virtual void paintContent (Graphics& g, int width, int height) = 0;
  47705. public:
  47706. /** @internal */
  47707. void paint (Graphics& g);
  47708. private:
  47709. Rectangle<int> content;
  47710. int side, allowablePlacements;
  47711. float arrowTipX, arrowTipY;
  47712. DropShadowEffect shadow;
  47713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  47714. };
  47715. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47716. /*** End of inlined file: juce_BubbleComponent.h ***/
  47717. #endif
  47718. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47719. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  47720. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47721. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47722. /**
  47723. A speech-bubble component that displays a short message.
  47724. This can be used to show a message with the tail of the speech bubble
  47725. pointing to a particular component or location on the screen.
  47726. @see BubbleComponent
  47727. */
  47728. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  47729. private Timer
  47730. {
  47731. public:
  47732. /** Creates a bubble component.
  47733. After creating one a BubbleComponent, do the following:
  47734. - add it to an appropriate parent component, or put it on the
  47735. desktop with Component::addToDesktop (0).
  47736. - use the showAt() method to show a message.
  47737. - it will make itself invisible after it times-out (and can optionally
  47738. also delete itself), or you can reuse it somewhere else by calling
  47739. showAt() again.
  47740. */
  47741. BubbleMessageComponent (int fadeOutLengthMs = 150);
  47742. /** Destructor. */
  47743. ~BubbleMessageComponent();
  47744. /** Shows a message bubble at a particular position.
  47745. This shows the bubble with its stem pointing to the given location
  47746. (co-ordinates being relative to its parent component).
  47747. For details about exactly how it decides where to position itself, see
  47748. BubbleComponent::updatePosition().
  47749. @param x the x co-ordinate of end of the bubble's tail
  47750. @param y the y co-ordinate of end of the bubble's tail
  47751. @param message the text to display
  47752. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47753. from its parent compnent. If this is 0 or less, it
  47754. will stay there until manually removed.
  47755. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47756. mouse button is pressed (anywhere on the screen)
  47757. @param deleteSelfAfterUse if true, then the component will delete itself after
  47758. it becomes invisible
  47759. */
  47760. void showAt (int x, int y,
  47761. const String& message,
  47762. int numMillisecondsBeforeRemoving,
  47763. bool removeWhenMouseClicked = true,
  47764. bool deleteSelfAfterUse = false);
  47765. /** Shows a message bubble next to a particular component.
  47766. This shows the bubble with its stem pointing at the given component.
  47767. For details about exactly how it decides where to position itself, see
  47768. BubbleComponent::updatePosition().
  47769. @param component the component that you want to point at
  47770. @param message the text to display
  47771. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47772. from its parent compnent. If this is 0 or less, it
  47773. will stay there until manually removed.
  47774. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47775. mouse button is pressed (anywhere on the screen)
  47776. @param deleteSelfAfterUse if true, then the component will delete itself after
  47777. it becomes invisible
  47778. */
  47779. void showAt (Component* component,
  47780. const String& message,
  47781. int numMillisecondsBeforeRemoving,
  47782. bool removeWhenMouseClicked = true,
  47783. bool deleteSelfAfterUse = false);
  47784. /** @internal */
  47785. void getContentSize (int& w, int& h);
  47786. /** @internal */
  47787. void paintContent (Graphics& g, int w, int h);
  47788. /** @internal */
  47789. void timerCallback();
  47790. private:
  47791. int fadeOutLength, mouseClickCounter;
  47792. TextLayout textLayout;
  47793. int64 expiryTime;
  47794. bool deleteAfterUse;
  47795. void init (int numMillisecondsBeforeRemoving,
  47796. bool removeWhenMouseClicked,
  47797. bool deleteSelfAfterUse);
  47798. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  47799. };
  47800. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47801. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  47802. #endif
  47803. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47804. /*** Start of inlined file: juce_ColourSelector.h ***/
  47805. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47806. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  47807. /**
  47808. A component that lets the user choose a colour.
  47809. This shows RGB sliders and a colourspace that the user can pick colours from.
  47810. This class is also a ChangeBroadcaster, so listeners can register to be told
  47811. when the colour changes.
  47812. */
  47813. class JUCE_API ColourSelector : public Component,
  47814. public ChangeBroadcaster,
  47815. protected SliderListener
  47816. {
  47817. public:
  47818. /** Options for the type of selector to show. These are passed into the constructor. */
  47819. enum ColourSelectorOptions
  47820. {
  47821. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  47822. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  47823. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  47824. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  47825. };
  47826. /** Creates a ColourSelector object.
  47827. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  47828. which of the selector's features should be visible.
  47829. The edgeGap value specifies the amount of space to leave around the edge.
  47830. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  47831. colourspace and hue selector components.
  47832. */
  47833. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  47834. int edgeGap = 4,
  47835. int gapAroundColourSpaceComponent = 7);
  47836. /** Destructor. */
  47837. ~ColourSelector();
  47838. /** Returns the colour that the user has currently selected.
  47839. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  47840. register to be told when the colour changes.
  47841. @see setCurrentColour
  47842. */
  47843. const Colour getCurrentColour() const;
  47844. /** Changes the colour that is currently being shown.
  47845. */
  47846. void setCurrentColour (const Colour& newColour);
  47847. /** Tells the selector how many preset colour swatches you want to have on the component.
  47848. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47849. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47850. their values.
  47851. */
  47852. virtual int getNumSwatches() const;
  47853. /** Called by the selector to find out the colour of one of the swatches.
  47854. Your subclass should return the colour of the swatch with the given index.
  47855. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47856. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47857. their values.
  47858. */
  47859. virtual const Colour getSwatchColour (int index) const;
  47860. /** Called by the selector when the user puts a new colour into one of the swatches.
  47861. Your subclass should change the colour of the swatch with the given index.
  47862. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47863. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47864. their values.
  47865. */
  47866. virtual void setSwatchColour (int index, const Colour& newColour) const;
  47867. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47868. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47869. methods.
  47870. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47871. */
  47872. enum ColourIds
  47873. {
  47874. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  47875. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  47876. };
  47877. private:
  47878. class ColourSpaceView;
  47879. class HueSelectorComp;
  47880. class SwatchComponent;
  47881. friend class ColourSpaceView;
  47882. friend class ScopedPointer<ColourSpaceView>;
  47883. friend class HueSelectorComp;
  47884. friend class ScopedPointer<HueSelectorComp>;
  47885. Colour colour;
  47886. float h, s, v;
  47887. ScopedPointer<Slider> sliders[4];
  47888. ScopedPointer<ColourSpaceView> colourSpace;
  47889. ScopedPointer<HueSelectorComp> hueSelector;
  47890. OwnedArray <SwatchComponent> swatchComponents;
  47891. const int flags;
  47892. int edgeGap;
  47893. Rectangle<int> previewArea;
  47894. void setHue (float newH);
  47895. void setSV (float newS, float newV);
  47896. void updateHSV();
  47897. void update();
  47898. void sliderValueChanged (Slider*);
  47899. void paint (Graphics& g);
  47900. void resized();
  47901. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  47902. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  47903. // This constructor is here temporarily to prevent old code compiling, because the parameters
  47904. // have changed - if you get an error here, update your code to use the new constructor instead..
  47905. ColourSelector (bool);
  47906. #endif
  47907. };
  47908. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  47909. /*** End of inlined file: juce_ColourSelector.h ***/
  47910. #endif
  47911. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  47912. #endif
  47913. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47914. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  47915. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47916. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47917. /**
  47918. A component that displays a piano keyboard, whose notes can be clicked on.
  47919. This component will mimic a physical midi keyboard, showing the current state of
  47920. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  47921. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  47922. Another feature is that the computer keyboard can also be used to play notes. By
  47923. default it maps the top two rows of a standard querty keyboard to the notes, but
  47924. these can be remapped if needed. It will only respond to keypresses when it has
  47925. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  47926. The component is also a ChangeBroadcaster, so if you want to be informed when the
  47927. keyboard is scrolled, you can register a ChangeListener for callbacks.
  47928. @see MidiKeyboardState
  47929. */
  47930. class JUCE_API MidiKeyboardComponent : public Component,
  47931. public MidiKeyboardStateListener,
  47932. public ChangeBroadcaster,
  47933. private Timer,
  47934. private AsyncUpdater
  47935. {
  47936. public:
  47937. /** The direction of the keyboard.
  47938. @see setOrientation
  47939. */
  47940. enum Orientation
  47941. {
  47942. horizontalKeyboard,
  47943. verticalKeyboardFacingLeft,
  47944. verticalKeyboardFacingRight,
  47945. };
  47946. /** Creates a MidiKeyboardComponent.
  47947. @param state the midi keyboard model that this component will represent
  47948. @param orientation whether the keyboard is horizonal or vertical
  47949. */
  47950. MidiKeyboardComponent (MidiKeyboardState& state,
  47951. Orientation orientation);
  47952. /** Destructor. */
  47953. ~MidiKeyboardComponent();
  47954. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  47955. on the component.
  47956. Values are 0 to 1.0, where 1.0 is the heaviest.
  47957. @see setMidiChannel
  47958. */
  47959. void setVelocity (float velocity, bool useMousePositionForVelocity);
  47960. /** Changes the midi channel number that will be used for events triggered by clicking
  47961. on the component.
  47962. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  47963. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  47964. Although this is the channel used for outgoing events, the component can display
  47965. incoming events from more than one channel - see setMidiChannelsToDisplay()
  47966. @see setVelocity
  47967. */
  47968. void setMidiChannel (int midiChannelNumber);
  47969. /** Returns the midi channel that the keyboard is using for midi messages.
  47970. @see setMidiChannel
  47971. */
  47972. int getMidiChannel() const noexcept { return midiChannel; }
  47973. /** Sets a mask to indicate which incoming midi channels should be represented by
  47974. key movements.
  47975. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  47976. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  47977. in this mask, the on-screen keys will also go down.
  47978. By default, this mask is set to 0xffff (all channels displayed).
  47979. @see setMidiChannel
  47980. */
  47981. void setMidiChannelsToDisplay (int midiChannelMask);
  47982. /** Returns the current set of midi channels represented by the component.
  47983. This is the value that was set with setMidiChannelsToDisplay().
  47984. */
  47985. int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
  47986. /** Changes the width used to draw the white keys. */
  47987. void setKeyWidth (float widthInPixels);
  47988. /** Returns the width that was set by setKeyWidth(). */
  47989. float getKeyWidth() const noexcept { return keyWidth; }
  47990. /** Changes the keyboard's current direction. */
  47991. void setOrientation (Orientation newOrientation);
  47992. /** Returns the keyboard's current direction. */
  47993. const Orientation getOrientation() const noexcept { return orientation; }
  47994. /** Sets the range of midi notes that the keyboard will be limited to.
  47995. By default the range is 0 to 127 (inclusive), but you can limit this if you
  47996. only want a restricted set of the keys to be shown.
  47997. Note that the values here are inclusive and must be between 0 and 127.
  47998. */
  47999. void setAvailableRange (int lowestNote,
  48000. int highestNote);
  48001. /** Returns the first note in the available range.
  48002. @see setAvailableRange
  48003. */
  48004. int getRangeStart() const noexcept { return rangeStart; }
  48005. /** Returns the last note in the available range.
  48006. @see setAvailableRange
  48007. */
  48008. int getRangeEnd() const noexcept { return rangeEnd; }
  48009. /** If the keyboard extends beyond the size of the component, this will scroll
  48010. it to show the given key at the start.
  48011. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  48012. base class to send a callback to any ChangeListeners that have been registered.
  48013. */
  48014. void setLowestVisibleKey (int noteNumber);
  48015. /** Returns the number of the first key shown in the component.
  48016. @see setLowestVisibleKey
  48017. */
  48018. int getLowestVisibleKey() const noexcept { return firstKey; }
  48019. /** Returns the length of the black notes.
  48020. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  48021. */
  48022. int getBlackNoteLength() const noexcept { return blackNoteLength; }
  48023. /** If set to true, then scroll buttons will appear at either end of the keyboard
  48024. if there are too many notes to fit them all in the component at once.
  48025. */
  48026. void setScrollButtonsVisible (bool canScroll);
  48027. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48028. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48029. methods.
  48030. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48031. */
  48032. enum ColourIds
  48033. {
  48034. whiteNoteColourId = 0x1005000,
  48035. blackNoteColourId = 0x1005001,
  48036. keySeparatorLineColourId = 0x1005002,
  48037. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  48038. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  48039. textLabelColourId = 0x1005005,
  48040. upDownButtonBackgroundColourId = 0x1005006,
  48041. upDownButtonArrowColourId = 0x1005007
  48042. };
  48043. /** Returns the position within the component of the left-hand edge of a key.
  48044. Depending on the keyboard's orientation, this may be a horizontal or vertical
  48045. distance, in either direction.
  48046. */
  48047. int getKeyStartPosition (const int midiNoteNumber) const;
  48048. /** Deletes all key-mappings.
  48049. @see setKeyPressForNote
  48050. */
  48051. void clearKeyMappings();
  48052. /** Maps a key-press to a given note.
  48053. @param key the key that should trigger the note
  48054. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  48055. be. The actual midi note that gets played will be
  48056. this value + (12 * the current base octave). To change
  48057. the base octave, see setKeyPressBaseOctave()
  48058. */
  48059. void setKeyPressForNote (const KeyPress& key,
  48060. int midiNoteOffsetFromC);
  48061. /** Removes any key-mappings for a given note.
  48062. For a description of what the note number means, see setKeyPressForNote().
  48063. */
  48064. void removeKeyPressForNote (int midiNoteOffsetFromC);
  48065. /** Changes the base note above which key-press-triggered notes are played.
  48066. The set of key-mappings that trigger notes can be moved up and down to cover
  48067. the entire scale using this method.
  48068. The value passed in is an octave number between 0 and 10 (inclusive), and
  48069. indicates which C is the base note to which the key-mapped notes are
  48070. relative.
  48071. */
  48072. void setKeyPressBaseOctave (int newOctaveNumber);
  48073. /** This sets the octave number which is shown as the octave number for middle C.
  48074. This affects only the default implementation of getWhiteNoteText(), which
  48075. passes this octave number to MidiMessage::getMidiNoteName() in order to
  48076. get the note text. See MidiMessage::getMidiNoteName() for more info about
  48077. the parameter.
  48078. By default this value is set to 3.
  48079. @see getOctaveForMiddleC
  48080. */
  48081. void setOctaveForMiddleC (int octaveNumForMiddleC);
  48082. /** This returns the value set by setOctaveForMiddleC().
  48083. @see setOctaveForMiddleC
  48084. */
  48085. int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
  48086. /** @internal */
  48087. void paint (Graphics& g);
  48088. /** @internal */
  48089. void resized();
  48090. /** @internal */
  48091. void mouseMove (const MouseEvent& e);
  48092. /** @internal */
  48093. void mouseDrag (const MouseEvent& e);
  48094. /** @internal */
  48095. void mouseDown (const MouseEvent& e);
  48096. /** @internal */
  48097. void mouseUp (const MouseEvent& e);
  48098. /** @internal */
  48099. void mouseEnter (const MouseEvent& e);
  48100. /** @internal */
  48101. void mouseExit (const MouseEvent& e);
  48102. /** @internal */
  48103. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  48104. /** @internal */
  48105. void timerCallback();
  48106. /** @internal */
  48107. bool keyStateChanged (bool isKeyDown);
  48108. /** @internal */
  48109. void focusLost (FocusChangeType cause);
  48110. /** @internal */
  48111. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  48112. /** @internal */
  48113. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  48114. /** @internal */
  48115. void handleAsyncUpdate();
  48116. /** @internal */
  48117. void colourChanged();
  48118. protected:
  48119. /** Draws a white note in the given rectangle.
  48120. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48121. currently pressed down.
  48122. When doing this, be sure to note the keyboard's orientation.
  48123. */
  48124. virtual void drawWhiteNote (int midiNoteNumber,
  48125. Graphics& g,
  48126. int x, int y, int w, int h,
  48127. bool isDown, bool isOver,
  48128. const Colour& lineColour,
  48129. const Colour& textColour);
  48130. /** Draws a black note in the given rectangle.
  48131. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48132. currently pressed down.
  48133. When doing this, be sure to note the keyboard's orientation.
  48134. */
  48135. virtual void drawBlackNote (int midiNoteNumber,
  48136. Graphics& g,
  48137. int x, int y, int w, int h,
  48138. bool isDown, bool isOver,
  48139. const Colour& noteFillColour);
  48140. /** Allows text to be drawn on the white notes.
  48141. By default this is used to label the C in each octave, but could be used for other things.
  48142. @see setOctaveForMiddleC
  48143. */
  48144. virtual const String getWhiteNoteText (const int midiNoteNumber);
  48145. /** Draws the up and down buttons that change the base note. */
  48146. virtual void drawUpDownButton (Graphics& g, int w, int h,
  48147. const bool isMouseOver,
  48148. const bool isButtonPressed,
  48149. const bool movesOctavesUp);
  48150. /** Callback when the mouse is clicked on a key.
  48151. You could use this to do things like handle right-clicks on keys, etc.
  48152. Return true if you want the click to trigger the note, or false if you
  48153. want to handle it yourself and not have the note played.
  48154. @see mouseDraggedToKey
  48155. */
  48156. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  48157. /** Callback when the mouse is dragged from one key onto another.
  48158. @see mouseDownOnKey
  48159. */
  48160. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  48161. /** Calculates the positon of a given midi-note.
  48162. This can be overridden to create layouts with custom key-widths.
  48163. @param midiNoteNumber the note to find
  48164. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  48165. @param x the x position of the left-hand edge of the key (this method
  48166. always works in terms of a horizontal keyboard)
  48167. @param w the width of the key
  48168. */
  48169. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  48170. int& x, int& w) const;
  48171. private:
  48172. friend class MidiKeyboardUpDownButton;
  48173. MidiKeyboardState& state;
  48174. int xOffset, blackNoteLength;
  48175. float keyWidth;
  48176. Orientation orientation;
  48177. int midiChannel, midiInChannelMask;
  48178. float velocity;
  48179. int noteUnderMouse, mouseDownNote;
  48180. BigInteger keysPressed, keysCurrentlyDrawnDown;
  48181. int rangeStart, rangeEnd, firstKey;
  48182. bool canScroll, mouseDragging, useMousePositionForVelocity;
  48183. ScopedPointer<Button> scrollDown, scrollUp;
  48184. Array <KeyPress> keyPresses;
  48185. Array <int> keyPressNotes;
  48186. int keyMappingOctave;
  48187. int octaveNumForMiddleC;
  48188. static const uint8 whiteNotes[];
  48189. static const uint8 blackNotes[];
  48190. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  48191. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  48192. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  48193. void resetAnyKeysInUse();
  48194. void updateNoteUnderMouse (const Point<int>& pos);
  48195. void repaintNote (const int midiNoteNumber);
  48196. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  48197. };
  48198. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48199. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  48200. #endif
  48201. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48202. /*** Start of inlined file: juce_NSViewComponent.h ***/
  48203. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48204. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48205. #if ! DOXYGEN
  48206. class NSViewComponentInternal;
  48207. #endif
  48208. #if JUCE_MAC || DOXYGEN
  48209. /**
  48210. A Mac-specific class that can create and embed an NSView inside itself.
  48211. To use it, create one of these, put it in place and make sure it's visible in a
  48212. window, then use setView() to assign an NSView to it. The view will then be
  48213. moved and resized to follow the movements of this component.
  48214. Of course, since the view is a native object, it'll obliterate any
  48215. juce components that may overlap this component, but that's life.
  48216. */
  48217. class JUCE_API NSViewComponent : public Component
  48218. {
  48219. public:
  48220. /** Create an initially-empty container. */
  48221. NSViewComponent();
  48222. /** Destructor. */
  48223. ~NSViewComponent();
  48224. /** Assigns an NSView to this peer.
  48225. The view will be retained and released by this component for as long as
  48226. it is needed. To remove the current view, just call setView (nullptr).
  48227. Note: a void* is used here to avoid including the cocoa headers as
  48228. part of the juce.h, but the method expects an NSView*.
  48229. */
  48230. void setView (void* nsView);
  48231. /** Returns the current NSView.
  48232. Note: a void* is returned here to avoid including the cocoa headers as
  48233. a requirement of juce.h, so you should just cast the object to an NSView*.
  48234. */
  48235. void* getView() const;
  48236. /** Resizes this component to fit the view that it contains. */
  48237. void resizeToFitView();
  48238. /** @internal */
  48239. void paint (Graphics& g);
  48240. private:
  48241. friend class NSViewComponentInternal;
  48242. ScopedPointer <NSViewComponentInternal> info;
  48243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  48244. };
  48245. #endif
  48246. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48247. /*** End of inlined file: juce_NSViewComponent.h ***/
  48248. #endif
  48249. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48250. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  48251. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48252. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48253. // this is used to disable OpenGL, and is defined in juce_Config.h
  48254. #if JUCE_OPENGL || DOXYGEN
  48255. /**
  48256. Represents the various properties of an OpenGL bitmap format.
  48257. @see OpenGLComponent::setPixelFormat
  48258. */
  48259. class JUCE_API OpenGLPixelFormat
  48260. {
  48261. public:
  48262. /** Creates an OpenGLPixelFormat.
  48263. The default constructor just initialises the object as a simple 8-bit
  48264. RGBA format.
  48265. */
  48266. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  48267. int alphaBits = 8,
  48268. int depthBufferBits = 16,
  48269. int stencilBufferBits = 0);
  48270. OpenGLPixelFormat (const OpenGLPixelFormat&);
  48271. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  48272. bool operator== (const OpenGLPixelFormat&) const;
  48273. int redBits; /**< The number of bits per pixel to use for the red channel. */
  48274. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  48275. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  48276. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  48277. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  48278. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  48279. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  48280. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  48281. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  48282. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  48283. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  48284. /** Returns a list of all the pixel formats that can be used in this system.
  48285. A reference component is needed in case there are multiple screens with different
  48286. capabilities - in which case, the one that the component is on will be used.
  48287. */
  48288. static void getAvailablePixelFormats (Component* component,
  48289. OwnedArray <OpenGLPixelFormat>& results);
  48290. private:
  48291. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  48292. };
  48293. /**
  48294. A base class for types of OpenGL context.
  48295. An OpenGLComponent will supply its own context for drawing in its window.
  48296. */
  48297. class JUCE_API OpenGLContext
  48298. {
  48299. public:
  48300. /** Destructor. */
  48301. virtual ~OpenGLContext();
  48302. /** Makes this context the currently active one. */
  48303. virtual bool makeActive() const noexcept = 0;
  48304. /** If this context is currently active, it is disactivated. */
  48305. virtual bool makeInactive() const noexcept = 0;
  48306. /** Returns true if this context is currently active. */
  48307. virtual bool isActive() const noexcept = 0;
  48308. /** Swaps the buffers (if the context can do this). */
  48309. virtual void swapBuffers() = 0;
  48310. /** Sets whether the context checks the vertical sync before swapping.
  48311. The value is the number of frames to allow between buffer-swapping. This is
  48312. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  48313. and greater numbers indicate that it should swap less often.
  48314. Returns true if it sets the value successfully.
  48315. */
  48316. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  48317. /** Returns the current swap-sync interval.
  48318. See setSwapInterval() for info about the value returned.
  48319. */
  48320. virtual int getSwapInterval() const = 0;
  48321. /** Returns the pixel format being used by this context. */
  48322. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  48323. /** For windowed contexts, this moves the context within the bounds of
  48324. its parent window.
  48325. */
  48326. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  48327. /** For windowed contexts, this triggers a repaint of the window.
  48328. (Not relevent on all platforms).
  48329. */
  48330. virtual void repaint() = 0;
  48331. /** Returns an OS-dependent handle to the raw GL context.
  48332. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  48333. a GLXContext.
  48334. */
  48335. virtual void* getRawContext() const noexcept = 0;
  48336. /** Deletes the context.
  48337. This must only be called on the message thread, or will deadlock.
  48338. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  48339. to call any other OpenGL function afterwards.
  48340. This doesn't touch other resources, such as window handles, etc.
  48341. You'll probably never have to call this method directly.
  48342. */
  48343. virtual void deleteContext() = 0;
  48344. /** Returns the context that's currently in active use by the calling thread.
  48345. Returns 0 if there isn't an active context.
  48346. */
  48347. static OpenGLContext* getCurrentContext();
  48348. protected:
  48349. OpenGLContext() noexcept;
  48350. private:
  48351. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  48352. };
  48353. /**
  48354. A component that contains an OpenGL canvas.
  48355. Override this, add it to whatever component you want to, and use the renderOpenGL()
  48356. method to draw its contents.
  48357. */
  48358. class JUCE_API OpenGLComponent : public Component
  48359. {
  48360. public:
  48361. /** Used to select the type of openGL API to use, if more than one choice is available
  48362. on a particular platform.
  48363. */
  48364. enum OpenGLType
  48365. {
  48366. openGLDefault = 0,
  48367. #if JUCE_IOS
  48368. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  48369. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  48370. #endif
  48371. };
  48372. /** Creates an OpenGLComponent. */
  48373. OpenGLComponent (OpenGLType type = openGLDefault);
  48374. /** Destructor. */
  48375. ~OpenGLComponent();
  48376. /** Changes the pixel format used by this component.
  48377. @see OpenGLPixelFormat::getAvailablePixelFormats()
  48378. */
  48379. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  48380. /** Returns the pixel format that this component is currently using. */
  48381. const OpenGLPixelFormat getPixelFormat() const;
  48382. /** Specifies an OpenGL context which should be shared with the one that this
  48383. component is using.
  48384. This is an OpenGL feature that lets two contexts share their texture data.
  48385. Note that this pointer is stored by the component, and when the component
  48386. needs to recreate its internal context for some reason, the same context
  48387. will be used again to share lists. So if you pass a context in here,
  48388. don't delete the context while this component is still using it! You can
  48389. call shareWith (nullptr) to stop this component from sharing with it.
  48390. */
  48391. void shareWith (OpenGLContext* contextToShareListsWith);
  48392. /** Returns the context that this component is sharing with.
  48393. @see shareWith
  48394. */
  48395. OpenGLContext* getShareContext() const noexcept { return contextToShareListsWith; }
  48396. /** Flips the openGL buffers over. */
  48397. void swapBuffers();
  48398. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  48399. When this is called, makeCurrentContextActive() will already have been called
  48400. for you, so you just need to draw.
  48401. */
  48402. virtual void renderOpenGL() = 0;
  48403. /** This method is called when the component creates a new OpenGL context.
  48404. A new context may be created when the component is first used, or when it
  48405. is moved to a different window, or when the window is hidden and re-shown,
  48406. etc.
  48407. You can use this callback as an opportunity to set up things like textures
  48408. that your context needs.
  48409. New contexts are created on-demand by the makeCurrentContextActive() method - so
  48410. if the context is deleted, e.g. by changing the pixel format or window, no context
  48411. will be created until the next call to makeCurrentContextActive(), which will
  48412. synchronously create one and call this method. This means that if you're using
  48413. a non-GUI thread for rendering, you can make sure this method is be called by
  48414. your renderer thread.
  48415. When this callback happens, the context will already have been made current
  48416. using the makeCurrentContextActive() method, so there's no need to call it
  48417. again in your code.
  48418. */
  48419. virtual void newOpenGLContextCreated() = 0;
  48420. /** Returns the context that will draw into this component.
  48421. This may return 0 if the component is currently invisible or hasn't currently
  48422. got a context. The context object can be deleted and a new one created during
  48423. the lifetime of this component, and there may be times when it doesn't have one.
  48424. @see newOpenGLContextCreated()
  48425. */
  48426. OpenGLContext* getCurrentContext() const noexcept { return context; }
  48427. /** Makes this component the current openGL context.
  48428. You might want to use this in things like your resize() method, before calling
  48429. GL commands.
  48430. If this returns false, then the context isn't active, so you should avoid
  48431. making any calls.
  48432. This call may actually create a context if one isn't currently initialised. If
  48433. it does this, it will also synchronously call the newOpenGLContextCreated()
  48434. method to let you initialise it as necessary.
  48435. @see OpenGLContext::makeActive
  48436. */
  48437. bool makeCurrentContextActive();
  48438. /** Stops the current component being the active OpenGL context.
  48439. This is the opposite of makeCurrentContextActive()
  48440. @see OpenGLContext::makeInactive
  48441. */
  48442. void makeCurrentContextInactive();
  48443. /** Returns true if this component is the active openGL context for the
  48444. current thread.
  48445. @see OpenGLContext::isActive
  48446. */
  48447. bool isActiveContext() const noexcept;
  48448. /** Calls the rendering callback, and swaps the buffers afterwards.
  48449. This is called automatically by paint() when the component needs to be rendered.
  48450. It can be overridden if you need to decouple the rendering from the paint callback
  48451. and render with a custom thread.
  48452. Returns true if the operation succeeded.
  48453. */
  48454. virtual bool renderAndSwapBuffers();
  48455. /** This returns a critical section that can be used to lock the current context.
  48456. Because the context that is used by this component can change, e.g. when the
  48457. component is shown or hidden, then if you're rendering to it on a background
  48458. thread, this allows you to lock the context for the duration of your rendering
  48459. routine.
  48460. */
  48461. CriticalSection& getContextLock() noexcept { return contextLock; }
  48462. /** Returns the native handle of an embedded heavyweight window, if there is one.
  48463. E.g. On windows, this will return the HWND of the sub-window containing
  48464. the opengl context, on the mac it'll be the NSOpenGLView.
  48465. */
  48466. void* getNativeWindowHandle() const;
  48467. /** Delete the context.
  48468. This can be called back on the same thread that created the context. */
  48469. void deleteContext();
  48470. /** @internal */
  48471. void paint (Graphics& g);
  48472. private:
  48473. const OpenGLType type;
  48474. class OpenGLComponentWatcher;
  48475. friend class OpenGLComponentWatcher;
  48476. friend class ScopedPointer <OpenGLComponentWatcher>;
  48477. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  48478. ScopedPointer <OpenGLContext> context;
  48479. OpenGLContext* contextToShareListsWith;
  48480. CriticalSection contextLock;
  48481. OpenGLPixelFormat preferredPixelFormat;
  48482. bool needToUpdateViewport;
  48483. OpenGLContext* createContext();
  48484. void updateContextPosition();
  48485. void internalRepaint (int x, int y, int w, int h);
  48486. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  48487. };
  48488. #endif
  48489. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48490. /*** End of inlined file: juce_OpenGLComponent.h ***/
  48491. #endif
  48492. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48493. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  48494. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48495. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48496. /**
  48497. A component with a set of buttons at the top for changing between pages of
  48498. preferences.
  48499. This is just a handy way of writing a Mac-style preferences panel where you
  48500. have a row of buttons along the top for the different preference categories,
  48501. each button having an icon above its name. Clicking these will show an
  48502. appropriate prefs page below it.
  48503. You can either put one of these inside your own component, or just use the
  48504. showInDialogBox() method to show it in a window and run it modally.
  48505. To use it, just add a set of named pages with the addSettingsPage() method,
  48506. and implement the createComponentForPage() method to create suitable components
  48507. for each of these pages.
  48508. */
  48509. class JUCE_API PreferencesPanel : public Component,
  48510. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  48511. {
  48512. public:
  48513. /** Creates an empty panel.
  48514. Use addSettingsPage() to add some pages to it in your constructor.
  48515. */
  48516. PreferencesPanel();
  48517. /** Destructor. */
  48518. ~PreferencesPanel();
  48519. /** Creates a page using a set of drawables to define the page's icon.
  48520. Note that the other version of this method is much easier if you're using
  48521. an image instead of a custom drawable.
  48522. @param pageTitle the name of this preferences page - you'll need to
  48523. make sure your createComponentForPage() method creates
  48524. a suitable component when it is passed this name
  48525. @param normalIcon the drawable to display in the page's button normally
  48526. @param overIcon the drawable to display in the page's button when the mouse is over
  48527. @param downIcon the drawable to display in the page's button when the button is down
  48528. @see DrawableButton
  48529. */
  48530. void addSettingsPage (const String& pageTitle,
  48531. const Drawable* normalIcon,
  48532. const Drawable* overIcon,
  48533. const Drawable* downIcon);
  48534. /** Creates a page using a set of drawables to define the page's icon.
  48535. The other version of this method gives you more control over the icon, but this
  48536. one is much easier if you're just loading it from a file.
  48537. @param pageTitle the name of this preferences page - you'll need to
  48538. make sure your createComponentForPage() method creates
  48539. a suitable component when it is passed this name
  48540. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  48541. For this to look good, you'll probably want to use a nice
  48542. transparent png file.
  48543. @param imageDataSize the size of the image data, in bytes
  48544. */
  48545. void addSettingsPage (const String& pageTitle,
  48546. const void* imageData,
  48547. int imageDataSize);
  48548. /** Utility method to display this panel in a DialogWindow.
  48549. Calling this will create a DialogWindow containing this panel with the
  48550. given size and title, and will run it modally, returning when the user
  48551. closes the dialog box.
  48552. */
  48553. void showInDialogBox (const String& dialogTitle,
  48554. int dialogWidth,
  48555. int dialogHeight,
  48556. const Colour& backgroundColour = Colours::white);
  48557. /** Subclasses must override this to return a component for each preferences page.
  48558. The subclass should return a pointer to a new component representing the named
  48559. page, which the panel will then display.
  48560. The panel will delete the component later when the user goes to another page
  48561. or deletes the panel.
  48562. */
  48563. virtual Component* createComponentForPage (const String& pageName) = 0;
  48564. /** Changes the current page being displayed. */
  48565. void setCurrentPage (const String& pageName);
  48566. /** Returns the size of the buttons shown along the top. */
  48567. int getButtonSize() const noexcept;
  48568. /** Changes the size of the buttons shown along the top. */
  48569. void setButtonSize (int newSize);
  48570. /** @internal */
  48571. void resized();
  48572. /** @internal */
  48573. void paint (Graphics& g);
  48574. /** @internal */
  48575. void buttonClicked (Button* button);
  48576. private:
  48577. String currentPageName;
  48578. ScopedPointer <Component> currentPage;
  48579. OwnedArray<DrawableButton> buttons;
  48580. int buttonSize;
  48581. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  48582. };
  48583. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48584. /*** End of inlined file: juce_PreferencesPanel.h ***/
  48585. #endif
  48586. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48587. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  48588. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48589. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48590. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  48591. // amalgamated build)
  48592. #ifndef DOXYGEN
  48593. #if JUCE_WINDOWS
  48594. typedef ActiveXControlComponent QTCompBaseClass;
  48595. #elif JUCE_MAC
  48596. typedef NSViewComponent QTCompBaseClass;
  48597. #endif
  48598. #endif
  48599. // this is used to disable QuickTime, and is defined in juce_Config.h
  48600. #if JUCE_QUICKTIME || DOXYGEN
  48601. /**
  48602. A window that can play back a QuickTime movie.
  48603. */
  48604. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  48605. {
  48606. public:
  48607. /** Creates a QuickTimeMovieComponent, initially blank.
  48608. Use the loadMovie() method to load a movie once you've added the
  48609. component to a window, (or put it on the desktop as a heavyweight window).
  48610. Loading a movie when the component isn't visible can cause problems, as
  48611. QuickTime needs a window handle to initialise properly.
  48612. */
  48613. QuickTimeMovieComponent();
  48614. /** Destructor. */
  48615. ~QuickTimeMovieComponent();
  48616. /** Returns true if QT is installed and working on this machine.
  48617. */
  48618. static bool isQuickTimeAvailable() noexcept;
  48619. /** Tries to load a QuickTime movie from a file into the player.
  48620. It's best to call this function once you've added the component to a window,
  48621. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48622. component isn't visible can cause problems, because QuickTime needs a window
  48623. handle to do its stuff.
  48624. @param movieFile the .mov file to open
  48625. @param isControllerVisible whether to show a controller bar at the bottom
  48626. @returns true if the movie opens successfully
  48627. */
  48628. bool loadMovie (const File& movieFile,
  48629. bool isControllerVisible);
  48630. /** Tries to load a QuickTime movie from a URL into the player.
  48631. It's best to call this function once you've added the component to a window,
  48632. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48633. component isn't visible can cause problems, because QuickTime needs a window
  48634. handle to do its stuff.
  48635. @param movieURL the .mov file to open
  48636. @param isControllerVisible whether to show a controller bar at the bottom
  48637. @returns true if the movie opens successfully
  48638. */
  48639. bool loadMovie (const URL& movieURL,
  48640. bool isControllerVisible);
  48641. /** Tries to load a QuickTime movie from a stream into the player.
  48642. It's best to call this function once you've added the component to a window,
  48643. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48644. component isn't visible can cause problems, because QuickTime needs a window
  48645. handle to do its stuff.
  48646. @param movieStream a stream containing a .mov file. The component may try
  48647. to read the whole stream before playing, rather than
  48648. streaming from it.
  48649. @param isControllerVisible whether to show a controller bar at the bottom
  48650. @returns true if the movie opens successfully
  48651. */
  48652. bool loadMovie (InputStream* movieStream,
  48653. bool isControllerVisible);
  48654. /** Closes the movie, if one is open. */
  48655. void closeMovie();
  48656. /** Returns the movie file that is currently open.
  48657. If there isn't one, this returns File::nonexistent
  48658. */
  48659. const File getCurrentMovieFile() const;
  48660. /** Returns true if there's currently a movie open. */
  48661. bool isMovieOpen() const;
  48662. /** Returns the length of the movie, in seconds. */
  48663. double getMovieDuration() const;
  48664. /** Returns the movie's natural size, in pixels.
  48665. You can use this to resize the component to show the movie at its preferred
  48666. scale.
  48667. If no movie is loaded, the size returned will be 0 x 0.
  48668. */
  48669. void getMovieNormalSize (int& width, int& height) const;
  48670. /** This will position the component within a given area, keeping its aspect
  48671. ratio correct according to the movie's normal size.
  48672. The component will be made as large as it can go within the space, and will
  48673. be aligned according to the justification value if this means there are gaps at
  48674. the top or sides.
  48675. */
  48676. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  48677. const RectanglePlacement& placement);
  48678. /** Starts the movie playing. */
  48679. void play();
  48680. /** Stops the movie playing. */
  48681. void stop();
  48682. /** Returns true if the movie is currently playing. */
  48683. bool isPlaying() const;
  48684. /** Moves the movie's position back to the start. */
  48685. void goToStart();
  48686. /** Sets the movie's position to a given time. */
  48687. void setPosition (double seconds);
  48688. /** Returns the current play position of the movie. */
  48689. double getPosition() const;
  48690. /** Changes the movie playback rate.
  48691. A value of 1 is normal speed, greater values play it proportionately faster,
  48692. smaller values play it slower.
  48693. */
  48694. void setSpeed (float newSpeed);
  48695. /** Changes the movie's playback volume.
  48696. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  48697. */
  48698. void setMovieVolume (float newVolume);
  48699. /** Returns the movie's playback volume.
  48700. @returns the volume in the range 0 (silent) to 1.0 (full)
  48701. */
  48702. float getMovieVolume() const;
  48703. /** Tells the movie whether it should loop. */
  48704. void setLooping (bool shouldLoop);
  48705. /** Returns true if the movie is currently looping.
  48706. @see setLooping
  48707. */
  48708. bool isLooping() const;
  48709. /** True if the native QuickTime controller bar is shown in the window.
  48710. @see loadMovie
  48711. */
  48712. bool isControllerVisible() const;
  48713. /** @internal */
  48714. void paint (Graphics& g);
  48715. private:
  48716. File movieFile;
  48717. bool movieLoaded, controllerVisible, looping;
  48718. #if JUCE_WINDOWS
  48719. void parentHierarchyChanged();
  48720. void visibilityChanged();
  48721. void createControlIfNeeded();
  48722. bool isControlCreated() const;
  48723. class Pimpl;
  48724. friend class ScopedPointer <Pimpl>;
  48725. ScopedPointer <Pimpl> pimpl;
  48726. #else
  48727. void* movie;
  48728. #endif
  48729. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  48730. };
  48731. #endif
  48732. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48733. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  48734. #endif
  48735. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48736. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  48737. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48738. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48739. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  48740. /**
  48741. On Windows only, this component sits in the taskbar tray as a small icon.
  48742. To use it, just create one of these components, but don't attempt to make it
  48743. visible, add it to a parent, or put it on the desktop.
  48744. You can then call setIconImage() to create an icon for it in the taskbar.
  48745. To change the icon's tooltip, you can use setIconTooltip().
  48746. To respond to mouse-events, you can override the normal mouseDown(),
  48747. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  48748. position will not be valid, you can use this to respond to clicks. Traditionally
  48749. you'd use a left-click to show your application's window, and a right-click
  48750. to show a pop-up menu.
  48751. */
  48752. class JUCE_API SystemTrayIconComponent : public Component
  48753. {
  48754. public:
  48755. SystemTrayIconComponent();
  48756. /** Destructor. */
  48757. ~SystemTrayIconComponent();
  48758. /** Changes the image shown in the taskbar.
  48759. */
  48760. void setIconImage (const Image& newImage);
  48761. /** Changes the tooltip that Windows shows above the icon. */
  48762. void setIconTooltip (const String& tooltip);
  48763. #if JUCE_LINUX
  48764. /** @internal */
  48765. void paint (Graphics& g);
  48766. #endif
  48767. private:
  48768. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  48769. };
  48770. #endif
  48771. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48772. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  48773. #endif
  48774. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48775. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  48776. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48777. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48778. #if JUCE_WEB_BROWSER || DOXYGEN
  48779. #if ! DOXYGEN
  48780. class WebBrowserComponentInternal;
  48781. #endif
  48782. /**
  48783. A component that displays an embedded web browser.
  48784. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  48785. Windows, probably IE.
  48786. */
  48787. class JUCE_API WebBrowserComponent : public Component
  48788. {
  48789. public:
  48790. /** Creates a WebBrowserComponent.
  48791. Once it's created and visible, send the browser to a URL using goToURL().
  48792. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  48793. component is taken offscreen, it'll clear the current page
  48794. and replace it with a blank page - this can be handy to stop
  48795. the browser using resources in the background when it's not
  48796. actually being used.
  48797. */
  48798. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  48799. /** Destructor. */
  48800. ~WebBrowserComponent();
  48801. /** Sends the browser to a particular URL.
  48802. @param url the URL to go to.
  48803. @param headers an optional set of parameters to put in the HTTP header. If
  48804. you supply this, it should be a set of string in the form
  48805. "HeaderKey: HeaderValue"
  48806. @param postData an optional block of data that will be attached to the HTTP
  48807. POST request
  48808. */
  48809. void goToURL (const String& url,
  48810. const StringArray* headers = nullptr,
  48811. const MemoryBlock* postData = nullptr);
  48812. /** Stops the current page loading.
  48813. */
  48814. void stop();
  48815. /** Sends the browser back one page.
  48816. */
  48817. void goBack();
  48818. /** Sends the browser forward one page.
  48819. */
  48820. void goForward();
  48821. /** Refreshes the browser.
  48822. */
  48823. void refresh();
  48824. /** This callback is called when the browser is about to navigate
  48825. to a new location.
  48826. You can override this method to perform some action when the user
  48827. tries to go to a particular URL. To allow the operation to carry on,
  48828. return true, or return false to stop the navigation happening.
  48829. */
  48830. virtual bool pageAboutToLoad (const String& newURL);
  48831. /** @internal */
  48832. void paint (Graphics& g);
  48833. /** @internal */
  48834. void resized();
  48835. /** @internal */
  48836. void parentHierarchyChanged();
  48837. /** @internal */
  48838. void visibilityChanged();
  48839. private:
  48840. WebBrowserComponentInternal* browser;
  48841. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  48842. String lastURL;
  48843. StringArray lastHeaders;
  48844. MemoryBlock lastPostData;
  48845. void reloadLastURL();
  48846. void checkWindowAssociation();
  48847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  48848. };
  48849. #endif
  48850. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48851. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  48852. #endif
  48853. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  48854. #endif
  48855. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48856. /*** Start of inlined file: juce_CallOutBox.h ***/
  48857. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48858. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  48859. /**
  48860. A box with a small arrow that can be used as a temporary pop-up window to show
  48861. extra controls when a button or other component is clicked.
  48862. Using one of these is similar to having a popup menu attached to a button or
  48863. other component - but it looks fancier, and has an arrow that can indicate the
  48864. object that it applies to.
  48865. Normally, you'd create one of these on the stack and run it modally, e.g.
  48866. @code
  48867. void mouseUp (const MouseEvent& e)
  48868. {
  48869. MyContentComponent content;
  48870. content.setSize (300, 300);
  48871. CallOutBox callOut (content, *this, nullptr);
  48872. callOut.runModalLoop();
  48873. }
  48874. @endcode
  48875. The call-out will resize and position itself when the content changes size.
  48876. */
  48877. class JUCE_API CallOutBox : public Component
  48878. {
  48879. public:
  48880. /** Creates a CallOutBox.
  48881. @param contentComponent the component to display inside the call-out. This should
  48882. already have a size set (although the call-out will also
  48883. update itself when the component's size is changed later).
  48884. Obviously this component must not be deleted until the
  48885. call-out box has been deleted.
  48886. @param componentToPointTo the component that the call-out's arrow should point towards
  48887. @param parentComponent if non-zero, this is the component to add the call-out to. If
  48888. this is zero, the call-out will be added to the desktop.
  48889. */
  48890. CallOutBox (Component& contentComponent,
  48891. Component& componentToPointTo,
  48892. Component* parentComponent);
  48893. /** Destructor. */
  48894. ~CallOutBox();
  48895. /** Changes the length of the arrow. */
  48896. void setArrowSize (float newSize);
  48897. /** Updates the position and size of the box.
  48898. You shouldn't normally need to call this, unless you need more precise control over the
  48899. layout.
  48900. @param newAreaToPointTo the rectangle to make the box's arrow point to
  48901. @param newAreaToFitIn the area within which the box's position should be constrained
  48902. */
  48903. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  48904. const Rectangle<int>& newAreaToFitIn);
  48905. /** @internal */
  48906. void paint (Graphics& g);
  48907. /** @internal */
  48908. void resized();
  48909. /** @internal */
  48910. void moved();
  48911. /** @internal */
  48912. void childBoundsChanged (Component*);
  48913. /** @internal */
  48914. bool hitTest (int x, int y);
  48915. /** @internal */
  48916. void inputAttemptWhenModal();
  48917. /** @internal */
  48918. bool keyPressed (const KeyPress& key);
  48919. /** @internal */
  48920. void handleCommandMessage (int commandId);
  48921. private:
  48922. int borderSpace;
  48923. float arrowSize;
  48924. Component& content;
  48925. Path outline;
  48926. Point<float> targetPoint;
  48927. Rectangle<int> availableArea, targetArea;
  48928. Image background;
  48929. void refreshPath();
  48930. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  48931. };
  48932. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  48933. /*** End of inlined file: juce_CallOutBox.h ***/
  48934. #endif
  48935. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48936. /*** Start of inlined file: juce_ComponentPeer.h ***/
  48937. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48938. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  48939. class ComponentBoundsConstrainer;
  48940. /**
  48941. The Component class uses a ComponentPeer internally to create and manage a real
  48942. operating-system window.
  48943. This is an abstract base class - the platform specific code contains implementations of
  48944. it for the various platforms.
  48945. User-code should very rarely need to have any involvement with this class.
  48946. @see Component::createNewPeer
  48947. */
  48948. class JUCE_API ComponentPeer
  48949. {
  48950. public:
  48951. /** A combination of these flags is passed to the ComponentPeer constructor. */
  48952. enum StyleFlags
  48953. {
  48954. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  48955. entry on the taskbar (ignored on MacOSX) */
  48956. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  48957. tooltip, etc. */
  48958. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  48959. through it (may not be possible on some platforms). */
  48960. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  48961. title bar and frame\. if not specified, the window will be
  48962. borderless. */
  48963. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  48964. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  48965. minimise button on it. */
  48966. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  48967. maximise button on it. */
  48968. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  48969. close button on it. */
  48970. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  48971. not be possible on all platforms). */
  48972. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  48973. do its own repainting, but only to repaint when the
  48974. performAnyPendingRepaintsNow() method is called. */
  48975. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  48976. be used for things like plugin windows, to stop them interfering
  48977. with the host's shortcut keys */
  48978. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  48979. };
  48980. /** Creates a peer.
  48981. The component is the one that we intend to represent, and the style flags are
  48982. a combination of the values in the StyleFlags enum
  48983. */
  48984. ComponentPeer (Component* component, int styleFlags);
  48985. /** Destructor. */
  48986. virtual ~ComponentPeer();
  48987. /** Returns the component being represented by this peer. */
  48988. Component* getComponent() const noexcept { return component; }
  48989. /** Returns the set of style flags that were set when the window was created.
  48990. @see Component::addToDesktop
  48991. */
  48992. int getStyleFlags() const noexcept { return styleFlags; }
  48993. /** Returns the raw handle to whatever kind of window is being used.
  48994. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  48995. but rememeber there's no guarantees what you'll get back.
  48996. */
  48997. virtual void* getNativeHandle() const = 0;
  48998. /** Shows or hides the window. */
  48999. virtual void setVisible (bool shouldBeVisible) = 0;
  49000. /** Changes the title of the window. */
  49001. virtual void setTitle (const String& title) = 0;
  49002. /** Moves the window without changing its size.
  49003. If the native window is contained in another window, then the co-ordinates are
  49004. relative to the parent window's origin, not the screen origin.
  49005. This should result in a callback to handleMovedOrResized().
  49006. */
  49007. virtual void setPosition (int x, int y) = 0;
  49008. /** Resizes the window without changing its position.
  49009. This should result in a callback to handleMovedOrResized().
  49010. */
  49011. virtual void setSize (int w, int h) = 0;
  49012. /** Moves and resizes the window.
  49013. If the native window is contained in another window, then the co-ordinates are
  49014. relative to the parent window's origin, not the screen origin.
  49015. This should result in a callback to handleMovedOrResized().
  49016. */
  49017. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  49018. /** Returns the current position and size of the window.
  49019. If the native window is contained in another window, then the co-ordinates are
  49020. relative to the parent window's origin, not the screen origin.
  49021. */
  49022. virtual const Rectangle<int> getBounds() const = 0;
  49023. /** Returns the x-position of this window, relative to the screen's origin. */
  49024. virtual const Point<int> getScreenPosition() const = 0;
  49025. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  49026. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  49027. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  49028. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  49029. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  49030. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  49031. /** Converts a screen area to a position relative to the top-left of this component. */
  49032. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  49033. /** Minimises the window. */
  49034. virtual void setMinimised (bool shouldBeMinimised) = 0;
  49035. /** True if the window is currently minimised. */
  49036. virtual bool isMinimised() const = 0;
  49037. /** Enable/disable fullscreen mode for the window. */
  49038. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  49039. /** True if the window is currently full-screen. */
  49040. virtual bool isFullScreen() const = 0;
  49041. /** Sets the size to restore to if fullscreen mode is turned off. */
  49042. void setNonFullScreenBounds (const Rectangle<int>& newBounds) noexcept;
  49043. /** Returns the size to restore to if fullscreen mode is turned off. */
  49044. const Rectangle<int>& getNonFullScreenBounds() const noexcept;
  49045. /** Attempts to change the icon associated with this window.
  49046. */
  49047. virtual void setIcon (const Image& newIcon) = 0;
  49048. /** Sets a constrainer to use if the peer can resize itself.
  49049. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  49050. */
  49051. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) noexcept;
  49052. /** Returns the current constrainer, if one has been set. */
  49053. ComponentBoundsConstrainer* getConstrainer() const noexcept { return constrainer; }
  49054. /** Checks if a point is in the window.
  49055. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  49056. is false, then this returns false if the point is actually inside a child of this
  49057. window.
  49058. */
  49059. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  49060. /** Returns the size of the window frame that's around this window.
  49061. Whether or not the window has a normal window frame depends on the flags
  49062. that were set when the window was created by Component::addToDesktop()
  49063. */
  49064. virtual const BorderSize<int> getFrameSize() const = 0;
  49065. /** This is called when the window's bounds change.
  49066. A peer implementation must call this when the window is moved and resized, so that
  49067. this method can pass the message on to the component.
  49068. */
  49069. void handleMovedOrResized();
  49070. /** This is called if the screen resolution changes.
  49071. A peer implementation must call this if the monitor arrangement changes or the available
  49072. screen size changes.
  49073. */
  49074. void handleScreenSizeChange();
  49075. /** This is called to repaint the component into the given context. */
  49076. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  49077. /** Sets this window to either be always-on-top or normal.
  49078. Some kinds of window might not be able to do this, so should return false.
  49079. */
  49080. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  49081. /** Brings the window to the top, optionally also giving it focus. */
  49082. virtual void toFront (bool makeActive) = 0;
  49083. /** Moves the window to be just behind another one. */
  49084. virtual void toBehind (ComponentPeer* other) = 0;
  49085. /** Called when the window is brought to the front, either by the OS or by a call
  49086. to toFront().
  49087. */
  49088. void handleBroughtToFront();
  49089. /** True if the window has the keyboard focus. */
  49090. virtual bool isFocused() const = 0;
  49091. /** Tries to give the window keyboard focus. */
  49092. virtual void grabFocus() = 0;
  49093. /** Called when the window gains keyboard focus. */
  49094. void handleFocusGain();
  49095. /** Called when the window loses keyboard focus. */
  49096. void handleFocusLoss();
  49097. Component* getLastFocusedSubcomponent() const noexcept;
  49098. /** Called when a key is pressed.
  49099. For keycode info, see the KeyPress class.
  49100. Returns true if the keystroke was used.
  49101. */
  49102. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  49103. /** Called whenever a key is pressed or released.
  49104. Returns true if the keystroke was used.
  49105. */
  49106. bool handleKeyUpOrDown (bool isKeyDown);
  49107. /** Called whenever a modifier key is pressed or released. */
  49108. void handleModifierKeysChange();
  49109. /** Tells the window that text input may be required at the given position.
  49110. This may cause things like a virtual on-screen keyboard to appear, depending
  49111. on the OS.
  49112. */
  49113. virtual void textInputRequired (const Point<int>& position) = 0;
  49114. /** If there's some kind of OS input-method in progress, this should dismiss it. */
  49115. virtual void dismissPendingTextInput();
  49116. /** Returns the currently focused TextInputTarget, or null if none is found. */
  49117. TextInputTarget* findCurrentTextInputTarget();
  49118. /** Invalidates a region of the window to be repainted asynchronously. */
  49119. virtual void repaint (const Rectangle<int>& area) = 0;
  49120. /** This can be called (from the message thread) to cause the immediate redrawing
  49121. of any areas of this window that need repainting.
  49122. You shouldn't ever really need to use this, it's mainly for special purposes
  49123. like supporting audio plugins where the host's event loop is out of our control.
  49124. */
  49125. virtual void performAnyPendingRepaintsNow() = 0;
  49126. /** Changes the window's transparency. */
  49127. virtual void setAlpha (float newAlpha) = 0;
  49128. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  49129. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  49130. void handleUserClosingWindow();
  49131. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  49132. void handleFileDragExit (const StringArray& files);
  49133. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  49134. /** Resets the masking region.
  49135. The subclass should call this every time it's about to call the handlePaint
  49136. method.
  49137. @see addMaskedRegion
  49138. */
  49139. void clearMaskedRegion();
  49140. /** Adds a rectangle to the set of areas not to paint over.
  49141. A component can call this on its peer during its paint() method, to signal
  49142. that the painting code should ignore a given region. The reason
  49143. for this is to stop embedded windows (such as OpenGL) getting painted over.
  49144. The masked region is cleared each time before a paint happens, so a component
  49145. will have to make sure it calls this every time it's painted.
  49146. */
  49147. void addMaskedRegion (int x, int y, int w, int h);
  49148. /** Returns the number of currently-active peers.
  49149. @see getPeer
  49150. */
  49151. static int getNumPeers() noexcept;
  49152. /** Returns one of the currently-active peers.
  49153. @see getNumPeers
  49154. */
  49155. static ComponentPeer* getPeer (int index) noexcept;
  49156. /** Checks if this peer object is valid.
  49157. @see getNumPeers
  49158. */
  49159. static bool isValidPeer (const ComponentPeer* peer) noexcept;
  49160. virtual const StringArray getAvailableRenderingEngines();
  49161. virtual int getCurrentRenderingEngine() const;
  49162. virtual void setCurrentRenderingEngine (int index);
  49163. protected:
  49164. Component* const component;
  49165. const int styleFlags;
  49166. RectangleList maskedRegion;
  49167. Rectangle<int> lastNonFullscreenBounds;
  49168. uint32 lastPaintTime;
  49169. ComponentBoundsConstrainer* constrainer;
  49170. static void updateCurrentModifiers() noexcept;
  49171. private:
  49172. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  49173. Component* lastDragAndDropCompUnderMouse;
  49174. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  49175. friend class Component;
  49176. friend class Desktop;
  49177. static ComponentPeer* getPeerFor (const Component* component) noexcept;
  49178. void setLastDragDropTarget (Component* comp);
  49179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  49180. };
  49181. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  49182. /*** End of inlined file: juce_ComponentPeer.h ***/
  49183. #endif
  49184. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49185. /*** Start of inlined file: juce_DialogWindow.h ***/
  49186. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49187. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  49188. /**
  49189. A dialog-box style window.
  49190. This class is a convenient way of creating a DocumentWindow with a close button
  49191. that can be triggered by pressing the escape key.
  49192. Any of the methods available to a DocumentWindow or ResizableWindow are also
  49193. available to this, so it can be made resizable, have a menu bar, etc.
  49194. To add items to the box, see the ResizableWindow::setContentOwned() or
  49195. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  49196. class - always put them in a content component!
  49197. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  49198. the user clicking the close button - for more info, see the DocumentWindow
  49199. help.
  49200. @see DocumentWindow, ResizableWindow
  49201. */
  49202. class JUCE_API DialogWindow : public DocumentWindow
  49203. {
  49204. public:
  49205. /** Creates a DialogWindow.
  49206. @param name the name to give the component - this is also
  49207. the title shown at the top of the window. To change
  49208. this later, use setName()
  49209. @param backgroundColour the colour to use for filling the window's background.
  49210. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49211. close button to be triggered
  49212. @param addToDesktop if true, the window will be automatically added to the
  49213. desktop; if false, you can use it as a child component
  49214. */
  49215. DialogWindow (const String& name,
  49216. const Colour& backgroundColour,
  49217. bool escapeKeyTriggersCloseButton,
  49218. bool addToDesktop = true);
  49219. /** Destructor.
  49220. If a content component has been set with setContentOwned(), it will be deleted.
  49221. */
  49222. ~DialogWindow();
  49223. /** Easy way of quickly showing a dialog box containing a given component.
  49224. This will open and display a DialogWindow containing a given component, making it
  49225. modal, but returning immediately to allow the dialog to finish in its own time. If
  49226. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  49227. instead.
  49228. To close the dialog programatically, you should call exitModalState (returnValue) on
  49229. the DialogWindow that is created. To find a pointer to this window from your
  49230. contentComponent, you can do something like this:
  49231. @code
  49232. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  49233. if (dw != nullptr)
  49234. dw->exitModalState (1234);
  49235. @endcode
  49236. @param dialogTitle the dialog box's title
  49237. @param contentComponent the content component for the dialog box. Make sure
  49238. that this has been set to the size you want it to
  49239. be before calling this method. The component won't
  49240. be deleted by this call, so you can re-use it or delete
  49241. it afterwards
  49242. @param componentToCentreAround if this is non-zero, it indicates a component that
  49243. you'd like to show this dialog box in front of. See the
  49244. DocumentWindow::centreAroundComponent() method for more
  49245. info on this parameter
  49246. @param backgroundColour a colour to use for the dialog box's background colour
  49247. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49248. close button to be triggered
  49249. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49250. a corner resizer
  49251. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49252. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49253. */
  49254. static void showDialog (const String& dialogTitle,
  49255. Component* contentComponent,
  49256. Component* componentToCentreAround,
  49257. const Colour& backgroundColour,
  49258. bool escapeKeyTriggersCloseButton,
  49259. bool shouldBeResizable = false,
  49260. bool useBottomRightCornerResizer = false);
  49261. /** Easy way of quickly showing a dialog box containing a given component.
  49262. This will open and display a DialogWindow containing a given component, returning
  49263. when the user clicks its close button.
  49264. It returns the value that was returned by the dialog box's runModalLoop() call.
  49265. To close the dialog programatically, you should call exitModalState (returnValue) on
  49266. the DialogWindow that is created. To find a pointer to this window from your
  49267. contentComponent, you can do something like this:
  49268. @code
  49269. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  49270. if (dw != nullptr)
  49271. dw->exitModalState (1234);
  49272. @endcode
  49273. @param dialogTitle the dialog box's title
  49274. @param contentComponent the content component for the dialog box. Make sure
  49275. that this has been set to the size you want it to
  49276. be before calling this method. The component won't
  49277. be deleted by this call, so you can re-use it or delete
  49278. it afterwards
  49279. @param componentToCentreAround if this is non-zero, it indicates a component that
  49280. you'd like to show this dialog box in front of. See the
  49281. DocumentWindow::centreAroundComponent() method for more
  49282. info on this parameter
  49283. @param backgroundColour a colour to use for the dialog box's background colour
  49284. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49285. close button to be triggered
  49286. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49287. a corner resizer
  49288. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49289. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49290. */
  49291. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  49292. static int showModalDialog (const String& dialogTitle,
  49293. Component* contentComponent,
  49294. Component* componentToCentreAround,
  49295. const Colour& backgroundColour,
  49296. bool escapeKeyTriggersCloseButton,
  49297. bool shouldBeResizable = false,
  49298. bool useBottomRightCornerResizer = false);
  49299. #endif
  49300. protected:
  49301. /** @internal */
  49302. void resized();
  49303. private:
  49304. bool escapeKeyTriggersCloseButton;
  49305. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  49306. };
  49307. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  49308. /*** End of inlined file: juce_DialogWindow.h ***/
  49309. #endif
  49310. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  49311. #endif
  49312. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49313. /*** Start of inlined file: juce_NativeMessageBox.h ***/
  49314. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49315. #define __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49316. class NativeMessageBox
  49317. {
  49318. public:
  49319. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  49320. If the callback parameter is null, the box is shown modally, and the method will
  49321. block until the user has clicked the button (or pressed the escape or return keys).
  49322. If the callback parameter is non-null, the box will be displayed and placed into a
  49323. modal state, but this method will return immediately, and the callback will be invoked
  49324. later when the user dismisses the box.
  49325. @param iconType the type of icon to show
  49326. @param title the headline to show at the top of the box
  49327. @param message a longer, more descriptive message to show underneath the title
  49328. @param associatedComponent if this is non-null, it specifies the component that the
  49329. alert window should be associated with. Depending on the look
  49330. and feel, this might be used for positioning of the alert window.
  49331. */
  49332. #if JUCE_MODAL_LOOPS_PERMITTED
  49333. static void JUCE_CALLTYPE showMessageBox (AlertWindow::AlertIconType iconType,
  49334. const String& title,
  49335. const String& message,
  49336. Component* associatedComponent = nullptr);
  49337. #endif
  49338. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  49339. If the callback parameter is null, the box is shown modally, and the method will
  49340. block until the user has clicked the button (or pressed the escape or return keys).
  49341. If the callback parameter is non-null, the box will be displayed and placed into a
  49342. modal state, but this method will return immediately, and the callback will be invoked
  49343. later when the user dismisses the box.
  49344. @param iconType the type of icon to show
  49345. @param title the headline to show at the top of the box
  49346. @param message a longer, more descriptive message to show underneath the title
  49347. @param associatedComponent if this is non-null, it specifies the component that the
  49348. alert window should be associated with. Depending on the look
  49349. and feel, this might be used for positioning of the alert window.
  49350. */
  49351. static void JUCE_CALLTYPE showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  49352. const String& title,
  49353. const String& message,
  49354. Component* associatedComponent = nullptr);
  49355. /** Shows a dialog box with two buttons.
  49356. Ideal for ok/cancel or yes/no choices. The return key can also be used
  49357. to trigger the first button, and the escape key for the second button.
  49358. If the callback parameter is null, the box is shown modally, and the method will
  49359. block until the user has clicked the button (or pressed the escape or return keys).
  49360. If the callback parameter is non-null, the box will be displayed and placed into a
  49361. modal state, but this method will return immediately, and the callback will be invoked
  49362. later when the user dismisses the box.
  49363. @param iconType the type of icon to show
  49364. @param title the headline to show at the top of the box
  49365. @param message a longer, more descriptive message to show underneath the title
  49366. @param associatedComponent if this is non-null, it specifies the component that the
  49367. alert window should be associated with. Depending on the look
  49368. and feel, this might be used for positioning of the alert window.
  49369. @param callback if this is non-null, the menu will be launched asynchronously,
  49370. returning immediately, and the callback will receive a call to its
  49371. modalStateFinished() when the box is dismissed, with its parameter
  49372. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  49373. will be owned and deleted by the system, so make sure that it works
  49374. safely and doesn't keep any references to objects that might be deleted
  49375. before it gets called.
  49376. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  49377. is not null, the method always returns false, and the user's choice is delivered
  49378. later by the callback.
  49379. */
  49380. static bool JUCE_CALLTYPE showOkCancelBox (AlertWindow::AlertIconType iconType,
  49381. const String& title,
  49382. const String& message,
  49383. #if JUCE_MODAL_LOOPS_PERMITTED
  49384. Component* associatedComponent = nullptr,
  49385. ModalComponentManager::Callback* callback = nullptr);
  49386. #else
  49387. Component* associatedComponent,
  49388. ModalComponentManager::Callback* callback);
  49389. #endif
  49390. /** Shows a dialog box with three buttons.
  49391. Ideal for yes/no/cancel boxes.
  49392. The escape key can be used to trigger the third button.
  49393. If the callback parameter is null, the box is shown modally, and the method will
  49394. block until the user has clicked the button (or pressed the escape or return keys).
  49395. If the callback parameter is non-null, the box will be displayed and placed into a
  49396. modal state, but this method will return immediately, and the callback will be invoked
  49397. later when the user dismisses the box.
  49398. @param iconType the type of icon to show
  49399. @param title the headline to show at the top of the box
  49400. @param message a longer, more descriptive message to show underneath the title
  49401. @param associatedComponent if this is non-null, it specifies the component that the
  49402. alert window should be associated with. Depending on the look
  49403. and feel, this might be used for positioning of the alert window.
  49404. @param callback if this is non-null, the menu will be launched asynchronously,
  49405. returning immediately, and the callback will receive a call to its
  49406. modalStateFinished() when the box is dismissed, with its parameter
  49407. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  49408. if it was cancelled, The callback object will be owned and deleted by the
  49409. system, so make sure that it works safely and doesn't keep any references
  49410. to objects that might be deleted before it gets called.
  49411. @returns If the callback parameter has been set, this returns 0. Otherwise, it returns one
  49412. of the following values:
  49413. - 0 if 'cancel' was pressed
  49414. - 1 if 'yes' was pressed
  49415. - 2 if 'no' was pressed
  49416. */
  49417. static int JUCE_CALLTYPE showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  49418. const String& title,
  49419. const String& message,
  49420. #if JUCE_MODAL_LOOPS_PERMITTED
  49421. Component* associatedComponent = nullptr,
  49422. ModalComponentManager::Callback* callback = nullptr);
  49423. #else
  49424. Component* associatedComponent,
  49425. ModalComponentManager::Callback* callback);
  49426. #endif
  49427. };
  49428. #endif // __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49429. /*** End of inlined file: juce_NativeMessageBox.h ***/
  49430. #endif
  49431. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  49432. #endif
  49433. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  49434. /*** Start of inlined file: juce_SplashScreen.h ***/
  49435. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  49436. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  49437. /** A component for showing a splash screen while your app starts up.
  49438. This will automatically position itself, and delete itself when the app has
  49439. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  49440. this).
  49441. To use it, just create one of these in your JUCEApplication::initialise() method,
  49442. call its show() method and let the object delete itself later.
  49443. E.g. @code
  49444. void MyApp::initialise (const String& commandLine)
  49445. {
  49446. SplashScreen* splash = new SplashScreen();
  49447. splash->show ("welcome to my app",
  49448. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  49449. 4000, false);
  49450. .. no need to delete the splash screen - it'll do that itself.
  49451. }
  49452. @endcode
  49453. */
  49454. class JUCE_API SplashScreen : public Component,
  49455. public Timer,
  49456. private DeletedAtShutdown
  49457. {
  49458. public:
  49459. /** Creates a SplashScreen object.
  49460. After creating one of these (or your subclass of it), call one of the show()
  49461. methods to display it.
  49462. */
  49463. SplashScreen();
  49464. /** Destructor. */
  49465. ~SplashScreen();
  49466. /** Creates a SplashScreen object that will display an image.
  49467. As soon as this is called, the SplashScreen will be displayed in the centre of the
  49468. screen. This method will also dispatch any pending messages to make sure that when
  49469. it returns, the splash screen has been completely drawn, and your initialisation
  49470. code can carry on.
  49471. @param title the name to give the component
  49472. @param backgroundImage an image to draw on the component. The component's size
  49473. will be set to the size of this image, and if the image is
  49474. semi-transparent, the component will be made semi-transparent
  49475. too. This image will be deleted (or released from the ImageCache
  49476. if that's how it was created) by the splash screen object when
  49477. it is itself deleted.
  49478. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  49479. should stay visible for. If the initialisation takes longer than
  49480. this time, the splash screen will wait for it to finish before
  49481. disappearing, but if initialisation is very quick, this lets
  49482. you make sure that people get a good look at your splash.
  49483. @param useDropShadow if true, the window will have a drop shadow
  49484. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  49485. the mouse (anywhere)
  49486. */
  49487. void show (const String& title,
  49488. const Image& backgroundImage,
  49489. int minimumTimeToDisplayFor,
  49490. bool useDropShadow,
  49491. bool removeOnMouseClick = true);
  49492. /** Creates a SplashScreen object with a specified size.
  49493. For a custom splash screen, you can use this method to display it at a certain size
  49494. and then override the paint() method yourself to do whatever's necessary.
  49495. As soon as this is called, the SplashScreen will be displayed in the centre of the
  49496. screen. This method will also dispatch any pending messages to make sure that when
  49497. it returns, the splash screen has been completely drawn, and your initialisation
  49498. code can carry on.
  49499. @param title the name to give the component
  49500. @param width the width to use
  49501. @param height the height to use
  49502. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  49503. should stay visible for. If the initialisation takes longer than
  49504. this time, the splash screen will wait for it to finish before
  49505. disappearing, but if initialisation is very quick, this lets
  49506. you make sure that people get a good look at your splash.
  49507. @param useDropShadow if true, the window will have a drop shadow
  49508. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  49509. the mouse (anywhere)
  49510. */
  49511. void show (const String& title,
  49512. int width,
  49513. int height,
  49514. int minimumTimeToDisplayFor,
  49515. bool useDropShadow,
  49516. bool removeOnMouseClick = true);
  49517. /** @internal */
  49518. void paint (Graphics& g);
  49519. /** @internal */
  49520. void timerCallback();
  49521. private:
  49522. Image backgroundImage;
  49523. Time earliestTimeToDelete;
  49524. int originalClickCounter;
  49525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  49526. };
  49527. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  49528. /*** End of inlined file: juce_SplashScreen.h ***/
  49529. #endif
  49530. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49531. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  49532. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49533. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49534. /**
  49535. A thread that automatically pops up a modal dialog box with a progress bar
  49536. and cancel button while it's busy running.
  49537. These are handy for performing some sort of task while giving the user feedback
  49538. about how long there is to go, etc.
  49539. E.g. @code
  49540. class MyTask : public ThreadWithProgressWindow
  49541. {
  49542. public:
  49543. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  49544. {
  49545. }
  49546. ~MyTask()
  49547. {
  49548. }
  49549. void run()
  49550. {
  49551. for (int i = 0; i < thingsToDo; ++i)
  49552. {
  49553. // must check this as often as possible, because this is
  49554. // how we know if the user's pressed 'cancel'
  49555. if (threadShouldExit())
  49556. break;
  49557. // this will update the progress bar on the dialog box
  49558. setProgress (i / (double) thingsToDo);
  49559. // ... do the business here...
  49560. }
  49561. }
  49562. };
  49563. void doTheTask()
  49564. {
  49565. MyTask m;
  49566. if (m.runThread())
  49567. {
  49568. // thread finished normally..
  49569. }
  49570. else
  49571. {
  49572. // user pressed the cancel button..
  49573. }
  49574. }
  49575. @endcode
  49576. @see Thread, AlertWindow
  49577. */
  49578. class JUCE_API ThreadWithProgressWindow : public Thread,
  49579. private Timer
  49580. {
  49581. public:
  49582. /** Creates the thread.
  49583. Initially, the dialog box won't be visible, it'll only appear when the
  49584. runThread() method is called.
  49585. @param windowTitle the title to go at the top of the dialog box
  49586. @param hasProgressBar whether the dialog box should have a progress bar (see
  49587. setProgress() )
  49588. @param hasCancelButton whether the dialog box should have a cancel button
  49589. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  49590. the thread to stop before killing it forcibly (see
  49591. Thread::stopThread() )
  49592. @param cancelButtonText the text that should be shown in the cancel button
  49593. (if it has one)
  49594. */
  49595. ThreadWithProgressWindow (const String& windowTitle,
  49596. bool hasProgressBar,
  49597. bool hasCancelButton,
  49598. int timeOutMsWhenCancelling = 10000,
  49599. const String& cancelButtonText = "Cancel");
  49600. /** Destructor. */
  49601. ~ThreadWithProgressWindow();
  49602. /** Starts the thread and waits for it to finish.
  49603. This will start the thread, make the dialog box appear, and wait until either
  49604. the thread finishes normally, or until the cancel button is pressed.
  49605. Before returning, the dialog box will be hidden.
  49606. @param threadPriority the priority to use when starting the thread - see
  49607. Thread::startThread() for values
  49608. @returns true if the thread finished normally; false if the user pressed cancel
  49609. */
  49610. bool runThread (int threadPriority = 5);
  49611. /** The thread should call this periodically to update the position of the progress bar.
  49612. @param newProgress the progress, from 0.0 to 1.0
  49613. @see setStatusMessage
  49614. */
  49615. void setProgress (double newProgress);
  49616. /** The thread can call this to change the message that's displayed in the dialog box.
  49617. */
  49618. void setStatusMessage (const String& newStatusMessage);
  49619. /** Returns the AlertWindow that is being used.
  49620. */
  49621. AlertWindow* getAlertWindow() const noexcept { return alertWindow; }
  49622. private:
  49623. void timerCallback();
  49624. double progress;
  49625. ScopedPointer <AlertWindow> alertWindow;
  49626. String message;
  49627. CriticalSection messageLock;
  49628. const int timeOutMsWhenCancelling;
  49629. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  49630. };
  49631. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49632. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  49633. #endif
  49634. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  49635. #endif
  49636. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  49637. #endif
  49638. #ifndef __JUCE_COLOUR_JUCEHEADER__
  49639. #endif
  49640. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  49641. #endif
  49642. #ifndef __JUCE_COLOURS_JUCEHEADER__
  49643. #endif
  49644. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  49645. #endif
  49646. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  49647. /*** Start of inlined file: juce_EdgeTable.h ***/
  49648. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  49649. #define __JUCE_EDGETABLE_JUCEHEADER__
  49650. class Path;
  49651. class Image;
  49652. /**
  49653. A table of horizontal scan-line segments - used for rasterising Paths.
  49654. @see Path, Graphics
  49655. */
  49656. class JUCE_API EdgeTable
  49657. {
  49658. public:
  49659. /** Creates an edge table containing a path.
  49660. A table is created with a fixed vertical range, and only sections of the path
  49661. which lie within this range will be added to the table.
  49662. @param clipLimits only the region of the path that lies within this area will be added
  49663. @param pathToAdd the path to add to the table
  49664. @param transform a transform to apply to the path being added
  49665. */
  49666. EdgeTable (const Rectangle<int>& clipLimits,
  49667. const Path& pathToAdd,
  49668. const AffineTransform& transform);
  49669. /** Creates an edge table containing a rectangle. */
  49670. EdgeTable (const Rectangle<int>& rectangleToAdd);
  49671. /** Creates an edge table containing a rectangle list. */
  49672. EdgeTable (const RectangleList& rectanglesToAdd);
  49673. /** Creates an edge table containing a rectangle. */
  49674. EdgeTable (const Rectangle<float>& rectangleToAdd);
  49675. /** Creates a copy of another edge table. */
  49676. EdgeTable (const EdgeTable& other);
  49677. /** Copies from another edge table. */
  49678. EdgeTable& operator= (const EdgeTable& other);
  49679. /** Destructor. */
  49680. ~EdgeTable();
  49681. void clipToRectangle (const Rectangle<int>& r);
  49682. void excludeRectangle (const Rectangle<int>& r);
  49683. void clipToEdgeTable (const EdgeTable& other);
  49684. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  49685. bool isEmpty() noexcept;
  49686. const Rectangle<int>& getMaximumBounds() const noexcept { return bounds; }
  49687. void translate (float dx, int dy) noexcept;
  49688. /** Reduces the amount of space the table has allocated.
  49689. This will shrink the table down to use as little memory as possible - useful for
  49690. read-only tables that get stored and re-used for rendering.
  49691. */
  49692. void optimiseTable();
  49693. /** Iterates the lines in the table, for rendering.
  49694. This function will iterate each line in the table, and call a user-defined class
  49695. to render each pixel or continuous line of pixels that the table contains.
  49696. @param iterationCallback this templated class must contain the following methods:
  49697. @code
  49698. inline void setEdgeTableYPos (int y);
  49699. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  49700. inline void handleEdgeTablePixelFull (int x) const;
  49701. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  49702. inline void handleEdgeTableLineFull (int x, int width) const;
  49703. @endcode
  49704. (these don't necessarily have to be 'const', but it might help it go faster)
  49705. */
  49706. template <class EdgeTableIterationCallback>
  49707. void iterate (EdgeTableIterationCallback& iterationCallback) const noexcept
  49708. {
  49709. const int* lineStart = table;
  49710. for (int y = 0; y < bounds.getHeight(); ++y)
  49711. {
  49712. const int* line = lineStart;
  49713. lineStart += lineStrideElements;
  49714. int numPoints = line[0];
  49715. if (--numPoints > 0)
  49716. {
  49717. int x = *++line;
  49718. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  49719. int levelAccumulator = 0;
  49720. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  49721. while (--numPoints >= 0)
  49722. {
  49723. const int level = *++line;
  49724. jassert (isPositiveAndBelow (level, (int) 256));
  49725. const int endX = *++line;
  49726. jassert (endX >= x);
  49727. const int endOfRun = (endX >> 8);
  49728. if (endOfRun == (x >> 8))
  49729. {
  49730. // small segment within the same pixel, so just save it for the next
  49731. // time round..
  49732. levelAccumulator += (endX - x) * level;
  49733. }
  49734. else
  49735. {
  49736. // plot the fist pixel of this segment, including any accumulated
  49737. // levels from smaller segments that haven't been drawn yet
  49738. levelAccumulator += (0x100 - (x & 0xff)) * level;
  49739. levelAccumulator >>= 8;
  49740. x >>= 8;
  49741. if (levelAccumulator > 0)
  49742. {
  49743. if (levelAccumulator >= 255)
  49744. iterationCallback.handleEdgeTablePixelFull (x);
  49745. else
  49746. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  49747. }
  49748. // if there's a run of similar pixels, do it all in one go..
  49749. if (level > 0)
  49750. {
  49751. jassert (endOfRun <= bounds.getRight());
  49752. const int numPix = endOfRun - ++x;
  49753. if (numPix > 0)
  49754. iterationCallback.handleEdgeTableLine (x, numPix, level);
  49755. }
  49756. // save the bit at the end to be drawn next time round the loop.
  49757. levelAccumulator = (endX & 0xff) * level;
  49758. }
  49759. x = endX;
  49760. }
  49761. levelAccumulator >>= 8;
  49762. if (levelAccumulator > 0)
  49763. {
  49764. x >>= 8;
  49765. jassert (x >= bounds.getX() && x < bounds.getRight());
  49766. if (levelAccumulator >= 255)
  49767. iterationCallback.handleEdgeTablePixelFull (x);
  49768. else
  49769. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  49770. }
  49771. }
  49772. }
  49773. }
  49774. private:
  49775. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  49776. HeapBlock<int> table;
  49777. Rectangle<int> bounds;
  49778. int maxEdgesPerLine, lineStrideElements;
  49779. bool needToCheckEmptinesss;
  49780. void addEdgePoint (int x, int y, int winding);
  49781. void remapTableForNumEdges (int newNumEdgesPerLine);
  49782. void intersectWithEdgeTableLine (int y, const int* otherLine);
  49783. void clipEdgeTableLineToRange (int* line, int x1, int x2) noexcept;
  49784. void sanitiseLevels (bool useNonZeroWinding) noexcept;
  49785. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) noexcept;
  49786. JUCE_LEAK_DETECTOR (EdgeTable);
  49787. };
  49788. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  49789. /*** End of inlined file: juce_EdgeTable.h ***/
  49790. #endif
  49791. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49792. /*** Start of inlined file: juce_FillType.h ***/
  49793. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49794. #define __JUCE_FILLTYPE_JUCEHEADER__
  49795. /**
  49796. Represents a colour or fill pattern to use for rendering paths.
  49797. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  49798. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  49799. @see Graphics::setFillType, DrawablePath::setFill
  49800. */
  49801. class JUCE_API FillType
  49802. {
  49803. public:
  49804. /** Creates a default fill type, of solid black. */
  49805. FillType() noexcept;
  49806. /** Creates a fill type of a solid colour.
  49807. @see setColour
  49808. */
  49809. FillType (const Colour& colour) noexcept;
  49810. /** Creates a gradient fill type.
  49811. @see setGradient
  49812. */
  49813. FillType (const ColourGradient& gradient);
  49814. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  49815. and rotation of the pattern.
  49816. @see setTiledImage
  49817. */
  49818. FillType (const Image& image, const AffineTransform& transform) noexcept;
  49819. /** Creates a copy of another FillType. */
  49820. FillType (const FillType& other);
  49821. /** Makes a copy of another FillType. */
  49822. FillType& operator= (const FillType& other);
  49823. /** Destructor. */
  49824. ~FillType() noexcept;
  49825. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  49826. bool isColour() const noexcept { return gradient == nullptr && image.isNull(); }
  49827. /** Returns true if this is a gradient fill. */
  49828. bool isGradient() const noexcept { return gradient != nullptr; }
  49829. /** Returns true if this is a tiled image pattern fill. */
  49830. bool isTiledImage() const noexcept { return image.isValid(); }
  49831. /** Turns this object into a solid colour fill.
  49832. If the object was an image or gradient, those fields will no longer be valid. */
  49833. void setColour (const Colour& newColour) noexcept;
  49834. /** Turns this object into a gradient fill. */
  49835. void setGradient (const ColourGradient& newGradient);
  49836. /** Turns this object into a tiled image fill type. The transform allows you to set
  49837. the scaling, offset and rotation of the pattern.
  49838. */
  49839. void setTiledImage (const Image& image, const AffineTransform& transform) noexcept;
  49840. /** Changes the opacity that should be used.
  49841. If the fill is a solid colour, this just changes the opacity of that colour. For
  49842. gradients and image tiles, it changes the opacity that will be used for them.
  49843. */
  49844. void setOpacity (float newOpacity) noexcept;
  49845. /** Returns the current opacity to be applied to the colour, gradient, or image.
  49846. @see setOpacity
  49847. */
  49848. float getOpacity() const noexcept { return colour.getFloatAlpha(); }
  49849. /** Returns true if this fill type is completely transparent. */
  49850. bool isInvisible() const noexcept;
  49851. /** The solid colour being used.
  49852. If the fill type is not a solid colour, the alpha channel of this colour indicates
  49853. the opacity that should be used for the fill, and the RGB channels are ignored.
  49854. */
  49855. Colour colour;
  49856. /** Returns the gradient that should be used for filling.
  49857. This will be zero if the object is some other type of fill.
  49858. If a gradient is active, the overall opacity with which it should be applied
  49859. is indicated by the alpha channel of the colour variable.
  49860. */
  49861. ScopedPointer <ColourGradient> gradient;
  49862. /** The image that should be used for tiling.
  49863. If an image fill is active, the overall opacity with which it should be applied
  49864. is indicated by the alpha channel of the colour variable.
  49865. */
  49866. Image image;
  49867. /** The transform that should be applied to the image or gradient that's being drawn. */
  49868. AffineTransform transform;
  49869. bool operator== (const FillType& other) const;
  49870. bool operator!= (const FillType& other) const;
  49871. private:
  49872. JUCE_LEAK_DETECTOR (FillType);
  49873. };
  49874. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  49875. /*** End of inlined file: juce_FillType.h ***/
  49876. #endif
  49877. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  49878. #endif
  49879. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  49880. #endif
  49881. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49882. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  49883. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49884. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49885. /**
  49886. Interface class for graphics context objects, used internally by the Graphics class.
  49887. Users are not supposed to create instances of this class directly - do your drawing
  49888. via the Graphics object instead.
  49889. It's a base class for different types of graphics context, that may perform software-based
  49890. or OS-accelerated rendering.
  49891. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  49892. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  49893. context.
  49894. */
  49895. class JUCE_API LowLevelGraphicsContext
  49896. {
  49897. protected:
  49898. LowLevelGraphicsContext();
  49899. public:
  49900. virtual ~LowLevelGraphicsContext();
  49901. /** Returns true if this device is vector-based, e.g. a printer. */
  49902. virtual bool isVectorDevice() const = 0;
  49903. /** Moves the origin to a new position.
  49904. The co-ords are relative to the current origin, and indicate the new position
  49905. of (0, 0).
  49906. */
  49907. virtual void setOrigin (int x, int y) = 0;
  49908. virtual void addTransform (const AffineTransform& transform) = 0;
  49909. virtual float getScaleFactor() = 0;
  49910. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  49911. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  49912. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  49913. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  49914. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  49915. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  49916. virtual const Rectangle<int> getClipBounds() const = 0;
  49917. virtual bool isClipEmpty() const = 0;
  49918. virtual void saveState() = 0;
  49919. virtual void restoreState() = 0;
  49920. virtual void beginTransparencyLayer (float opacity) = 0;
  49921. virtual void endTransparencyLayer() = 0;
  49922. virtual void setFill (const FillType& fillType) = 0;
  49923. virtual void setOpacity (float newOpacity) = 0;
  49924. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  49925. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  49926. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  49927. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  49928. virtual void drawLine (const Line <float>& line) = 0;
  49929. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  49930. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  49931. virtual void setFont (const Font& newFont) = 0;
  49932. virtual const Font getFont() = 0;
  49933. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  49934. };
  49935. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49936. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  49937. #endif
  49938. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49939. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49940. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49941. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49942. /**
  49943. An implementation of LowLevelGraphicsContext that turns the drawing operations
  49944. into a PostScript document.
  49945. */
  49946. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  49947. {
  49948. public:
  49949. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  49950. const String& documentTitle,
  49951. int totalWidth,
  49952. int totalHeight);
  49953. ~LowLevelGraphicsPostScriptRenderer();
  49954. bool isVectorDevice() const;
  49955. void setOrigin (int x, int y);
  49956. void addTransform (const AffineTransform& transform);
  49957. float getScaleFactor();
  49958. bool clipToRectangle (const Rectangle<int>& r);
  49959. bool clipToRectangleList (const RectangleList& clipRegion);
  49960. void excludeClipRectangle (const Rectangle<int>& r);
  49961. void clipToPath (const Path& path, const AffineTransform& transform);
  49962. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49963. void saveState();
  49964. void restoreState();
  49965. void beginTransparencyLayer (float opacity);
  49966. void endTransparencyLayer();
  49967. bool clipRegionIntersects (const Rectangle<int>& r);
  49968. const Rectangle<int> getClipBounds() const;
  49969. bool isClipEmpty() const;
  49970. void setFill (const FillType& fillType);
  49971. void setOpacity (float opacity);
  49972. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49973. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49974. void fillPath (const Path& path, const AffineTransform& transform);
  49975. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49976. void drawLine (const Line <float>& line);
  49977. void drawVerticalLine (int x, float top, float bottom);
  49978. void drawHorizontalLine (int x, float top, float bottom);
  49979. const Font getFont();
  49980. void setFont (const Font& newFont);
  49981. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49982. protected:
  49983. OutputStream& out;
  49984. int totalWidth, totalHeight;
  49985. bool needToClip;
  49986. Colour lastColour;
  49987. struct SavedState
  49988. {
  49989. SavedState();
  49990. ~SavedState();
  49991. RectangleList clip;
  49992. int xOffset, yOffset;
  49993. FillType fillType;
  49994. Font font;
  49995. private:
  49996. SavedState& operator= (const SavedState&);
  49997. };
  49998. OwnedArray <SavedState> stateStack;
  49999. void writeClip();
  50000. void writeColour (const Colour& colour);
  50001. void writePath (const Path& path) const;
  50002. void writeXY (float x, float y) const;
  50003. void writeTransform (const AffineTransform& trans) const;
  50004. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  50005. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  50006. };
  50007. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50008. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50009. #endif
  50010. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50011. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50012. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50013. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50014. /**
  50015. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  50016. its rendering in memory.
  50017. User code is not supposed to create instances of this class directly - do all your
  50018. rendering via the Graphics class instead.
  50019. */
  50020. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  50021. {
  50022. public:
  50023. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  50024. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  50025. ~LowLevelGraphicsSoftwareRenderer();
  50026. bool isVectorDevice() const;
  50027. void setOrigin (int x, int y);
  50028. void addTransform (const AffineTransform& transform);
  50029. float getScaleFactor();
  50030. bool clipToRectangle (const Rectangle<int>& r);
  50031. bool clipToRectangleList (const RectangleList& clipRegion);
  50032. void excludeClipRectangle (const Rectangle<int>& r);
  50033. void clipToPath (const Path& path, const AffineTransform& transform);
  50034. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50035. bool clipRegionIntersects (const Rectangle<int>& r);
  50036. const Rectangle<int> getClipBounds() const;
  50037. bool isClipEmpty() const;
  50038. void saveState();
  50039. void restoreState();
  50040. void beginTransparencyLayer (float opacity);
  50041. void endTransparencyLayer();
  50042. void setFill (const FillType& fillType);
  50043. void setOpacity (float opacity);
  50044. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50045. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50046. void fillPath (const Path& path, const AffineTransform& transform);
  50047. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50048. void drawLine (const Line <float>& line);
  50049. void drawVerticalLine (int x, float top, float bottom);
  50050. void drawHorizontalLine (int x, float top, float bottom);
  50051. void setFont (const Font& newFont);
  50052. const Font getFont();
  50053. void drawGlyph (int glyphNumber, float x, float y);
  50054. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50055. protected:
  50056. Image image;
  50057. class GlyphCache;
  50058. class CachedGlyph;
  50059. class SavedState;
  50060. friend class ScopedPointer <SavedState>;
  50061. friend class OwnedArray <SavedState>;
  50062. friend class OwnedArray <CachedGlyph>;
  50063. ScopedPointer <SavedState> currentState;
  50064. OwnedArray <SavedState> stateStack;
  50065. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  50066. };
  50067. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50068. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50069. #endif
  50070. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  50071. #endif
  50072. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  50073. #endif
  50074. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50075. /*** Start of inlined file: juce_DrawableComposite.h ***/
  50076. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50077. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50078. /**
  50079. A drawable object which acts as a container for a set of other Drawables.
  50080. @see Drawable
  50081. */
  50082. class JUCE_API DrawableComposite : public Drawable
  50083. {
  50084. public:
  50085. /** Creates a composite Drawable. */
  50086. DrawableComposite();
  50087. /** Creates a copy of a DrawableComposite. */
  50088. DrawableComposite (const DrawableComposite& other);
  50089. /** Destructor. */
  50090. ~DrawableComposite();
  50091. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  50092. @see setContentArea
  50093. */
  50094. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  50095. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  50096. @see setBoundingBox
  50097. */
  50098. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50099. /** Changes the bounding box transform to match the content area, so that any sub-items will
  50100. be drawn at their untransformed positions.
  50101. */
  50102. void resetBoundingBoxToContentArea();
  50103. /** Returns the main content rectangle.
  50104. The content area is actually defined by the markers named "left", "right", "top" and
  50105. "bottom", but this method is a shortcut that returns them all at once.
  50106. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  50107. */
  50108. const RelativeRectangle getContentArea() const;
  50109. /** Changes the main content area.
  50110. The content area is actually defined by the markers named "left", "right", "top" and
  50111. "bottom", but this method is a shortcut that sets them all at once.
  50112. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  50113. */
  50114. void setContentArea (const RelativeRectangle& newArea);
  50115. /** Resets the content area and the bounding transform to fit around the area occupied
  50116. by the child components (ignoring any markers).
  50117. */
  50118. void resetContentAreaAndBoundingBoxToFitChildren();
  50119. /** The name of the marker that defines the left edge of the content area. */
  50120. static const char* const contentLeftMarkerName;
  50121. /** The name of the marker that defines the right edge of the content area. */
  50122. static const char* const contentRightMarkerName;
  50123. /** The name of the marker that defines the top edge of the content area. */
  50124. static const char* const contentTopMarkerName;
  50125. /** The name of the marker that defines the bottom edge of the content area. */
  50126. static const char* const contentBottomMarkerName;
  50127. /** @internal */
  50128. Drawable* createCopy() const;
  50129. /** @internal */
  50130. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50131. /** @internal */
  50132. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50133. /** @internal */
  50134. static const Identifier valueTreeType;
  50135. /** @internal */
  50136. const Rectangle<float> getDrawableBounds() const;
  50137. /** @internal */
  50138. void childBoundsChanged (Component*);
  50139. /** @internal */
  50140. void childrenChanged();
  50141. /** @internal */
  50142. void parentHierarchyChanged();
  50143. /** @internal */
  50144. MarkerList* getMarkers (bool xAxis);
  50145. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  50146. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50147. {
  50148. public:
  50149. ValueTreeWrapper (const ValueTree& state);
  50150. ValueTree getChildList() const;
  50151. ValueTree getChildListCreating (UndoManager* undoManager);
  50152. const RelativeParallelogram getBoundingBox() const;
  50153. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50154. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  50155. const RelativeRectangle getContentArea() const;
  50156. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  50157. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  50158. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  50159. static const Identifier topLeft, topRight, bottomLeft;
  50160. private:
  50161. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  50162. };
  50163. private:
  50164. RelativeParallelogram bounds;
  50165. MarkerList markersX, markersY;
  50166. bool updateBoundsReentrant;
  50167. friend class Drawable::Positioner<DrawableComposite>;
  50168. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50169. void recalculateCoordinates (Expression::Scope*);
  50170. void updateBoundsToFitChildren();
  50171. DrawableComposite& operator= (const DrawableComposite&);
  50172. JUCE_LEAK_DETECTOR (DrawableComposite);
  50173. };
  50174. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50175. /*** End of inlined file: juce_DrawableComposite.h ***/
  50176. #endif
  50177. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50178. /*** Start of inlined file: juce_DrawableImage.h ***/
  50179. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50180. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50181. /**
  50182. A drawable object which is a bitmap image.
  50183. @see Drawable
  50184. */
  50185. class JUCE_API DrawableImage : public Drawable
  50186. {
  50187. public:
  50188. DrawableImage();
  50189. DrawableImage (const DrawableImage& other);
  50190. /** Destructor. */
  50191. ~DrawableImage();
  50192. /** Sets the image that this drawable will render. */
  50193. void setImage (const Image& imageToUse);
  50194. /** Returns the current image. */
  50195. const Image getImage() const { return image; }
  50196. /** Sets the opacity to use when drawing the image. */
  50197. void setOpacity (float newOpacity);
  50198. /** Returns the image's opacity. */
  50199. float getOpacity() const noexcept { return opacity; }
  50200. /** Sets a colour to draw over the image's alpha channel.
  50201. By default this is transparent so isn't drawn, but if you set a non-transparent
  50202. colour here, then it will be overlaid on the image, using the image's alpha
  50203. channel as a mask.
  50204. This is handy for doing things like darkening or lightening an image by overlaying
  50205. it with semi-transparent black or white.
  50206. */
  50207. void setOverlayColour (const Colour& newOverlayColour);
  50208. /** Returns the overlay colour. */
  50209. const Colour& getOverlayColour() const noexcept { return overlayColour; }
  50210. /** Sets the bounding box within which the image should be displayed. */
  50211. void setBoundingBox (const RelativeParallelogram& newBounds);
  50212. /** Returns the position to which the image's top-left corner should be remapped in the target
  50213. coordinate space when rendering this object.
  50214. @see setTransform
  50215. */
  50216. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50217. /** @internal */
  50218. void paint (Graphics& g);
  50219. /** @internal */
  50220. bool hitTest (int x, int y);
  50221. /** @internal */
  50222. Drawable* createCopy() const;
  50223. /** @internal */
  50224. const Rectangle<float> getDrawableBounds() const;
  50225. /** @internal */
  50226. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50227. /** @internal */
  50228. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50229. /** @internal */
  50230. static const Identifier valueTreeType;
  50231. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  50232. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50233. {
  50234. public:
  50235. ValueTreeWrapper (const ValueTree& state);
  50236. const var getImageIdentifier() const;
  50237. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  50238. Value getImageIdentifierValue (UndoManager* undoManager);
  50239. float getOpacity() const;
  50240. void setOpacity (float newOpacity, UndoManager* undoManager);
  50241. Value getOpacityValue (UndoManager* undoManager);
  50242. const Colour getOverlayColour() const;
  50243. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  50244. Value getOverlayColourValue (UndoManager* undoManager);
  50245. const RelativeParallelogram getBoundingBox() const;
  50246. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50247. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  50248. };
  50249. private:
  50250. Image image;
  50251. float opacity;
  50252. Colour overlayColour;
  50253. RelativeParallelogram bounds;
  50254. friend class Drawable::Positioner<DrawableImage>;
  50255. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50256. void recalculateCoordinates (Expression::Scope*);
  50257. DrawableImage& operator= (const DrawableImage&);
  50258. JUCE_LEAK_DETECTOR (DrawableImage);
  50259. };
  50260. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50261. /*** End of inlined file: juce_DrawableImage.h ***/
  50262. #endif
  50263. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50264. /*** Start of inlined file: juce_DrawablePath.h ***/
  50265. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50266. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  50267. /*** Start of inlined file: juce_DrawableShape.h ***/
  50268. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50269. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50270. /**
  50271. A base class implementing common functionality for Drawable classes which
  50272. consist of some kind of filled and stroked outline.
  50273. @see DrawablePath, DrawableRectangle
  50274. */
  50275. class JUCE_API DrawableShape : public Drawable
  50276. {
  50277. protected:
  50278. DrawableShape();
  50279. DrawableShape (const DrawableShape&);
  50280. public:
  50281. /** Destructor. */
  50282. ~DrawableShape();
  50283. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  50284. */
  50285. class RelativeFillType
  50286. {
  50287. public:
  50288. RelativeFillType();
  50289. RelativeFillType (const FillType& fill);
  50290. RelativeFillType (const RelativeFillType&);
  50291. RelativeFillType& operator= (const RelativeFillType&);
  50292. bool operator== (const RelativeFillType&) const;
  50293. bool operator!= (const RelativeFillType&) const;
  50294. bool isDynamic() const;
  50295. bool recalculateCoords (Expression::Scope* scope);
  50296. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  50297. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  50298. FillType fill;
  50299. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  50300. };
  50301. /** Sets a fill type for the path.
  50302. This colour is used to fill the path - if you don't want the path to be
  50303. filled (e.g. if you're just drawing an outline), set this to a transparent
  50304. colour.
  50305. @see setPath, setStrokeFill
  50306. */
  50307. void setFill (const FillType& newFill);
  50308. /** Sets a fill type for the path.
  50309. This colour is used to fill the path - if you don't want the path to be
  50310. filled (e.g. if you're just drawing an outline), set this to a transparent
  50311. colour.
  50312. @see setPath, setStrokeFill
  50313. */
  50314. void setFill (const RelativeFillType& newFill);
  50315. /** Returns the current fill type.
  50316. @see setFill
  50317. */
  50318. const RelativeFillType& getFill() const noexcept { return mainFill; }
  50319. /** Sets the fill type with which the outline will be drawn.
  50320. @see setFill
  50321. */
  50322. void setStrokeFill (const FillType& newStrokeFill);
  50323. /** Sets the fill type with which the outline will be drawn.
  50324. @see setFill
  50325. */
  50326. void setStrokeFill (const RelativeFillType& newStrokeFill);
  50327. /** Returns the current stroke fill.
  50328. @see setStrokeFill
  50329. */
  50330. const RelativeFillType& getStrokeFill() const noexcept { return strokeFill; }
  50331. /** Changes the properties of the outline that will be drawn around the path.
  50332. If the stroke has 0 thickness, no stroke will be drawn.
  50333. @see setStrokeThickness, setStrokeColour
  50334. */
  50335. void setStrokeType (const PathStrokeType& newStrokeType);
  50336. /** Changes the stroke thickness.
  50337. This is a shortcut for calling setStrokeType.
  50338. */
  50339. void setStrokeThickness (float newThickness);
  50340. /** Returns the current outline style. */
  50341. const PathStrokeType& getStrokeType() const noexcept { return strokeType; }
  50342. /** @internal */
  50343. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  50344. {
  50345. public:
  50346. FillAndStrokeState (const ValueTree& state);
  50347. ValueTree getFillState (const Identifier& fillOrStrokeType);
  50348. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  50349. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  50350. ComponentBuilder::ImageProvider*, UndoManager*);
  50351. const PathStrokeType getStrokeType() const;
  50352. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  50353. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  50354. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  50355. };
  50356. /** @internal */
  50357. const Rectangle<float> getDrawableBounds() const;
  50358. /** @internal */
  50359. void paint (Graphics& g);
  50360. /** @internal */
  50361. bool hitTest (int x, int y);
  50362. protected:
  50363. /** Called when the cached path should be updated. */
  50364. void pathChanged();
  50365. /** Called when the cached stroke should be updated. */
  50366. void strokeChanged();
  50367. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  50368. bool isStrokeVisible() const noexcept;
  50369. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  50370. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  50371. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  50372. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  50373. PathStrokeType strokeType;
  50374. Path path, strokePath;
  50375. private:
  50376. class RelativePositioner;
  50377. RelativeFillType mainFill, strokeFill;
  50378. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  50379. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  50380. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  50381. DrawableShape& operator= (const DrawableShape&);
  50382. };
  50383. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50384. /*** End of inlined file: juce_DrawableShape.h ***/
  50385. /**
  50386. A drawable object which renders a filled or outlined shape.
  50387. For details on how to change the fill and stroke, see the DrawableShape class.
  50388. @see Drawable, DrawableShape
  50389. */
  50390. class JUCE_API DrawablePath : public DrawableShape
  50391. {
  50392. public:
  50393. /** Creates a DrawablePath. */
  50394. DrawablePath();
  50395. DrawablePath (const DrawablePath& other);
  50396. /** Destructor. */
  50397. ~DrawablePath();
  50398. /** Changes the path that will be drawn.
  50399. @see setFillColour, setStrokeType
  50400. */
  50401. void setPath (const Path& newPath);
  50402. /** Sets the path using a RelativePointPath.
  50403. Calling this will set up a Component::Positioner to automatically update the path
  50404. if any of the points in the source path are dynamic.
  50405. */
  50406. void setPath (const RelativePointPath& newPath);
  50407. /** Returns the current path. */
  50408. const Path& getPath() const;
  50409. /** Returns the current path for the outline. */
  50410. const Path& getStrokePath() const;
  50411. /** @internal */
  50412. Drawable* createCopy() const;
  50413. /** @internal */
  50414. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50415. /** @internal */
  50416. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50417. /** @internal */
  50418. static const Identifier valueTreeType;
  50419. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  50420. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  50421. {
  50422. public:
  50423. ValueTreeWrapper (const ValueTree& state);
  50424. bool usesNonZeroWinding() const;
  50425. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  50426. class Element
  50427. {
  50428. public:
  50429. explicit Element (const ValueTree& state);
  50430. ~Element();
  50431. const Identifier getType() const noexcept { return state.getType(); }
  50432. int getNumControlPoints() const noexcept;
  50433. const RelativePoint getControlPoint (int index) const;
  50434. Value getControlPointValue (int index, UndoManager*) const;
  50435. const RelativePoint getStartPoint() const;
  50436. const RelativePoint getEndPoint() const;
  50437. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  50438. float getLength (Expression::Scope*) const;
  50439. ValueTreeWrapper getParent() const;
  50440. Element getPreviousElement() const;
  50441. const String getModeOfEndPoint() const;
  50442. void setModeOfEndPoint (const String& newMode, UndoManager*);
  50443. void convertToLine (UndoManager*);
  50444. void convertToCubic (Expression::Scope*, UndoManager*);
  50445. void convertToPathBreak (UndoManager* undoManager);
  50446. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  50447. void removePoint (UndoManager* undoManager);
  50448. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  50449. static const Identifier mode, startSubPathElement, closeSubPathElement,
  50450. lineToElement, quadraticToElement, cubicToElement;
  50451. static const char* cornerMode;
  50452. static const char* roundedMode;
  50453. static const char* symmetricMode;
  50454. ValueTree state;
  50455. };
  50456. ValueTree getPathState();
  50457. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  50458. void writeTo (RelativePointPath& path) const;
  50459. static const Identifier nonZeroWinding, point1, point2, point3;
  50460. };
  50461. private:
  50462. ScopedPointer<RelativePointPath> relativePath;
  50463. class RelativePositioner;
  50464. friend class RelativePositioner;
  50465. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  50466. DrawablePath& operator= (const DrawablePath&);
  50467. JUCE_LEAK_DETECTOR (DrawablePath);
  50468. };
  50469. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  50470. /*** End of inlined file: juce_DrawablePath.h ***/
  50471. #endif
  50472. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50473. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  50474. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50475. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50476. /**
  50477. A Drawable object which draws a rectangle.
  50478. For details on how to change the fill and stroke, see the DrawableShape class.
  50479. @see Drawable, DrawableShape
  50480. */
  50481. class JUCE_API DrawableRectangle : public DrawableShape
  50482. {
  50483. public:
  50484. DrawableRectangle();
  50485. DrawableRectangle (const DrawableRectangle& other);
  50486. /** Destructor. */
  50487. ~DrawableRectangle();
  50488. /** Sets the rectangle's bounds. */
  50489. void setRectangle (const RelativeParallelogram& newBounds);
  50490. /** Returns the rectangle's bounds. */
  50491. const RelativeParallelogram& getRectangle() const noexcept { return bounds; }
  50492. /** Returns the corner size to be used. */
  50493. const RelativePoint getCornerSize() const { return cornerSize; }
  50494. /** Sets a new corner size for the rectangle */
  50495. void setCornerSize (const RelativePoint& newSize);
  50496. /** @internal */
  50497. Drawable* createCopy() const;
  50498. /** @internal */
  50499. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50500. /** @internal */
  50501. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50502. /** @internal */
  50503. static const Identifier valueTreeType;
  50504. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  50505. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  50506. {
  50507. public:
  50508. ValueTreeWrapper (const ValueTree& state);
  50509. const RelativeParallelogram getRectangle() const;
  50510. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  50511. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  50512. const RelativePoint getCornerSize() const;
  50513. Value getCornerSizeValue (UndoManager*) const;
  50514. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  50515. };
  50516. private:
  50517. friend class Drawable::Positioner<DrawableRectangle>;
  50518. RelativeParallelogram bounds;
  50519. RelativePoint cornerSize;
  50520. void rebuildPath();
  50521. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50522. void recalculateCoordinates (Expression::Scope*);
  50523. DrawableRectangle& operator= (const DrawableRectangle&);
  50524. JUCE_LEAK_DETECTOR (DrawableRectangle);
  50525. };
  50526. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50527. /*** End of inlined file: juce_DrawableRectangle.h ***/
  50528. #endif
  50529. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50530. #endif
  50531. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  50532. /*** Start of inlined file: juce_DrawableText.h ***/
  50533. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  50534. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  50535. /**
  50536. A drawable object which renders a line of text.
  50537. @see Drawable
  50538. */
  50539. class JUCE_API DrawableText : public Drawable
  50540. {
  50541. public:
  50542. /** Creates a DrawableText object. */
  50543. DrawableText();
  50544. DrawableText (const DrawableText& other);
  50545. /** Destructor. */
  50546. ~DrawableText();
  50547. /** Sets the text to display.*/
  50548. void setText (const String& newText);
  50549. /** Sets the colour of the text. */
  50550. void setColour (const Colour& newColour);
  50551. /** Returns the current text colour. */
  50552. const Colour& getColour() const noexcept { return colour; }
  50553. /** Sets the font to use.
  50554. Note that the font height and horizontal scale are actually based upon the position
  50555. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  50556. the height and scale control point will be moved to match the dimensions of the font supplied;
  50557. if it is false, then the new font's height and scale are ignored.
  50558. */
  50559. void setFont (const Font& newFont, bool applySizeAndScale);
  50560. /** Changes the justification of the text within the bounding box. */
  50561. void setJustification (const Justification& newJustification);
  50562. /** Returns the parallelogram that defines the text bounding box. */
  50563. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50564. /** Sets the bounding box that contains the text. */
  50565. void setBoundingBox (const RelativeParallelogram& newBounds);
  50566. /** Returns the point within the bounds that defines the font's size and scale. */
  50567. const RelativePoint& getFontSizeControlPoint() const noexcept { return fontSizeControlPoint; }
  50568. /** Sets the control point that defines the font's height and horizontal scale.
  50569. This position is a point within the bounding box parallelogram, whose Y position (relative
  50570. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  50571. and its X defines the font's horizontal scale.
  50572. */
  50573. void setFontSizeControlPoint (const RelativePoint& newPoint);
  50574. /** @internal */
  50575. void paint (Graphics& g);
  50576. /** @internal */
  50577. Drawable* createCopy() const;
  50578. /** @internal */
  50579. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50580. /** @internal */
  50581. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50582. /** @internal */
  50583. static const Identifier valueTreeType;
  50584. /** @internal */
  50585. const Rectangle<float> getDrawableBounds() const;
  50586. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  50587. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50588. {
  50589. public:
  50590. ValueTreeWrapper (const ValueTree& state);
  50591. const String getText() const;
  50592. void setText (const String& newText, UndoManager* undoManager);
  50593. Value getTextValue (UndoManager* undoManager);
  50594. const Colour getColour() const;
  50595. void setColour (const Colour& newColour, UndoManager* undoManager);
  50596. const Justification getJustification() const;
  50597. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  50598. const Font getFont() const;
  50599. void setFont (const Font& newFont, UndoManager* undoManager);
  50600. Value getFontValue (UndoManager* undoManager);
  50601. const RelativeParallelogram getBoundingBox() const;
  50602. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50603. const RelativePoint getFontSizeControlPoint() const;
  50604. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  50605. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  50606. };
  50607. private:
  50608. RelativeParallelogram bounds;
  50609. RelativePoint fontSizeControlPoint;
  50610. Point<float> resolvedPoints[3];
  50611. Font font, scaledFont;
  50612. String text;
  50613. Colour colour;
  50614. Justification justification;
  50615. friend class Drawable::Positioner<DrawableText>;
  50616. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50617. void recalculateCoordinates (Expression::Scope*);
  50618. void refreshBounds();
  50619. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  50620. DrawableText& operator= (const DrawableText&);
  50621. JUCE_LEAK_DETECTOR (DrawableText);
  50622. };
  50623. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  50624. /*** End of inlined file: juce_DrawableText.h ***/
  50625. #endif
  50626. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  50627. #endif
  50628. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  50629. /*** Start of inlined file: juce_GlowEffect.h ***/
  50630. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  50631. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  50632. /**
  50633. A component effect that adds a coloured blur around the component's contents.
  50634. (This will only work on non-opaque components).
  50635. @see Component::setComponentEffect, DropShadowEffect
  50636. */
  50637. class JUCE_API GlowEffect : public ImageEffectFilter
  50638. {
  50639. public:
  50640. /** Creates a default 'glow' effect.
  50641. To customise its appearance, use the setGlowProperties() method.
  50642. */
  50643. GlowEffect();
  50644. /** Destructor. */
  50645. ~GlowEffect();
  50646. /** Sets the glow's radius and colour.
  50647. The radius is how large the blur should be, and the colour is
  50648. used to render it (for a less intense glow, lower the colour's
  50649. opacity).
  50650. */
  50651. void setGlowProperties (float newRadius,
  50652. const Colour& newColour);
  50653. /** @internal */
  50654. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  50655. private:
  50656. float radius;
  50657. Colour colour;
  50658. JUCE_LEAK_DETECTOR (GlowEffect);
  50659. };
  50660. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  50661. /*** End of inlined file: juce_GlowEffect.h ***/
  50662. #endif
  50663. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  50664. #endif
  50665. #ifndef __JUCE_FONT_JUCEHEADER__
  50666. #endif
  50667. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  50668. #endif
  50669. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  50670. #endif
  50671. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  50672. #endif
  50673. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  50674. #endif
  50675. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  50676. #endif
  50677. #ifndef __JUCE_LINE_JUCEHEADER__
  50678. #endif
  50679. #ifndef __JUCE_PATH_JUCEHEADER__
  50680. #endif
  50681. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  50682. /*** Start of inlined file: juce_PathIterator.h ***/
  50683. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  50684. #define __JUCE_PATHITERATOR_JUCEHEADER__
  50685. /**
  50686. Flattens a Path object into a series of straight-line sections.
  50687. Use one of these to iterate through a Path object, and it will convert
  50688. all the curves into line sections so it's easy to render or perform
  50689. geometric operations on.
  50690. @see Path
  50691. */
  50692. class JUCE_API PathFlatteningIterator
  50693. {
  50694. public:
  50695. /** Creates a PathFlatteningIterator.
  50696. After creation, use the next() method to initialise the fields in the
  50697. object with the first line's position.
  50698. @param path the path to iterate along
  50699. @param transform a transform to apply to each point in the path being iterated
  50700. @param tolerance the amount by which the curves are allowed to deviate from the lines
  50701. into which they are being broken down - a higher tolerance contains
  50702. less lines, so can be generated faster, but will be less smooth.
  50703. */
  50704. PathFlatteningIterator (const Path& path,
  50705. const AffineTransform& transform = AffineTransform::identity,
  50706. float tolerance = defaultTolerance);
  50707. /** Destructor. */
  50708. ~PathFlatteningIterator();
  50709. /** Fetches the next line segment from the path.
  50710. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  50711. so that they describe the new line segment.
  50712. @returns false when there are no more lines to fetch.
  50713. */
  50714. bool next();
  50715. float x1; /**< The x position of the start of the current line segment. */
  50716. float y1; /**< The y position of the start of the current line segment. */
  50717. float x2; /**< The x position of the end of the current line segment. */
  50718. float y2; /**< The y position of the end of the current line segment. */
  50719. /** Indicates whether the current line segment is closing a sub-path.
  50720. If the current line is the one that connects the end of a sub-path
  50721. back to the start again, this will be true.
  50722. */
  50723. bool closesSubPath;
  50724. /** The index of the current line within the current sub-path.
  50725. E.g. you can use this to see whether the line is the first one in the
  50726. subpath by seeing if it's 0.
  50727. */
  50728. int subPathIndex;
  50729. /** Returns true if the current segment is the last in the current sub-path. */
  50730. bool isLastInSubpath() const noexcept;
  50731. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  50732. static const float defaultTolerance;
  50733. private:
  50734. const Path& path;
  50735. const AffineTransform transform;
  50736. float* points;
  50737. const float toleranceSquared;
  50738. float subPathCloseX, subPathCloseY;
  50739. const bool isIdentityTransform;
  50740. HeapBlock <float> stackBase;
  50741. float* stackPos;
  50742. size_t index, stackSize;
  50743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  50744. };
  50745. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  50746. /*** End of inlined file: juce_PathIterator.h ***/
  50747. #endif
  50748. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  50749. #endif
  50750. #ifndef __JUCE_POINT_JUCEHEADER__
  50751. #endif
  50752. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  50753. #endif
  50754. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  50755. #endif
  50756. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  50757. /*** Start of inlined file: juce_CameraDevice.h ***/
  50758. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  50759. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  50760. #if JUCE_USE_CAMERA || DOXYGEN
  50761. /**
  50762. Controls any video capture devices that might be available.
  50763. Use getAvailableDevices() to list the devices that are attached to the
  50764. system, then call openDevice to open one for use. Once you have a CameraDevice
  50765. object, you can get a viewer component from it, and use its methods to
  50766. stream to a file or capture still-frames.
  50767. */
  50768. class JUCE_API CameraDevice
  50769. {
  50770. public:
  50771. /** Destructor. */
  50772. virtual ~CameraDevice();
  50773. /** Returns a list of the available cameras on this machine.
  50774. You can open one of these devices by calling openDevice().
  50775. */
  50776. static const StringArray getAvailableDevices();
  50777. /** Opens a camera device.
  50778. The index parameter indicates which of the items returned by getAvailableDevices()
  50779. to open.
  50780. The size constraints allow the method to choose between different resolutions if
  50781. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  50782. then these will be ignored.
  50783. */
  50784. static CameraDevice* openDevice (int deviceIndex,
  50785. int minWidth = 128, int minHeight = 64,
  50786. int maxWidth = 1024, int maxHeight = 768);
  50787. /** Returns the name of this device */
  50788. const String getName() const { return name; }
  50789. /** Creates a component that can be used to display a preview of the
  50790. video from this camera.
  50791. */
  50792. Component* createViewerComponent();
  50793. /** Starts recording video to the specified file.
  50794. You should use getFileExtension() to find out the correct extension to
  50795. use for your filename.
  50796. If the file exists, it will be deleted before the recording starts.
  50797. This method may not start recording instantly, so if you need to know the
  50798. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  50799. after the recording has finished.
  50800. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  50801. or may not be used, depending on the driver.
  50802. */
  50803. void startRecordingToFile (const File& file, int quality = 2);
  50804. /** Stops recording, after a call to startRecordingToFile().
  50805. */
  50806. void stopRecording();
  50807. /** Returns the file extension that should be used for the files
  50808. that you pass to startRecordingToFile().
  50809. This may be platform-specific, e.g. ".mov" or ".avi".
  50810. */
  50811. static const String getFileExtension();
  50812. /** After calling stopRecording(), this method can be called to return the timestamp
  50813. of the first frame that was written to the file.
  50814. */
  50815. const Time getTimeOfFirstRecordedFrame() const;
  50816. /**
  50817. Receives callbacks with images from a CameraDevice.
  50818. @see CameraDevice::addListener
  50819. */
  50820. class JUCE_API Listener
  50821. {
  50822. public:
  50823. Listener() {}
  50824. virtual ~Listener() {}
  50825. /** This method is called when a new image arrives.
  50826. This may be called by any thread, so be careful about thread-safety,
  50827. and make sure that you process the data as quickly as possible to
  50828. avoid glitching!
  50829. */
  50830. virtual void imageReceived (const Image& image) = 0;
  50831. };
  50832. /** Adds a listener to receive images from the camera.
  50833. Be very careful not to delete the listener without first removing it by calling
  50834. removeListener().
  50835. */
  50836. void addListener (Listener* listenerToAdd);
  50837. /** Removes a listener that was previously added with addListener().
  50838. */
  50839. void removeListener (Listener* listenerToRemove);
  50840. protected:
  50841. /** @internal */
  50842. CameraDevice (const String& name, int index);
  50843. private:
  50844. void* internal;
  50845. bool isRecording;
  50846. String name;
  50847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  50848. };
  50849. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  50850. typedef CameraDevice::Listener CameraImageListener;
  50851. #endif
  50852. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  50853. /*** End of inlined file: juce_CameraDevice.h ***/
  50854. #endif
  50855. #ifndef __JUCE_IMAGE_JUCEHEADER__
  50856. #endif
  50857. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50858. /*** Start of inlined file: juce_ImageCache.h ***/
  50859. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50860. #define __JUCE_IMAGECACHE_JUCEHEADER__
  50861. /**
  50862. A global cache of images that have been loaded from files or memory.
  50863. If you're loading an image and may need to use the image in more than one
  50864. place, this is used to allow the same image to be shared rather than loading
  50865. multiple copies into memory.
  50866. Another advantage is that after images are released, they will be kept in
  50867. memory for a few seconds before it is actually deleted, so if you're repeatedly
  50868. loading/deleting the same image, it'll reduce the chances of having to reload it
  50869. each time.
  50870. @see Image, ImageFileFormat
  50871. */
  50872. class JUCE_API ImageCache
  50873. {
  50874. public:
  50875. /** Loads an image from a file, (or just returns the image if it's already cached).
  50876. If the cache already contains an image that was loaded from this file,
  50877. that image will be returned. Otherwise, this method will try to load the
  50878. file, add it to the cache, and return it.
  50879. Remember that the image returned is shared, so drawing into it might
  50880. affect other things that are using it! If you want to draw on it, first
  50881. call Image::duplicateIfShared()
  50882. @param file the file to try to load
  50883. @returns the image, or null if it there was an error loading it
  50884. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50885. */
  50886. static const Image getFromFile (const File& file);
  50887. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  50888. If the cache already contains an image that was loaded from this block of memory,
  50889. that image will be returned. Otherwise, this method will try to load the
  50890. file, add it to the cache, and return it.
  50891. Remember that the image returned is shared, so drawing into it might
  50892. affect other things that are using it! If you want to draw on it, first
  50893. call Image::duplicateIfShared()
  50894. @param imageData the block of memory containing the image data
  50895. @param dataSize the data size in bytes
  50896. @returns the image, or an invalid image if it there was an error loading it
  50897. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50898. */
  50899. static const Image getFromMemory (const void* imageData, int dataSize);
  50900. /** Checks the cache for an image with a particular hashcode.
  50901. If there's an image in the cache with this hashcode, it will be returned,
  50902. otherwise it will return an invalid image.
  50903. @param hashCode the hash code that was associated with the image by addImageToCache()
  50904. @see addImageToCache
  50905. */
  50906. static const Image getFromHashCode (int64 hashCode);
  50907. /** Adds an image to the cache with a user-defined hash-code.
  50908. The image passed-in will be referenced (not copied) by the cache, so it's probably
  50909. a good idea not to draw into it after adding it, otherwise this will affect all
  50910. instances of it that may be in use.
  50911. @param image the image to add
  50912. @param hashCode the hash-code to associate with it
  50913. @see getFromHashCode
  50914. */
  50915. static void addImageToCache (const Image& image, int64 hashCode);
  50916. /** Changes the amount of time before an unused image will be removed from the cache.
  50917. By default this is about 5 seconds.
  50918. */
  50919. static void setCacheTimeout (int millisecs);
  50920. private:
  50921. class Pimpl;
  50922. friend class Pimpl;
  50923. ImageCache();
  50924. ~ImageCache();
  50925. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  50926. };
  50927. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  50928. /*** End of inlined file: juce_ImageCache.h ***/
  50929. #endif
  50930. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50931. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  50932. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50933. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50934. /**
  50935. Represents a filter kernel to use in convoluting an image.
  50936. @see Image::applyConvolution
  50937. */
  50938. class JUCE_API ImageConvolutionKernel
  50939. {
  50940. public:
  50941. /** Creates an empty convulution kernel.
  50942. @param size the length of each dimension of the kernel, so e.g. if the size
  50943. is 5, it will create a 5x5 kernel
  50944. */
  50945. ImageConvolutionKernel (int size);
  50946. /** Destructor. */
  50947. ~ImageConvolutionKernel();
  50948. /** Resets all values in the kernel to zero. */
  50949. void clear();
  50950. /** Returns one of the kernel values. */
  50951. float getKernelValue (int x, int y) const noexcept;
  50952. /** Sets the value of a specific cell in the kernel.
  50953. The x and y parameters must be in the range 0 < x < getKernelSize().
  50954. @see setOverallSum
  50955. */
  50956. void setKernelValue (int x, int y, float value) noexcept;
  50957. /** Rescales all values in the kernel to make the total add up to a fixed value.
  50958. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  50959. */
  50960. void setOverallSum (float desiredTotalSum);
  50961. /** Multiplies all values in the kernel by a value. */
  50962. void rescaleAllValues (float multiplier);
  50963. /** Intialises the kernel for a gaussian blur.
  50964. @param blurRadius this may be larger or smaller than the kernel's actual
  50965. size but this will obviously be wasteful or clip at the
  50966. edges. Ideally the kernel should be just larger than
  50967. (blurRadius * 2).
  50968. */
  50969. void createGaussianBlur (float blurRadius);
  50970. /** Returns the size of the kernel.
  50971. E.g. if it's a 3x3 kernel, this returns 3.
  50972. */
  50973. int getKernelSize() const { return size; }
  50974. /** Applies the kernel to an image.
  50975. @param destImage the image that will receive the resultant convoluted pixels.
  50976. @param sourceImage the source image to read from - this can be the same image as
  50977. the destination, but if different, it must be exactly the same
  50978. size and format.
  50979. @param destinationArea the region of the image to apply the filter to
  50980. */
  50981. void applyToImage (Image& destImage,
  50982. const Image& sourceImage,
  50983. const Rectangle<int>& destinationArea) const;
  50984. private:
  50985. HeapBlock <float> values;
  50986. const int size;
  50987. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  50988. };
  50989. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50990. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  50991. #endif
  50992. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50993. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  50994. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50995. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50996. /**
  50997. Base-class for codecs that can read and write image file formats such
  50998. as PNG, JPEG, etc.
  50999. This class also contains static methods to make it easy to load images
  51000. from files, streams or from memory.
  51001. @see Image, ImageCache
  51002. */
  51003. class JUCE_API ImageFileFormat
  51004. {
  51005. protected:
  51006. /** Creates an ImageFormat. */
  51007. ImageFileFormat() {}
  51008. public:
  51009. /** Destructor. */
  51010. virtual ~ImageFileFormat() {}
  51011. /** Returns a description of this file format.
  51012. E.g. "JPEG", "PNG"
  51013. */
  51014. virtual const String getFormatName() = 0;
  51015. /** Returns true if the given stream seems to contain data that this format
  51016. understands.
  51017. The format class should only read the first few bytes of the stream and sniff
  51018. for header bytes that it understands.
  51019. @see decodeImage
  51020. */
  51021. virtual bool canUnderstand (InputStream& input) = 0;
  51022. /** Tries to decode and return an image from the given stream.
  51023. This will be called for an image format after calling its canUnderStand() method
  51024. to see if it can handle the stream.
  51025. @param input the stream to read the data from. The stream will be positioned
  51026. at the start of the image data (but this may not necessarily
  51027. be position 0)
  51028. @returns the image that was decoded, or an invalid image if it fails.
  51029. @see loadFrom
  51030. */
  51031. virtual const Image decodeImage (InputStream& input) = 0;
  51032. /** Attempts to write an image to a stream.
  51033. To specify extra information like encoding quality, there will be appropriate parameters
  51034. in the subclasses of the specific file types.
  51035. @returns true if it nothing went wrong.
  51036. */
  51037. virtual bool writeImageToStream (const Image& sourceImage,
  51038. OutputStream& destStream) = 0;
  51039. /** Tries the built-in decoders to see if it can find one to read this stream.
  51040. There are currently built-in decoders for PNG, JPEG and GIF formats.
  51041. The object that is returned should not be deleted by the caller.
  51042. @see canUnderstand, decodeImage, loadFrom
  51043. */
  51044. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  51045. /** Tries to load an image from a stream.
  51046. This will use the findImageFormatForStream() method to locate a suitable
  51047. codec, and use that to load the image.
  51048. @returns the image that was decoded, or an invalid image if it fails.
  51049. */
  51050. static const Image loadFrom (InputStream& input);
  51051. /** Tries to load an image from a file.
  51052. This will use the findImageFormatForStream() method to locate a suitable
  51053. codec, and use that to load the image.
  51054. @returns the image that was decoded, or an invalid image if it fails.
  51055. */
  51056. static const Image loadFrom (const File& file);
  51057. /** Tries to load an image from a block of raw image data.
  51058. This will use the findImageFormatForStream() method to locate a suitable
  51059. codec, and use that to load the image.
  51060. @returns the image that was decoded, or an invalid image if it fails.
  51061. */
  51062. static const Image loadFrom (const void* rawData,
  51063. const int numBytesOfData);
  51064. };
  51065. /**
  51066. A subclass of ImageFileFormat for reading and writing PNG files.
  51067. @see ImageFileFormat, JPEGImageFormat
  51068. */
  51069. class JUCE_API PNGImageFormat : public ImageFileFormat
  51070. {
  51071. public:
  51072. PNGImageFormat();
  51073. ~PNGImageFormat();
  51074. const String getFormatName();
  51075. bool canUnderstand (InputStream& input);
  51076. const Image decodeImage (InputStream& input);
  51077. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51078. };
  51079. /**
  51080. A subclass of ImageFileFormat for reading and writing JPEG files.
  51081. @see ImageFileFormat, PNGImageFormat
  51082. */
  51083. class JUCE_API JPEGImageFormat : public ImageFileFormat
  51084. {
  51085. public:
  51086. JPEGImageFormat();
  51087. ~JPEGImageFormat();
  51088. /** Specifies the quality to be used when writing a JPEG file.
  51089. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  51090. any negative value is "default" quality
  51091. */
  51092. void setQuality (float newQuality);
  51093. const String getFormatName();
  51094. bool canUnderstand (InputStream& input);
  51095. const Image decodeImage (InputStream& input);
  51096. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51097. private:
  51098. float quality;
  51099. };
  51100. /**
  51101. A subclass of ImageFileFormat for reading GIF files.
  51102. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  51103. */
  51104. class JUCE_API GIFImageFormat : public ImageFileFormat
  51105. {
  51106. public:
  51107. GIFImageFormat();
  51108. ~GIFImageFormat();
  51109. const String getFormatName();
  51110. bool canUnderstand (InputStream& input);
  51111. const Image decodeImage (InputStream& input);
  51112. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51113. };
  51114. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51115. /*** End of inlined file: juce_ImageFileFormat.h ***/
  51116. #endif
  51117. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  51118. #endif
  51119. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51120. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  51121. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51122. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51123. /**
  51124. A class to take care of the logic involved with the loading/saving of some kind
  51125. of document.
  51126. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  51127. functions you need for documents that get saved to a file, so this class attempts
  51128. to abstract most of the boring stuff.
  51129. Your subclass should just implement all the pure virtual methods, and you can
  51130. then use the higher-level public methods to do the load/save dialogs, to warn the user
  51131. about overwriting files, etc.
  51132. The document object keeps track of whether it has changed since it was last saved or
  51133. loaded, so when you change something, call its changed() method. This will set a
  51134. flag so it knows it needs saving, and will also broadcast a change message using the
  51135. ChangeBroadcaster base class.
  51136. @see ChangeBroadcaster
  51137. */
  51138. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  51139. {
  51140. public:
  51141. /** Creates a FileBasedDocument.
  51142. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  51143. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  51144. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  51145. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  51146. */
  51147. FileBasedDocument (const String& fileExtension,
  51148. const String& fileWildCard,
  51149. const String& openFileDialogTitle,
  51150. const String& saveFileDialogTitle);
  51151. /** Destructor. */
  51152. virtual ~FileBasedDocument();
  51153. /** Returns true if the changed() method has been called since the file was
  51154. last saved or loaded.
  51155. @see resetChangedFlag, changed
  51156. */
  51157. bool hasChangedSinceSaved() const { return changedSinceSave; }
  51158. /** Called to indicate that the document has changed and needs saving.
  51159. This method will also trigger a change message to be sent out using the
  51160. ChangeBroadcaster base class.
  51161. After calling the method, the hasChangedSinceSaved() method will return true, until
  51162. it is reset either by saving to a file or using the resetChangedFlag() method.
  51163. @see hasChangedSinceSaved, resetChangedFlag
  51164. */
  51165. virtual void changed();
  51166. /** Sets the state of the 'changed' flag.
  51167. The 'changed' flag is set to true when the changed() method is called - use this method
  51168. to reset it or to set it without also broadcasting a change message.
  51169. @see changed, hasChangedSinceSaved
  51170. */
  51171. void setChangedFlag (bool hasChanged);
  51172. /** Tries to open a file.
  51173. If the file opens correctly, the document's file (see the getFile() method) is set
  51174. to this new one; if it fails, the document's file is left unchanged, and optionally
  51175. a message box is shown telling the user there was an error.
  51176. @returns true if the new file loaded successfully
  51177. @see loadDocument, loadFromUserSpecifiedFile
  51178. */
  51179. bool loadFrom (const File& fileToLoadFrom,
  51180. bool showMessageOnFailure);
  51181. /** Asks the user for a file and tries to load it.
  51182. This will pop up a dialog box using the title, file extension and
  51183. wildcard specified in the document's constructor, and asks the user
  51184. for a file. If they pick one, the loadFrom() method is used to
  51185. try to load it, optionally showing a message if it fails.
  51186. @returns true if a file was loaded; false if the user cancelled or if they
  51187. picked a file which failed to load correctly
  51188. @see loadFrom
  51189. */
  51190. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  51191. /** A set of possible outcomes of one of the save() methods
  51192. */
  51193. enum SaveResult
  51194. {
  51195. savedOk = 0, /**< indicates that a file was saved successfully. */
  51196. userCancelledSave, /**< indicates that the user aborted the save operation. */
  51197. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  51198. };
  51199. /** Tries to save the document to the last file it was saved or loaded from.
  51200. This will always try to write to the file, even if the document isn't flagged as
  51201. having changed.
  51202. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  51203. true, it will prompt the user to pick a file, as if
  51204. saveAsInteractive() was called.
  51205. @param showMessageOnFailure if true it will show a warning message when if the
  51206. save operation fails
  51207. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  51208. */
  51209. SaveResult save (bool askUserForFileIfNotSpecified,
  51210. bool showMessageOnFailure);
  51211. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  51212. it if they say yes.
  51213. If you've got a document open and want to close it (e.g. to quit the app), this is the
  51214. method to call.
  51215. If the document doesn't need saving it'll return the value savedOk so
  51216. you can go ahead and delete the document.
  51217. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  51218. return savedOk, so again, you can safely delete the document.
  51219. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  51220. close-document operation.
  51221. And if they click "save changes", it'll try to save and either return savedOk, or
  51222. failedToWriteToFile if there was a problem.
  51223. @see save, saveAs, saveAsInteractive
  51224. */
  51225. SaveResult saveIfNeededAndUserAgrees();
  51226. /** Tries to save the document to a specified file.
  51227. If this succeeds, it'll also change the document's internal file (as returned by
  51228. the getFile() method). If it fails, the file will be left unchanged.
  51229. @param newFile the file to try to write to
  51230. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  51231. the user first if they want to overwrite it
  51232. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  51233. use the saveAsInteractive() method to ask the user for a
  51234. filename
  51235. @param showMessageOnFailure if true and the write operation fails, it'll show
  51236. a message box to warn the user
  51237. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  51238. */
  51239. SaveResult saveAs (const File& newFile,
  51240. bool warnAboutOverwritingExistingFiles,
  51241. bool askUserForFileIfNotSpecified,
  51242. bool showMessageOnFailure);
  51243. /** Prompts the user for a filename and tries to save to it.
  51244. This will pop up a dialog box using the title, file extension and
  51245. wildcard specified in the document's constructor, and asks the user
  51246. for a file. If they pick one, the saveAs() method is used to try to save
  51247. to this file.
  51248. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  51249. the user first if they want to overwrite it
  51250. @see saveIfNeededAndUserAgrees, save, saveAs
  51251. */
  51252. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  51253. /** Returns the file that this document was last successfully saved or loaded from.
  51254. When the document object is created, this will be set to File::nonexistent.
  51255. It is changed when one of the load or save methods is used, or when setFile()
  51256. is used to explicitly set it.
  51257. */
  51258. const File getFile() const { return documentFile; }
  51259. /** Sets the file that this document thinks it was loaded from.
  51260. This won't actually load anything - it just changes the file stored internally.
  51261. @see getFile
  51262. */
  51263. void setFile (const File& newFile);
  51264. protected:
  51265. /** Overload this to return the title of the document.
  51266. This is used in message boxes, filenames and file choosers, so it should be
  51267. something sensible.
  51268. */
  51269. virtual const String getDocumentTitle() = 0;
  51270. /** This method should try to load your document from the given file.
  51271. If it fails, it should return an error message. If it succeeds, it should return
  51272. an empty string.
  51273. */
  51274. virtual const String loadDocument (const File& file) = 0;
  51275. /** This method should try to write your document to the given file.
  51276. If it fails, it should return an error message. If it succeeds, it should return
  51277. an empty string.
  51278. */
  51279. virtual const String saveDocument (const File& file) = 0;
  51280. /** This is used for dialog boxes to make them open at the last folder you
  51281. were using.
  51282. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  51283. the last document that was used - you might want to store this value
  51284. in a static variable, or even in your application's properties. It should
  51285. be a global setting rather than a property of this object.
  51286. This method works very well in conjunction with a RecentlyOpenedFilesList
  51287. object to manage your recent-files list.
  51288. As a default value, it's ok to return File::nonexistent, and the document
  51289. object will use a sensible one instead.
  51290. @see RecentlyOpenedFilesList
  51291. */
  51292. virtual const File getLastDocumentOpened() = 0;
  51293. /** This is used for dialog boxes to make them open at the last folder you
  51294. were using.
  51295. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  51296. the last document that was used - you might want to store this value
  51297. in a static variable, or even in your application's properties. It should
  51298. be a global setting rather than a property of this object.
  51299. This method works very well in conjunction with a RecentlyOpenedFilesList
  51300. object to manage your recent-files list.
  51301. @see RecentlyOpenedFilesList
  51302. */
  51303. virtual void setLastDocumentOpened (const File& file) = 0;
  51304. private:
  51305. File documentFile;
  51306. bool changedSinceSave;
  51307. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  51308. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  51309. };
  51310. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51311. /*** End of inlined file: juce_FileBasedDocument.h ***/
  51312. #endif
  51313. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  51314. #endif
  51315. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51316. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  51317. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51318. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51319. /**
  51320. Manages a set of files for use as a list of recently-opened documents.
  51321. This is a handy class for holding your list of recently-opened documents, with
  51322. helpful methods for things like purging any non-existent files, automatically
  51323. adding them to a menu, and making persistence easy.
  51324. @see File, FileBasedDocument
  51325. */
  51326. class JUCE_API RecentlyOpenedFilesList
  51327. {
  51328. public:
  51329. /** Creates an empty list.
  51330. */
  51331. RecentlyOpenedFilesList();
  51332. /** Destructor. */
  51333. ~RecentlyOpenedFilesList();
  51334. /** Sets a limit for the number of files that will be stored in the list.
  51335. When addFile() is called, then if there is no more space in the list, the
  51336. least-recently added file will be dropped.
  51337. @see getMaxNumberOfItems
  51338. */
  51339. void setMaxNumberOfItems (int newMaxNumber);
  51340. /** Returns the number of items that this list will store.
  51341. @see setMaxNumberOfItems
  51342. */
  51343. int getMaxNumberOfItems() const noexcept { return maxNumberOfItems; }
  51344. /** Returns the number of files in the list.
  51345. The most recently added file is always at index 0.
  51346. */
  51347. int getNumFiles() const;
  51348. /** Returns one of the files in the list.
  51349. The most recently added file is always at index 0.
  51350. */
  51351. const File getFile (int index) const;
  51352. /** Returns an array of all the absolute pathnames in the list.
  51353. */
  51354. const StringArray& getAllFilenames() const noexcept { return files; }
  51355. /** Clears all the files from the list. */
  51356. void clear();
  51357. /** Adds a file to the list.
  51358. The file will be added at index 0. If this file is already in the list, it will
  51359. be moved up to index 0, but a file can only appear once in the list.
  51360. If the list already contains the maximum number of items that is permitted, the
  51361. least-recently added file will be dropped from the end.
  51362. */
  51363. void addFile (const File& file);
  51364. /** Removes a file from the list. */
  51365. void removeFile (const File& file);
  51366. /** Checks each of the files in the list, removing any that don't exist.
  51367. You might want to call this after reloading a list of files, or before putting them
  51368. on a menu.
  51369. */
  51370. void removeNonExistentFiles();
  51371. /** Adds entries to a menu, representing each of the files in the list.
  51372. This is handy for creating an "open recent file..." menu in your app. The
  51373. menu items are numbered consecutively starting with the baseItemId value,
  51374. and can either be added as complete pathnames, or just the last part of the
  51375. filename.
  51376. If dontAddNonExistentFiles is true, then each file will be checked and only those
  51377. that exist will be added.
  51378. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  51379. pointers to file objects. Any files that appear in this list will not be added to the
  51380. menu - the reason for this is that you might have a number of files already open, so
  51381. might not want these to be shown in the menu.
  51382. It returns the number of items that were added.
  51383. */
  51384. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  51385. int baseItemId,
  51386. bool showFullPaths,
  51387. bool dontAddNonExistentFiles,
  51388. const File** filesToAvoid = nullptr);
  51389. /** Returns a string that encapsulates all the files in the list.
  51390. The string that is returned can later be passed into restoreFromString() in
  51391. order to recreate the list. This is handy for persisting your list, e.g. in
  51392. a PropertiesFile object.
  51393. @see restoreFromString
  51394. */
  51395. const String toString() const;
  51396. /** Restores the list from a previously stringified version of the list.
  51397. Pass in a stringified version created with toString() in order to persist/restore
  51398. your list.
  51399. @see toString
  51400. */
  51401. void restoreFromString (const String& stringifiedVersion);
  51402. private:
  51403. StringArray files;
  51404. int maxNumberOfItems;
  51405. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  51406. };
  51407. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51408. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  51409. #endif
  51410. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  51411. #endif
  51412. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51413. /*** Start of inlined file: juce_SystemClipboard.h ***/
  51414. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51415. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51416. /**
  51417. Handles reading/writing to the system's clipboard.
  51418. */
  51419. class JUCE_API SystemClipboard
  51420. {
  51421. public:
  51422. /** Copies a string of text onto the clipboard */
  51423. static void copyTextToClipboard (const String& text);
  51424. /** Gets the current clipboard's contents.
  51425. Obviously this might have come from another app, so could contain
  51426. anything..
  51427. */
  51428. static const String getTextFromClipboard();
  51429. };
  51430. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51431. /*** End of inlined file: juce_SystemClipboard.h ***/
  51432. #endif
  51433. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  51434. #endif
  51435. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  51436. #endif
  51437. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  51438. /*** Start of inlined file: juce_UnitTest.h ***/
  51439. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  51440. #define __JUCE_UNITTEST_JUCEHEADER__
  51441. class UnitTestRunner;
  51442. /**
  51443. This is a base class for classes that perform a unit test.
  51444. To write a test using this class, your code should look something like this:
  51445. @code
  51446. class MyTest : public UnitTest
  51447. {
  51448. public:
  51449. MyTest() : UnitTest ("Foobar testing") {}
  51450. void runTest()
  51451. {
  51452. beginTest ("Part 1");
  51453. expect (myFoobar.doesSomething());
  51454. expect (myFoobar.doesSomethingElse());
  51455. beginTest ("Part 2");
  51456. expect (myOtherFoobar.doesSomething());
  51457. expect (myOtherFoobar.doesSomethingElse());
  51458. ...etc..
  51459. }
  51460. };
  51461. // Creating a static instance will automatically add the instance to the array
  51462. // returned by UnitTest::getAllTests(), so the test will be included when you call
  51463. // UnitTestRunner::runAllTests()
  51464. static MyTest test;
  51465. @endcode
  51466. To run a test, use the UnitTestRunner class.
  51467. @see UnitTestRunner
  51468. */
  51469. class JUCE_API UnitTest
  51470. {
  51471. public:
  51472. /** Creates a test with the given name. */
  51473. explicit UnitTest (const String& name);
  51474. /** Destructor. */
  51475. virtual ~UnitTest();
  51476. /** Returns the name of the test. */
  51477. const String getName() const noexcept { return name; }
  51478. /** Runs the test, using the specified UnitTestRunner.
  51479. You shouldn't need to call this method directly - use
  51480. UnitTestRunner::runTests() instead.
  51481. */
  51482. void performTest (UnitTestRunner* runner);
  51483. /** Returns the set of all UnitTest objects that currently exist. */
  51484. static Array<UnitTest*>& getAllTests();
  51485. /** You can optionally implement this method to set up your test.
  51486. This method will be called before runTest().
  51487. */
  51488. virtual void initialise();
  51489. /** You can optionally implement this method to clear up after your test has been run.
  51490. This method will be called after runTest() has returned.
  51491. */
  51492. virtual void shutdown();
  51493. /** Implement this method in your subclass to actually run your tests.
  51494. The content of your implementation should call beginTest() and expect()
  51495. to perform the tests.
  51496. */
  51497. virtual void runTest() = 0;
  51498. /** Tells the system that a new subsection of tests is beginning.
  51499. This should be called from your runTest() method, and may be called
  51500. as many times as you like, to demarcate different sets of tests.
  51501. */
  51502. void beginTest (const String& testName);
  51503. /** Checks that the result of a test is true, and logs this result.
  51504. In your runTest() method, you should call this method for each condition that
  51505. you want to check, e.g.
  51506. @code
  51507. void runTest()
  51508. {
  51509. beginTest ("basic tests");
  51510. expect (x + y == 2);
  51511. expect (getThing() == someThing);
  51512. ...etc...
  51513. }
  51514. @endcode
  51515. If testResult is true, a pass is logged; if it's false, a failure is logged.
  51516. If the failure message is specified, it will be written to the log if the test fails.
  51517. */
  51518. void expect (bool testResult, const String& failureMessage = String::empty);
  51519. /** Compares two values, and if they don't match, prints out a message containing the
  51520. expected and actual result values.
  51521. */
  51522. template <class ValueType>
  51523. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  51524. {
  51525. const bool result = (actual == expected);
  51526. if (! result)
  51527. {
  51528. if (failureMessage.isNotEmpty())
  51529. failureMessage << " -- ";
  51530. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  51531. }
  51532. expect (result, failureMessage);
  51533. }
  51534. /** Writes a message to the test log.
  51535. This can only be called from within your runTest() method.
  51536. */
  51537. void logMessage (const String& message);
  51538. private:
  51539. const String name;
  51540. UnitTestRunner* runner;
  51541. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  51542. };
  51543. /**
  51544. Runs a set of unit tests.
  51545. You can instantiate one of these objects and use it to invoke tests on a set of
  51546. UnitTest objects.
  51547. By using a subclass of UnitTestRunner, you can intercept logging messages and
  51548. perform custom behaviour when each test completes.
  51549. @see UnitTest
  51550. */
  51551. class JUCE_API UnitTestRunner
  51552. {
  51553. public:
  51554. /** */
  51555. UnitTestRunner();
  51556. /** Destructor. */
  51557. virtual ~UnitTestRunner();
  51558. /** Runs a set of tests.
  51559. The tests are performed in order, and the results are logged. To run all the
  51560. registered UnitTest objects that exist, use runAllTests().
  51561. */
  51562. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  51563. /** Runs all the UnitTest objects that currently exist.
  51564. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  51565. */
  51566. void runAllTests (bool assertOnFailure);
  51567. /** Contains the results of a test.
  51568. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  51569. it contains details of the number of subsequent UnitTest::expect() calls that are
  51570. made.
  51571. */
  51572. struct TestResult
  51573. {
  51574. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  51575. String unitTestName;
  51576. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  51577. String subcategoryName;
  51578. /** The number of UnitTest::expect() calls that succeeded. */
  51579. int passes;
  51580. /** The number of UnitTest::expect() calls that failed. */
  51581. int failures;
  51582. /** A list of messages describing the failed tests. */
  51583. StringArray messages;
  51584. };
  51585. /** Returns the number of TestResult objects that have been performed.
  51586. @see getResult
  51587. */
  51588. int getNumResults() const noexcept;
  51589. /** Returns one of the TestResult objects that describes a test that has been run.
  51590. @see getNumResults
  51591. */
  51592. const TestResult* getResult (int index) const noexcept;
  51593. protected:
  51594. /** Called when the list of results changes.
  51595. You can override this to perform some sort of behaviour when results are added.
  51596. */
  51597. virtual void resultsUpdated();
  51598. /** Logs a message about the current test progress.
  51599. By default this just writes the message to the Logger class, but you could override
  51600. this to do something else with the data.
  51601. */
  51602. virtual void logMessage (const String& message);
  51603. private:
  51604. friend class UnitTest;
  51605. UnitTest* currentTest;
  51606. String currentSubCategory;
  51607. OwnedArray <TestResult, CriticalSection> results;
  51608. bool assertOnFailure;
  51609. void beginNewTest (UnitTest* test, const String& subCategory);
  51610. void endTest();
  51611. void addPass();
  51612. void addFail (const String& failureMessage);
  51613. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  51614. };
  51615. #endif // __JUCE_UNITTEST_JUCEHEADER__
  51616. /*** End of inlined file: juce_UnitTest.h ***/
  51617. #endif
  51618. #endif
  51619. /*** End of inlined file: juce_app_includes.h ***/
  51620. #endif
  51621. #if JUCE_MSVC
  51622. #pragma warning (pop)
  51623. #pragma pack (pop)
  51624. #endif
  51625. END_JUCE_NAMESPACE
  51626. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  51627. #ifdef JUCE_NAMESPACE
  51628. // this will obviously save a lot of typing, but can be disabled by
  51629. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  51630. using namespace JUCE_NAMESPACE;
  51631. /* On the Mac, these symbols are defined in the Mac libraries, so
  51632. these macros make it easier to reference them without writing out
  51633. the namespace every time.
  51634. If you run into difficulties where these macros interfere with the contents
  51635. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  51636. the comments in that file for more information.
  51637. */
  51638. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  51639. #define Component JUCE_NAMESPACE::Component
  51640. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  51641. #define Point JUCE_NAMESPACE::Point
  51642. #define Button JUCE_NAMESPACE::Button
  51643. #endif
  51644. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  51645. it easier to use the juce version explicitly.
  51646. If you run into difficulties where this macro interferes with other 3rd party header
  51647. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  51648. file for more information.
  51649. */
  51650. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  51651. #define Rectangle JUCE_NAMESPACE::Rectangle
  51652. #endif
  51653. #endif
  51654. #endif
  51655. /* Easy autolinking to the right JUCE libraries under win32.
  51656. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  51657. including this header file.
  51658. */
  51659. #if JUCE_MSVC
  51660. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  51661. /** If you want your application to link to Juce as a DLL instead of
  51662. a static library (on win32), just define the JUCE_DLL macro before
  51663. including juce.h
  51664. */
  51665. #ifdef JUCE_DLL
  51666. #if JUCE_DEBUG
  51667. #define AUTOLINKEDLIB "JUCE_debug.lib"
  51668. #else
  51669. #define AUTOLINKEDLIB "JUCE.lib"
  51670. #endif
  51671. #else
  51672. #if JUCE_DEBUG
  51673. #ifdef _WIN64
  51674. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  51675. #else
  51676. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  51677. #endif
  51678. #else
  51679. #ifdef _WIN64
  51680. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  51681. #else
  51682. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  51683. #endif
  51684. #endif
  51685. #endif
  51686. #pragma comment(lib, AUTOLINKEDLIB)
  51687. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  51688. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  51689. #endif
  51690. // Auto-link the other win32 libs that are needed by library calls..
  51691. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  51692. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  51693. // Auto-links to various win32 libs that are needed by library calls..
  51694. #pragma comment(lib, "kernel32.lib")
  51695. #pragma comment(lib, "user32.lib")
  51696. #pragma comment(lib, "shell32.lib")
  51697. #pragma comment(lib, "gdi32.lib")
  51698. #pragma comment(lib, "vfw32.lib")
  51699. #pragma comment(lib, "comdlg32.lib")
  51700. #pragma comment(lib, "winmm.lib")
  51701. #pragma comment(lib, "wininet.lib")
  51702. #pragma comment(lib, "ole32.lib")
  51703. #pragma comment(lib, "oleaut32.lib")
  51704. #pragma comment(lib, "advapi32.lib")
  51705. #pragma comment(lib, "ws2_32.lib")
  51706. #pragma comment(lib, "version.lib")
  51707. #pragma comment(lib, "shlwapi.lib")
  51708. #pragma comment(lib, "imm32.lib")
  51709. #ifdef _NATIVE_WCHAR_T_DEFINED
  51710. #ifdef _DEBUG
  51711. #pragma comment(lib, "comsuppwd.lib")
  51712. #else
  51713. #pragma comment(lib, "comsuppw.lib")
  51714. #endif
  51715. #else
  51716. #ifdef _DEBUG
  51717. #pragma comment(lib, "comsuppd.lib")
  51718. #else
  51719. #pragma comment(lib, "comsupp.lib")
  51720. #endif
  51721. #endif
  51722. #if JUCE_OPENGL
  51723. #pragma comment(lib, "OpenGL32.Lib")
  51724. #pragma comment(lib, "GlU32.Lib")
  51725. #endif
  51726. #if JUCE_QUICKTIME
  51727. #pragma comment (lib, "QTMLClient.lib")
  51728. #endif
  51729. #if JUCE_USE_CAMERA
  51730. #pragma comment (lib, "Strmiids.lib")
  51731. #pragma comment (lib, "wmvcore.lib")
  51732. #endif
  51733. #if JUCE_DIRECT2D
  51734. #pragma comment (lib, "Dwrite.lib")
  51735. #pragma comment (lib, "D2d1.lib")
  51736. #endif
  51737. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  51738. #endif
  51739. #endif
  51740. #endif
  51741. #endif // __JUCE_JUCEHEADER__
  51742. /*** End of inlined file: juce.h ***/
  51743. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__